From caa13dd4d1d4d50739fd2312d7222660e20c2fff Mon Sep 17 00:00:00 2001 From: vunamtien Date: Wed, 19 Jan 2022 04:43:29 +0700 Subject: [PATCH] compute x509 certificate thumbprint (#11717) Co-authored-by: tienvn4 --- .../com/baeldung/certificate/Thumbprint.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 core-java-modules/core-java-security-3/src/main/java/com/baeldung/certificate/Thumbprint.java diff --git a/core-java-modules/core-java-security-3/src/main/java/com/baeldung/certificate/Thumbprint.java b/core-java-modules/core-java-security-3/src/main/java/com/baeldung/certificate/Thumbprint.java new file mode 100644 index 0000000000..7ccf1091c6 --- /dev/null +++ b/core-java-modules/core-java-security-3/src/main/java/com/baeldung/certificate/Thumbprint.java @@ -0,0 +1,38 @@ +package com.baeldung.certificate; + +import org.apache.commons.codec.digest.DigestUtils; + +import javax.xml.bind.DatatypeConverter; +import java.io.FileInputStream; +import java.io.IOException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateEncodingException; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + +public class Thumbprint { + + public static void main(String[] args) throws CertificateException, IOException, NoSuchAlgorithmException { + X509Certificate certObject = getCertObject("baeldung.pem"); + System.out.println(getThumbprint(certObject)); + } + + 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); + } + } + + 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(); + } + + private static String getThumbprintWithApache(X509Certificate cert) throws CertificateEncodingException { + return DigestUtils.sha1Hex(cert.getEncoded()); + } +}