如何获取Android设备上安装的另一个应用程序的证书sha256哈希? 我正在使用How to get APK signing signature?中提到的解决方案。但它提供的签名似乎不是证书哈希。
答案 0 :(得分:2)
尽管有名称,但这是证书的公开部分。
我的CWAC-Security库有a SignatureUtils
class with a getSignatureHash()
method,用于计算此信息的SHA-256哈希值。结果与使用Java的keytool
从密钥库转储哈希的结果相同。
核心代码相当短:
public static String getSignatureHash(Context ctxt, String packageName)
throws NameNotFoundException, NoSuchAlgorithmException {
MessageDigest md=MessageDigest.getInstance("SHA-256");
Signature sig=
ctxt.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_SIGNATURES).signatures[0];
return(toHexStringWithColons(md.digest(sig.toByteArray())));
}
// based on https://stackoverflow.com/a/2197650/115145
public static String toHexStringWithColons(byte[] bytes) {
char[] hexArray=
{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B',
'C', 'D', 'E', 'F' };
char[] hexChars=new char[(bytes.length * 3) - 1];
int v;
for (int j=0; j < bytes.length; j++) {
v=bytes[j] & 0xFF;
hexChars[j * 3]=hexArray[v / 16];
hexChars[j * 3 + 1]=hexArray[v % 16];
if (j < bytes.length - 1) {
hexChars[j * 3 + 2]=':';
}
}
return new String(hexChars);
}
答案 1 :(得分:0)
您可以尝试这样的事情:
PackageManager packageManager = getPackageManager();
int flag = PackageManager.GET_SIGNATURES;
PackageInfo packageInfo = null;
try {
packageInfo = packageManager.getPackageInfo(packageName, flag);
byte[] certificates = packageInfo.signatures[0].toByteArray();
InputStream input = new ByteArrayInputStream(certificates);
CertificateFactory factory = CertificateFactory.getInstance("X509");
X509Certificate certificate = (X509Certificate) factory.generateCertificate(input);
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
byte[] publicKey = messageDigest.digest(certificate.getEncoded());
} catch (PackageManager.NameNotFoundException exception) {
exception.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e2) {
e2.printStackTrace();
}