在IE中查看证书信息,在证书详细信息标签页中的最下面有证书的“微缩图算法”和“微缩图”2个值。
微缩图的概念是微软自己定义的,其原理就是对证书的编码信息再做一次sha1的摘要。注:sha1就是微缩图算法,该值也可能为MD5.
在java的Certificate类中,不能直接得到微缩图,需要根据微缩图的算法和其原理得到微缩图。
具体代码如下:
package com.wiflish.framework.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.X509Certificate; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * 获取证书微缩图的工具类。 * * @author wiflish * */ public class TummbPrintUtils { private static final Log logger = LogFactory.getLog(TummbPrintUtils.class); /** * 获取微缩图。 * * @param cert 证书。 * @param thumAlg 微缩图算法。 * @param delimiter 分隔符,如:":" * @return 返回微缩图。 */ public static String getThumbprint(X509Certificate cert, String thumAlg, String delimiter) { if (cert == null) { return null; } if (thumAlg == null || thumAlg.length() == 0) { return null; } String thumbPrint = ""; try { MessageDigest md = MessageDigest.getInstance(thumAlg); byte rawDigest[] = md.digest(cert.getEncoded()); thumbPrint = getHex(rawDigest, delimiter); } catch (NoSuchAlgorithmException e) { thumbPrint = ""; logger.error("不支持[" + thumAlg + "]算法!", e); } catch (CertificateEncodingException e) { thumbPrint = ""; logger.error("证书编码异常!", e); } return thumbPrint; } /** * 获取证书微缩图,默认使用sha1算法,默认微缩图字符串不进行分隔。 * * @param cert 证书 * @return */ public static String getThumbprint(X509Certificate cert) { return getThumbprint(cert, "sha1", null); } /** * 获取证书微缩图。默认使用sha1算法,使用指定的分隔符进行分隔。 * * @param cert 证书。 * @param delimiter 指定的分隔符,如:":"。 * @return */ public static String getThumbprint(X509Certificate cert, String delimiter) { return getThumbprint(cert, "sha1", delimiter); } /** * 将将证书摘要转换为16进制字符串,即得到证书微缩图。 * * @param buf * @param delimiter * @return */ private static String getHex(byte buf[], String delimiter) { String result = ""; if (buf == null) { return ""; } String defaultDelimiter = ""; if (delimiter != null && delimiter.length() > 0) { defaultDelimiter = delimiter; } for (int i = 0; i < buf.length; i++) { if (i > 0) { result += defaultDelimiter; } short sValue = buf[i]; int iValue = 0; iValue += sValue; String converted = Integer.toHexString(iValue); if (converted.length() > 2) { converted = converted.substring(converted.length() - 2); } // 只有1位数时,前面补0。 else if (converted.length() < 2) { converted = ("0" + converted); } // 将微缩图都转换为大写字母。 result += converted.toUpperCase(); } return result; } }