fal*_*tto 6 java android androidhttpclient android-security
我正在阅读Android上的证书固定,我很困惑.我没有使用okhttp或改装,所以我必须手动完成.这里有一个教程:https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#Android ,他们将证书添加到可信证书列表中.但是当我们检查服务器上安装的证书的sha256的base64时,还有另一个教程:https://medium.com/@appmattus/android-security-ssl-pinning-1db8acb6621e 哪种方法是正确的?为什么我们不能像浏览器那样从头中的服务器接收sha256并将其存储在某个地方?
我会推荐这个
\n https://www.paypal-engineering.com/2015/10/14/key-pinning-in-mobile-applications/\n
安卓方法
\n\n最简单的方法是使用基于 JSEE 的方法,如下所示。这是 Android 的推荐方法。method\xe2\x80\x99s 输入参数是 HTTPS 连接和目标 URL 的一组有效引脚。
\n\nprivate boolean validatePinning(HttpsURLConnection conn, Set<String> validPins) {\n try {\n Certificate[] certs = conn.getServerCertificates();\n MessageDigest md = MessageDigest.getInstance("SHA-256");\n for (Certificate cert : certs) {\n X509Certificate x509Certificate = (X509Certificate) cert;\n byte[] key = x509Certificate.getPublicKey().getEncoded();\n md.update(key, 0, key.length);\n byte[] hashBytes = md.digest();\n StringBuffer hexHash = new StringBuffer();\n for (int i = 0; i < hashBytes.length; i++) {\n int k = 0xFF & hashBytes[i];\n String tmp = (k<16)? "0" : "";\n tmp += Integer.toHexString(0xFF & hashBytes[i]);\n hexHash.append(tmp);\n }\n if (validPins.contains(hexHash.toString())) {\n return true;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n return false;\n}\nRun Code Online (Sandbox Code Playgroud)\n\n引脚被声明为字符串。例如:
\n\n声明关键引脚
\n\nprivate static final Set<String> PINS = new HashSet<String>(Arrays.asList(\n new String[]{\n "996b510ce2380da9c738...87cb13c9ec409941",\n "ba47e83b1ccf0939bb40d2...edf856ba892c06481a"}));\nRun Code Online (Sandbox Code Playgroud)\n\n利用上述方法,这里有一个示例,展示了如何使用它。下面突出显示了唯一相关的部分。
\n\n使用按键固定的示例
\n\nprotected String doInBackground(String... urls) {\n try {\n /** Test pinning given the target URL **/\n /** for now use pre-defined endpoint URL instead or urls[0] **/\n Log.i(LOG_TAG, "==> PinningTestTask launched.");\n String dest = defaultEndpoint;\n URL targetURL = new URL(dest);\n HttpsURLConnection targetConnection = (HttpsURLConnection) targetURL.openConnection();\n targetConnection.connect();\n if (validatePinning(targetConnection, PINS)) {\n final String updateText = "Key pinning succeded for: " + dest;\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(updateText);\n }\n });\n } else {\n final String updateText = "Key pinning failed for: " + dest;\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(updateText);\n }\n });\n }\n } catch (Exception e) {\n e.printStackTrace();\n final String updateText = "Key pinning failed for: " + dest + "\\n" + e.toString();\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n textView.setText(updateText);\n }\n });\n }\n return null;\n}\nRun Code Online (Sandbox Code Playgroud)\n