Advertisement
tolikpunkoff

get X.509 certificate fingerprint (hash)

Jan 8th, 2020
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.75 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.IO;
  5. using System.Security.Cryptography;
  6. using System.Security.Cryptography.X509Certificates;
  7.  
  8. namespace GetFingerprintExample
  9. {
  10.     public static class Fingerpint
  11.     {
  12.         public static string GetCertFingerprint(string CertFile, string AlgName)
  13.         {
  14.             if (!File.Exists(CertFile))
  15.             {
  16.                 Console.WriteLine("File not found.");
  17.                 return null;
  18.             }
  19.  
  20.             //load certificate
  21.             X509Certificate2 X509 = null;
  22.             try
  23.             {
  24.                 X509 = new X509Certificate2(CertFile);
  25.             }
  26.             catch (Exception ex)
  27.             {
  28.                 Console.WriteLine(ex.Message);
  29.                 return null;
  30.             }
  31.             byte[] cert = X509.GetRawCertData();
  32.            
  33.             //create hash algorithm
  34.             HashAlgorithm alg = null;
  35.             switch (AlgName.ToUpperInvariant())
  36.             {
  37.                 case "MD5": alg = MD5.Create(); break;
  38.                 case "SHA1": alg = SHA1.Create(); break;
  39.                 case "SHA256": alg = SHA256.Create(); break;
  40.                 case "SHA384": alg = SHA384.Create(); break;
  41.                 case "SHA512": alg = SHA512.Create(); break;
  42.                 default:
  43.                     {
  44.                         Console.WriteLine("Unknow algorithm.");
  45.                         return null;
  46.                     }
  47.             }
  48.            
  49.             //calculate hash and return value
  50.             byte[] hash = alg.ComputeHash(cert);
  51.             string hex = BitConverter.ToString(hash).ToLowerInvariant().
  52.                 Replace("-", "");
  53.  
  54.             return hex;
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement