簡體   English   中英

C#生成證書Thumbprint(Java實現)

[英]Generating a certificate Thumbprint in C# (Implemented in Java)

我已經實現了一個簡單的 one liner,它在 java 中生成證書指紋

X509Certificate cert = readCertFromFile(path);   //I read the certificate here
byte[] digest = DigestUtils.sha256(cert.getEncoded());  //I calculate hash of the cert

我想在 C# 中實現相同的功能。我嘗試使用 C# 的 X509Certificate class 讀取證書並生成 hash 值,但它不同於通過 java 生成的值。89828Encoded78 中是否有 java 的 X509Certificate.get828Encoded78 的實現? java 中的 getEncoded() 返回

此證書的編碼形式。 假定每種證書類型只有一種編碼形式; 例如,X.509 證書將被編碼為 ASN.1 DER。

我很感激這方面的任何幫助。

在 C# 中,您可以使用 System.Security.Cryptography.X509Certificates 命名空間中的 X509Certificate2 class 從文件中讀取證書並獲取其編碼形式。

X509Certificate2 cert = new X509Certificate2(path);

// 獲取證書的編碼形式

byte[] encodedCert = cert.RawData;

要計算編碼證書的 SHA-256 hash,您可以使用 System.Security.Cryptography 命名空間中的 SHA256 class。 以下是如何使用 SHA256 class 計算編碼證書的 SHA-256 hash 的示例:

using (SHA256 sha256 = SHA256.Create()) {
byte[] hash = sha256.ComputeHash(encodedCert); }

獲取證書的 SHA-256 指紋的最直接方法是

byte[] thumbprint = cert.GetCertHash(HashAlgorithmName.SHA256);

或者,如果你想要十六進制版本:

string thumbprint = cert.GetCertHashString(HashAlgorithmName.SHA256);

這相當於下面的代碼,更像是 Java 的方法:

byte[] thumbprint = SHA256.HashData(cert.RawData);

不同之處在於GetCertHash例程不需要復制 RawData 值(屬性訪問器需要這樣做),因此它的性能更高一些。

            // Load the certificate from a file
            X509Certificate2 certificate = new X509Certificate2("certificate.pfx", "password");

            // Generate the thumbprint
            string thumbprint = certificate.Thumbprint;

            // Print the thumbprint
            Console.WriteLine(thumbprint);

X509Certificate2 Class

以下來自同一示例的示例也使用了文件讀取模式。

using System;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.IO;
using System.Security.Cryptography.X509Certificates;

class CertInfo
{
    //Reads a file.
    internal static byte[] ReadFile (string fileName)
    {
        FileStream f = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        int size = (int)f.Length;
        byte[] data = new byte[size];
        size = f.Read(data, 0, size);
        f.Close();
        return data;
    }
    //Main method begins here.
    static void Main(string[] args)
    {
        //Test for correct number of arguments.
        if (args.Length < 1)
        {
            Console.WriteLine("Usage: CertInfo <filename>");
            return;
        }
        try
        {
            X509Certificate2 x509 = new X509Certificate2();
            //Create X509Certificate2 object from .cer file.
            byte[] rawData = ReadFile(args[0]);
            x509.Import(rawData);

            //Print to console information contained in the certificate.
            Console.WriteLine("{0}Subject: {1}{0}", Environment.NewLine, x509.Subject);
            Console.WriteLine("{0}Issuer: {1}{0}", Environment.NewLine, x509.Issuer);
            Console.WriteLine("{0}Version: {1}{0}", Environment.NewLine, x509.Version);
            Console.WriteLine("{0}Valid Date: {1}{0}", Environment.NewLine, x509.NotBefore);
            Console.WriteLine("{0}Expiry Date: {1}{0}", Environment.NewLine, x509.NotAfter);
            Console.WriteLine("{0}Thumbprint: {1}{0}", Environment.NewLine, x509.Thumbprint);
            Console.WriteLine("{0}Serial Number: {1}{0}", Environment.NewLine, x509.SerialNumber);
            Console.WriteLine("{0}Friendly Name: {1}{0}", Environment.NewLine, x509.PublicKey.Oid.FriendlyName);
            Console.WriteLine("{0}Public Key Format: {1}{0}", Environment.NewLine, x509.PublicKey.EncodedKeyValue.Format(true));
            Console.WriteLine("{0}Raw Data Length: {1}{0}", Environment.NewLine, x509.RawData.Length);
            Console.WriteLine("{0}Certificate to string: {1}{0}", Environment.NewLine, x509.ToString(true));
            Console.WriteLine("{0}Certificate to XML String: {1}{0}", Environment.NewLine, x509.PublicKey.Key.ToXmlString(false));

            //Add the certificate to a X509Store.
            X509Store store = new X509Store();
            store.Open(OpenFlags.MaxAllowed);
            store.Add(x509);
            store.Close();
        }
        catch (DirectoryNotFoundException)
        {
               Console.WriteLine("Error: The directory specified could not be found.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: A file in the directory could not be accessed.");
        }
        catch (NullReferenceException)
        {
            Console.WriteLine("File must be a .cer file. Program does not have access to that type of file.");
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM