如何比较 java.security.cert.X509Certificate 的不同实现
我在应用程序的不同部分使用 bouncycastle org.bouncycastle.jce.provider.X509CertificateObject 和 sun.security.x509.X509CertImpl,有时我需要比较它们的相等性,equals() 方法不起作用以及 getSubjectDN 等方法().getName() 为每个实现显示不同的结果,如何在不使用二进制 DER 或 PEM 的情况下比较这些证书的相等性 比较?
I'm using bouncycastle org.bouncycastle.jce.provider.X509CertificateObject and sun.security.x509.X509CertImpl in different parts of my app, and sometimes I need to compare them for equality, equals() method is not working and methods like getSubjectDN().getName() display different results for each of these implementations, how could I compare these certificates for equality without going to binary DER or PEM comparison?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
判断两个证书是否相等的安全方法是比较它们的二进制表示形式。 Bouncy Castle 和 Sun 的实现都具有
getEncoded
方法。您可以使用 Arrays#equals 来比较两者。您应该避免比较SubjectDN 或IssuerDN 字符串,即使在二进制级别上它们完全相等,表示形式也很可能不同。在与 .NET 交互时,我必须通过艰难的方式来学习这一点 - 对于更奇特的 RDN,各个相对可分辨名称(例如 CN、O、OU...)的命名是不同的。我的建议是留在二进制级别进行比较,棘手的高级比较很容易出错并且更难以维护。
A safe way to tell if two certificates are equal is to compare their binary representation. Both the Bouncy Castle and Sun's implementation feature a
getEncoded
method. You could compare the two with Arrays#equals.You should avoid comparing SubjectDN or IssuerDN strings, it is quite possible that the representation differs even if on the binary level they are perfectly equal. I had to learn this the hard way when interfacing with .NET - the naming of the individual relative distinguished names (such as CN, O, OU...) was different for more exotic RDNs. My advice would be to stay on the binary level for comparison, tricky high-level comparisons are error-prone and harder to maintain.
另一种方法是使用证书数据的 MD5 或 SHA-1 哈希值进行比较。这就是证书指纹的生成方式,并且可以保证两者的平等性。
Another way would be to compare using MD5 or SHA-1 hashes of the certificate data. This is how the certificate fingerprint is generated, and would give you assurances of the equality of the two.
您可以尝试将本例客户端(BouncyCastle)中的证书转换为 java.security
You can try to convert the certificate in this case client (BouncyCastle) to java.security