使用OpenSSL命令手动计算公钥的哈希值,并截取前32个字节作为Android SSL Pinning所需的哈希值。
示例代码:
openssl x509 -in cert.crt -pubkey -noout > pub.pem
openssl rsa -in pub.pem -pubin -outform der | openssl dgst -sha256 -binary | xxd -p
public static String getCertificateSHA256Fingerprint(Context context) throws PackageManager.NameNotFoundException, NoSuchAlgorithmException {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
int flags = PackageManager.GET_SIGNATURES;
PackageInfo packageInfo = pm.getPackageInfo(packageName, flags);
Signature[] signatures = packageInfo.signatures;
byte[] cert = signatures[0].toByteArray();
MessageDigest digest = MessageDigest.getInstance("SHA256");
byte[] hash = digest.digest(cert);
return bytesToHex(hash);
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}