如何在Java中检索/计算X509证书的指纹? [英] How to retrieve/compute an X509 certificate's thumbprint in Java?

查看:492
本文介绍了如何在Java中检索/计算X509证书的指纹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java客户端,它调用一个Web服务操作,它接受证书指纹作为参数。我相信指纹是某种类型的SHA1散列,以十六进制字符串格式,证书的公钥,但我不知道。

I have a java client that is calling a web service operation which takes a certificate "thumbprint" as a parameter. I believe the thumbprint is some kind of SHA1 hash, in hexadecimal string format, of the cert's public key, but I'm not sure.

.NET框架似乎包括一个获取此值的简单方法( X509Certificate2.Thumbprint 属性)。在Windows中查看.cer文件的属性还会显示指纹,如下所示:

The .NET framework seems to include a simple way to get this value (X509Certificate2.Thumbprint property). Viewing a .cer file's properties in Windows also displays the thumbprint, which looks like:

a6 9c fd b0 58 0d a4 ee ae 9a 47 75 24 c3 0b 9f 5d b6 1c 77

因此我的问题是:在Java中检索或计算此指纹字符串,如果我有一个 java.security.cert.X509Certificate

My question is therefore: Does anybody know how to retrieve or compute this thumbprint string within Java, if I have an instance of a java.security.cert.X509Certificate?

推荐答案

Thumbprint是一个.NET东西。为什么在Java中需要它?

Thumbprint is a .NET thing. Why do you need it in Java?

它不是证书的一部分。它只是证书的 DER编码的SHA1哈希。您可以像这样轻松计算:

It's not part of certificate. It's simply SHA1 hash of the DER encoding of the certificate. You can calculate it easily like this,

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();
    }

}

这篇关于如何在Java中检索/计算X509证书的指纹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆