James James -4 years ago 256
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!

Answer Source

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 (...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download