通过我的证书是如何验证应用程序签名吗? [英] How to verify that app was signed by my certificate?
问题描述
我如何检查,如果我的应用程序的签名,我用签字的证书的签名相匹配?
How do I check if the signature of my app matches the signature of the certificate that I used to sign it?
这是我应该怎么能够获得证书指纹:
This is how I should be able to get the certificates fingerprint:
public String getCertificateFingerprint() throws NameNotFoundException, CertificateException, NoSuchAlgorithmException {
PackageManager pm = context.getPackageManager();
String packageName =context.getPackageName();
int flags = PackageManager.GET_SIGNATURES;
PackageInfo packageInfo = null;
packageInfo = pm.getPackageInfo(packageName, flags);
Signature[] signatures = packageInfo.signatures;
byte[] cert = signatures[0].toByteArray();
InputStream input = new ByteArrayInputStream(cert);
CertificateFactory cf = null;
cf = CertificateFactory.getInstance("X509");
X509Certificate c = null;
c = (X509Certificate) cf.generateCertificate(input);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] publicKey = md.digest(c.getPublicKey().getEncoded());
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < publicKey.length; i++) {
String appendString = Integer.toHexString(0xFF & publicKey[i]);
if (appendString.length() == 1)
hexString.append("0");
hexString.append(appendString);
}
return hexString.toString();
}
这是我应该能够得到我的证书的指纹:
This is how I should be able to get the fingerprint of my certificate:
keytool -v -list -keystore filenameandpath
我的问题是,这两个给回不同的结果。
可能有人指出什么我搞砸了?
My problem is, that these two give back different results. Could someone point out what I'm screwing up?
推荐答案
正在计算错误的数据的MD5哈希值。证书的指纹是原始证书的散列(MD5,SHA1,SHA256等)。即,你应该计算这些字节的哈希值:
You are computing the MD5 hash of the wrong data. The fingerprint of a certificate is a hash (MD5, SHA1, SHA256, etc.) of the raw certificate. I.e., you should be computing the hash of these bytes:
byte[] cert = signatures[0].toByteArray();
例如,下面的代码计算SHA1指纹,只是改变SHA1方式为MD5,如果你preFER。
E.g., the following computes a SHA1 fingerprint, just change SHA1 to MD5 if you prefer.
public String computeFingerPrint(final byte[] certRaw) {
String strResult = "";
MessageDigest md;
try {
md = MessageDigest.getInstance("SHA1");
md.update(certRaw);
for (byte b : md.digest()) {
strResult += Integer.toString(b & 0xff, 16);
}
strResult = strResult.toUpperCase(DATA_LOCALE);
}
catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return strResult;
}
这篇关于通过我的证书是如何验证应用程序签名吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!