简体   繁体   English

如何在C#中验证用于签名APK文件的链接证书

[英]How to verify a chained certificate used to sign an APK file in C#

This code fails every time I pass it an APK file that has a certification chain (intermediate and Root CA). 每当我通过带有验证链(中级和根CA)的APK文件时,此代码都会失败。 If the file is self-signed it works correctly. 如果文件是自签名的,则可以正常工作。

RSACryptoServiceProvider csp = (RSACryptoServiceProvider)Cert.PublicKey.Key;
bool verified = csp.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), vData)

"hash" is the sha1 digest of the signature file (SF) and vData the encrypted hash of a signature (CMSG_ENCRYPTED_DIGEST,), both are byte arrays. “哈希”是签名文件(SF)的sha1摘要,而vData是签名的加密哈希(CMSG_ENCRYPTED_DIGEST,),它们都是字节数组。

I will answer my own question after finding the answer. 找到答案后,我将回答我自己的问题。 The problem resides when specifying the digest method. 指定摘要方法时,问题仍然存在。

A X509 certificate uses two algorithms that may not coincide (SignatureAlgorithm.FriendlyName and PublicKey.Key.SignatureAlgorithm). X509证书使用两种可能不一致的算法(SignatureAlgorithm.FriendlyName和PublicKey.Key.SignatureAlgorithm)。 When verifying the hash you must make sure that it matches the SignatureAlgorithm of the certificate and not the algorithm used in the public key (which was my fault). 验证哈希时,必须确保它与证书的SignatureAlgorithm匹配,而不与公钥中使用的算法匹配(这是我的错)。

If in doubt, check both: 如有疑问,请同时检查:

                            if (cert.SignatureAlgorithm.FriendlyName.ToString().Contains("sha256"))
                        {
                            SHA256Managed sha256 = new SHA256Managed();
                            byte[] hash256 = sha256.ComputeHash(sig);
                            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
                            verify_all.Add(csp.VerifyHash(hash256, CryptoConfig.MapNameToOID("SHA256"), vData));
                        }

                        else if (cert.SignatureAlgorithm.FriendlyName.ToString().Contains("sha1"))
                        {
                            SHA1Managed Sha1 = new SHA1Managed();
                            byte[] hash1 = sha1.ComputeHash(sig);                                
                            RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key;
                            verify_all.Add(csp.VerifyHash(hash1, CryptoConfig.MapNameToOID("SHA256"), vData));
                        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM