如何获得SHA256证书指纹?

时间:2016-01-04 07:37:24

标签: c# x509certificate sha256

如何获取证书的SHA256指纹? SHA 256证书有两个指纹,我能够检索主指纹而不是SHA256。

2 个答案:

答案 0 :(得分:2)

如果您想获得证书的SHA256指纹,您必须做一些手动工作。内置Thumbprint属性仅限SHA1。

哟必须使用SHA256 class并对证书的内容进行计算哈希:

using System;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

namespace MyNamespace {
    class MyClass {
        public static String GetSha2Thumbprint(X509Certificate2 cert) {
            Byte[] hashBytes;
            using (var hasher = new SHA256Managed()) {
                hashBytes = hasher.ComputeHash(cert.RawData);
            }
            return hashBytes.Aggregate(String.Empty, (str, hashByte) => str + hashByte.ToString("x2"));
        }
    }
}

并在必要时将此代码转换为扩展方法。

答案 1 :(得分:0)

public static String GetSha2Thumbprint(X509Certificate2 cert)
        {
            Byte[] hashBytes;
            using (var hasher = new SHA256Managed())
            {
                hashBytes = hasher.ComputeHash(cert.RawData);
            }
            string result = BitConverter.ToString(hashBytes)
                // this will remove all the dashes in between each two haracters
            .Replace("-", string.Empty).ToLower();         
            return result;
        }
After getting the Hashbytes , you have to do the bit convertion.

此帖也帮助了我。 Hashing text with SHA-256 at Windows Forms