1. Overview
1.概述
A certificate’s thumbprint (or fingerprint) is the unique identifier of the certificate. It’s not part of the certificate, but it’s calculated from it.
证书的拇指印(或指纹)是证书的唯一标识符。它不是证书的一部分,但它是由它计算出来的。
In this short tutorial, we’ll see how to compute an X509 certificate’s thumbprint in Java.
在这个简短的教程中,我们将看到如何在Java中计算一个X509证书的拇指印。
2. Use Plain Java
2.使用普通的Java
First, let’s get an X509Certificate object from our certificate file:
首先,让我们从我们的证书文件中获得一个X509Certificate对象。
public static X509Certificate getCertObject(String filePath)
throws IOException, CertificateException {
try (FileInputStream is = new FileInputStream(filePath)) {
CertificateFactory certificateFactory = CertificateFactory
.getInstance("X.509");
return (X509Certificate) certificateFactory.generateCertificate(is);
}
}
Next, let’s get the thumbprint from this object:
接下来,让我们从这个对象中获取拇指指纹。
private static String getThumbprint(X509Certificate cert)
throws NoSuchAlgorithmException, CertificateEncodingException {
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(cert.getEncoded());
return DatatypeConverter.printHexBinary(md.digest()).toLowerCase();
}
For example, if we have an X509 certificate file named baeldung.pem, we can use the methods above to easily print its thumbprint:
例如,如果我们有一个名为baeldung.pem的X509证书文件,我们可以使用上述方法来轻松打印其缩略图。
X509Certificate certObject = getCertObject("baeldung.pem");
System.out.println(getThumbprint(certObject));
The result will look something like:
其结果将看起来像这样。
c9fa9f008655c8401ad27e213b985804854d928c
3. Use Apache Commons Codec
3.使用Apache Commons Codec
We can also use the DigestUtils class from the Apache Commons Codec library to achieve the same goal.
我们还可以使用Apache Commons Codec库中的DigestUtils类来实现同样的目标。
Let’s add a dependency to our pom.xml file:
让我们在我们的pom.xml文件中添加一个依赖项。
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.15</version>
</dependency>
Now, we simply use the sha1Hex() method to get the thumbprint from our X509Certificate object:
现在,我们只需使用sha1Hex()方法从我们的X509Certificate对象中获取拇指印。
DigestUtils.sha1Hex(certObject.getEncoded());
4. Conclusion
4.总结
In this quick tutorial, we’ve learned two ways to compute an X509 certificate’s thumbprint in Java.
在这个快速教程中,我们学习了两种在Java中计算X509证书拇指印的方法。
As always, the example code from this article can be found over on GitHub.
一如既往,本文中的示例代码可以在GitHub上找到over。