比较java中的两个公钥值

时间:2016-05-25 14:09:38

标签: java security

比较从服务器提取的公钥和java中本地存储的密钥的最佳方法是什么?

以下是获取公钥的代码

public static PublicKey getPublicKey(){

    String hostname = "www.google.com";
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();        
    SSLSocket socket = null;
    Certificate[] certs = null;
    try {
        socket = (SSLSocket) factory.createSocket(hostname, 443);
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        socket.startHandshake();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        certs = socket.getSession().getPeerCertificates();
    } catch (SSLPeerUnverifiedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Certificate cert = certs[0];
    PublicKey key = cert.getPublicKey();
    System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
    System.out.println("Public key \n" + key);
    System.out.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");

    return key;
}

我希望将响应中的公钥与本地存储的密钥进行比较,例如在文本文件中。

由于

2 个答案:

答案 0 :(得分:0)

使用equals()方法,如果它是您正在使用的对象的类,则在RSAPublicKeyImpl中实现。

答案 1 :(得分:0)

您需要使用'thumbprint'比较公钥,'thumbprint'是证书的唯一标识符。该指纹基本上是证书的SHA-1。

    public class X509 {

    public static void main(String[] args) {
        FileInputStream is;
        try {
            is = new FileInputStream("/tmp/certificate_x509.pem");
            CertificateFactory x509CertFact = CertificateFactory.getInstance("X.509");
            X509Certificate cert = (X509Certificate)x509CertFact.generateCertificate(is);
            String thumbprint = getThumbPrint(cert);
            System.out.println(thumbprint);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

    }

    public static String getThumbPrint(X509Certificate cert) 
        throws NoSuchAlgorithmException, CertificateEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] der = cert.getEncoded();
        md.update(der);
        byte[] digest = md.digest();
        return hexify(digest);

    }

    public static 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);

        for (int i = 0; i < bytes.length; ++i) {
            buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
            buf.append(hexDigits[bytes[i] & 0x0f]);
        }

        return buf.toString();
    }
}