Get Public Key Hash for a string
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
public class CryptoUtility
{
public static string GetPublicKeyHash(string publicKeyString)
{
SHA256 sha = new SHA256Managed();
byte[] bytes = HexToBin(publicKeyString);
byte[] hashvalue = sha.ComputeHash(bytes);
return Convert.ToBase64String(hashvalue);
}
public static byte[] HexToBin(string hexString)
{
if (hexString == null)
{
throw new ArgumentException("hexString cannot be null", "hexString");
}
if (!(hexString.Length % 2 == 0))
{
throw new ArgumentException("Inappropriate length in hexString.", "hexString");
}
if (Regex.IsMatch(hexString, "[^0-9A-F]+", RegexOptions.IgnoreCase))
{
throw new ArgumentException("Non-hex values in hexString.", "hexString");
}
int arraySize = System.Convert.ToInt32(hexString.Length / 2);
byte[] bytes = new byte[arraySize - 1];
int counter = 0;
for (int i = 0; i <= hexString.Length - 1; i += 2)
{
string hexValue = hexString.Substring(i, 2);
int intValue = Convert.ToInt32(hexValue, 16);
bytes[counter] = Convert.ToByte(intValue);
counter += 1;
}
return bytes;
}
}
Related examples in the same category