I have a java client that is calling a web service operation which takes a certificate "thumbprint" as a parameter. I believe the thumbprint is some kind of SHA1 hash, in hexadecimal string format, of the cert's public key, but I'm not sure.
The .NET framework seems to include a simple way to get this value (X509Certificate2.Thumbprint property). Viewing a .cer file's properties in Windows also displays the thumbprint, which looks like:
a6 9c fd b0 58 0d a4 ee ae 9a 47 75 24 c3 0b 9f 5d b6 1c 77
My question is therefore: Does anybody know how to retrieve or compute this thumbprint string within Java, if I have an instance of a java.security.cert.X509Certificate?
One-liner using Google's Guava
Using Apache Commons Codec you can do:
You can generate the thumbprint by using the openssl command, so example if you have the pem format of the certificate in a file (file.txt)
then:
cat file.txt | openssl x509 -sha1 -fingerprint
- this would generate the same thumbprintShort example without using any libraries.
The SHA-1 hash of the DER encoding of the certificate is what .NET is getting with X509Certificate2.Thumbprint.
As noted on the remarks on MSDN:
Java's standard library doesn't provide the thumbprint directly, but you can get it like this:
Here's a full worked example using a conveniently accessible PEM file:
Create stackoverflow.crt.pem:
Create X509.java:
Compile the program with Java 8:
Or Java 9 - due to modular JDK/JPMS - DataTypeConverter is not in java.base, but java.xml.bind, so you need to explicitly depend on it during your build:
Otherwise, on Java 9, you get this when you try to build it:
Run it with Java 8:
In Java 9 - due to modular JDK/JPMS - DataTypeConverter is not in java.base, but java.xml.bind, so you need to explicitly depend on it when running your program:
Otherwise, on Java 9, you get this when you try to run it:
Get the expected output:
Here's a simpler way: