Tom
Tom

Reputation: 1234

C# SHA-2 (512) Base64 encoded hash

Looking for a way to do the following in C# from a string.

public static String sha512Hex(byte[] data)

Calculates the SHA-512 digest and returns the value as a hex string.

Parameters: data - Data to digest Returns: SHA-512 digest as a hex string

    private static string GetSHA512(string text)
    {
        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        byte[] message = UE.GetBytes(text);
        SHA512Managed hashString = new SHA512Managed();
        string encodedData = Convert.ToBase64String(message);
        string hex = "";
        hashValue = hashString.ComputeHash(UE.GetBytes(encodedData));
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;
    }

Upvotes: 7

Views: 32159

Answers (3)

Erçin Dedeoğlu
Erçin Dedeoğlu

Reputation: 5383

Better memory management:

    public static string SHA512Hash(string value)
    {
        byte[] encryptedBytes;

        using (var hashTool = new SHA512Managed())
        {
            encryptedBytes = hashTool.ComputeHash(System.Text.Encoding.UTF8.GetBytes(string.Concat(value)));
            hashTool.Clear();
        }

        return Convert.ToBase64String(encryptedBytes);
    }

Upvotes: 0

Tom
Tom

Reputation: 1234

Got this to work. Taken from here and modified a bit.

    public static string CreateSHAHash(string Phrase)
    {
        SHA512Managed HashTool = new SHA512Managed();
        Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
        Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
        HashTool.Clear();
        return Convert.ToBase64String(EncryptedBytes);
    }

Upvotes: 12

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391634

Would System.Security.Cryptography.SHA512 be what you need?

var alg = SHA512.Create();
alg.ComputeHash(Encoding.UTF8.GetBytes("test"));
BitConverter.ToString(alg.Hash).Dump();

Executed in LINQPad produces:

EE-26-B0-DD-4A-F7-E7-49-AA-1A-8E-E3-C1-0A-E9-92-3F-61-89-80-77-2E-47-3F-88-19-A5-D4-94-0E-0D-B2-7A-C1-85-F8-A0-E1-D5-F8-4F-88-BC-88-7F-D6-7B-14-37-32-C3-04-CC-5F-A9-AD-8E-6F-57-F5-00-28-A8-FF

To create the method from your question:

public static string sha512Hex(byte[] data)
{
    using (var alg = SHA512.Create())
    {
        alg.ComputeHash(data);
        return BitConverter.ToString(alg.Hash);
    }
}

Upvotes: 20

Related Questions