jdk/src/share/classes/sun/security/x509/X509CertImpl.java
changeset 20177 8ea486a4f36e
parent 16492 4cd9aa345503
child 21819 8cd757e836d8
--- a/jdk/src/share/classes/sun/security/x509/X509CertImpl.java	Wed Sep 18 14:10:24 2013 +0100
+++ b/jdk/src/share/classes/sun/security/x509/X509CertImpl.java	Wed Sep 18 21:37:45 2013 +0800
@@ -37,6 +37,7 @@
 import java.security.cert.*;
 import java.security.cert.Certificate;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 
 import javax.security.auth.x500.X500Principal;
 
@@ -1913,4 +1914,45 @@
         }
         return false;
     }
+
+    private ConcurrentHashMap<String,String> fingerprints =
+            new ConcurrentHashMap<>(2);
+
+    public String getFingerprint(String algorithm) {
+        return fingerprints.computeIfAbsent(algorithm,
+                x -> getCertificateFingerPrint(x));
+    }
+
+    /**
+     * Gets the requested finger print of the certificate. The result
+     * only contains 0-9 and A-F. No small case, no colon.
+     */
+    private String getCertificateFingerPrint(String mdAlg) {
+        String fingerPrint = "";
+        try {
+            byte[] encCertInfo = getEncoded();
+            MessageDigest md = MessageDigest.getInstance(mdAlg);
+            byte[] digest = md.digest(encCertInfo);
+            StringBuffer buf = new StringBuffer();
+            for (int i = 0; i < digest.length; i++) {
+                byte2hex(digest[i], buf);
+            }
+            fingerPrint = buf.toString();
+        } catch (NoSuchAlgorithmException | CertificateEncodingException e) {
+            // ignored
+        }
+        return fingerPrint;
+    }
+
+    /**
+     * Converts a byte to hex digit and writes to the supplied buffer
+     */
+    private static void byte2hex(byte b, StringBuffer buf) {
+        char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
+                '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+        int high = ((b & 0xf0) >> 4);
+        int low = (b & 0x0f);
+        buf.append(hexChars[high]);
+        buf.append(hexChars[low]);
+    }
 }