How can I SHA512 a string in C#?

Your code is correct, but you should dispose of the SHA512Managed instance:

using (SHA512 shaM = new SHA512Managed())
{
   hash = shaM.ComputeHash(data);
}

512 bits are 64 bytes.

To convert a string to a byte array, you need to specify an encoding. UTF8 is okay if you want to create a hash code:

var data = Encoding.UTF8.GetBytes("text");    
using (...

This is from one of my projects:

public static string SHA512(string input)
{
    var bytes = System.Text.Encoding.UTF8.GetBytes(input);
    using (var hash = System.Security.Cryptography.SHA512.Create())
    {
        var hashedInputBytes = hash.ComputeHash(bytes);

        // Convert to text
        // StringBuilder Capacity is 128, because 512 bits / 8 bits in byte * 2 symbols for byte 
        var hashedInputStringBuilder = new System.Text.StringBuilder(128);
        foreach (var b in hashedInputBytes)
            hashedInputStringBuilder.Append(b.ToString("X2"));
        return hashedInputStringBuilder.ToString();
    }
}

Please, note:

  1. SHA512 object is disposed ('using' section), so we do not have any resource leaks.
  2. StringBuilder is used for efficient hex string building.

512/8 = 64, so 64 is indeed the correct size. Perhaps you want to convert it to hexadecimal after the SHA512 algorithm.

See also: How do you convert Byte Array to Hexadecimal String, and vice versa?

Tags:

C#

Hash