James James - 2 months ago 16x
ASP.NET (C#) Question

How can I SHA512 a string in C#?

I am trying to write a function to take a string and sha512 it like so?

public string SHA512(string input)
string hash;


return hash;

What should the magic be?

I tried the following, but
kept ending up as 64bytes long (not 128 as expected).

byte[] data = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
byte[] hash;
SHA512 shaM = new SHA512Managed();
hash = shaM.ComputeHash(data);

Thanks in advance!


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

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

512 bits are 64 bytes.

Do 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 (...