    001package cpw.mods.fml.common;
    002
    003import java.nio.ByteBuffer;
    004import java.security.MessageDigest;
    005import java.security.cert.Certificate;
    006
    007public class CertificateHelper {
    008
    009    private static final String HEXES = "0123456789abcdef";
    010
    011    public static String getFingerprint(Certificate certificate)
    012    {
    013        if (certificate == null)
    014        {
    015            return "NO VALID CERTIFICATE FOUND";
    016        }
    017        try
    018        {
    019            MessageDigest md = MessageDigest.getInstance("SHA-1");
    020            byte[] der = certificate.getEncoded();
    021            md.update(der);
    022            byte[] digest = md.digest();
    023            return hexify(digest);
    024        }
    025        catch (Exception e)
    026        {
    027            return null;
    028        }
    029    }
    030
    031    public static String getFingerprint(ByteBuffer buffer)
    032    {
    033        try
    034        {
    035            MessageDigest digest = MessageDigest.getInstance("SHA-1");
    036            digest.update(buffer);
    037            byte[] chksum = digest.digest();
    038            return hexify(chksum);
    039        }
    040        catch (Exception e)
    041        {
    042            return null;
    043        }
    044    }
    045
    046    private static String hexify(byte[] chksum)
    047    {
    048        final StringBuilder hex = new StringBuilder( 2 * chksum.length );
    049        for ( final byte b : chksum ) {
    050          hex.append(HEXES.charAt((b & 0xF0) >> 4))
    051             .append(HEXES.charAt((b & 0x0F)));
    052        }
    053        return hex.toString();
    054    }
    055
    056}