Friday, June 28, 2013

Generate MD5 thumbprint form security certificate

Recently I was involved in implementing keystore validation on default wso2carbon keystore. The main idea behind this implementaion was to make customer aware about security risks by leaving default JKS in production because wso2 keystore is publically available since we are an open source company.

During system validation what I did was obtain the primary keystore of the vendor and validate its MD5 thumbprint value with default wso2carbon certificate thumbprint value. This method used to generate the thumb print form an X509Certificate is interesting and I hope this will be useful to someone someday + me :)


/**
* Generate the MD5 thumbprint of the certificate
*
* @param certificate that we need the thumbprint
* @return MD5 thumbprint value
* @throws CertificateEncodingException
* @throws NoSuchAlgorithmException
*/
private String getCertFingerprint(X509Certificate certificate) throws CertificateEncodingException, NoSuchAlgorithmException {
MessageDigest digestValue = MessageDigest.getInstance("MD5");
byte[] der = certificate.getEncoded();
digestValue.update(der);
byte[] digestInBytes = digestValue.digest();
return hexify(digestInBytes);
}

/**
* Helper method to hexify a byte array.
* @param bytes
* @return hexadecimal representation
*/
private String hexify(byte bytes[]) {

char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBuffer buf = new StringBuffer(bytes.length * 2);

// appending : marks to make fingerprint more readable
for (int i = 0; i < bytes.length; ++i) {
buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
buf.append(hexDigits[bytes[i] & 0x0f] + ":");
}
// removing the last : value from the buffer string
buf.deleteCharAt(buf.length()-1);
return buf.toString();
}

No comments:

Post a Comment