Get Sha256 public key from certificate

2.2k views Asked by At

Currently, am working on client server application(Chat) am implementing security for server and clients, few of the client is written in java SMACK library, they are using TLS Pining for JAVA it needs sha2 hash [https://github.com/Flowdalic/java-pinning][1]

Server is implemented using C#, I have certificate on server side how can I get the sha2 public key with below format from the certificate, below is my code.

cer =new X509Certificate2(ConfigurationManager.AppSettings["CertificateName"],"123456");

string hellow= cer.GetCertHashString(); //it will return sha1 hash 

what I need is the below format and sha2-256 key from the certificate SHA2-256 key

83:F9:17:1E:06:A3:13:11:88:89:F7:D7:93:02:BD:1B:7A:20:42:EE:0C:FD:02:9A:BF:8D:D0:6F:FA:6C:D9:D3

1

There are 1 answers

0
bilal On BEST ANSWER

I have found the solution for my question, let me share.

If you want to get certificate's SHA256 thumbprint, you have to do some manual work. Built-in Thumbprint property is SHA1 only.

Yo have to use a SHA256 class and compute hash over certificate's content:

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 BitConverter.ToString(hashBytes).Replace("-", ":");
        }
    }
}