I am trying to write a function to take a string and sha512 it like so?
public string SHA512(string input)
{
string hash;
~magic~
return hash;
}
What should the magic be?
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:
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?
You might try these lines:
public static string GenSHA512(string s, bool l = false)
{
string r = "";
try
{
byte[] d = Encoding.UTF8.GetBytes(s);
using (SHA512 a = new SHA512Managed())
{
byte[] h = a.ComputeHash(d);
r = BitConverter.ToString(h).Replace("-", "");
}
r = (l ? r.ToLowerInvariant() : r);
}
catch
{
}
return r;
}
Instead of WinCrypt-API using System.Security.Cryptography, you can also use BouncyCastle:
public static byte[] SHA512(string text)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);
Org.BouncyCastle.Crypto.Digests.Sha512Digest digester = new Org.BouncyCastle.Crypto.Digests.Sha512Digest();
byte[] retValue = new byte[digester.GetDigestSize()];
digester.BlockUpdate(bytes, 0, bytes.Length);
digester.DoFinal(retValue, 0);
return retValue;
}
If you need the HMAC-version (to add authentication to the hash)
public static byte[] HmacSha512(string text, string key)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
var hmac = new Org.BouncyCastle.Crypto.Macs.HMac(new Org.BouncyCastle.Crypto.Digests.Sha512Digest());
hmac.Init(new Org.BouncyCastle.Crypto.Parameters.KeyParameter(System.Text.Encoding.UTF8.GetBytes(key)));
byte[] result = new byte[hmac.GetMacSize()];
hmac.BlockUpdate(bytes, 0, bytes.Length);
hmac.DoFinal(result, 0);
return result;
}
Keeping it simple:
using (SHA512 sha512 = new SHA512Managed())
{
password = Encoding.UTF8.GetString(sha512.ComputeHash(Encoding.UTF8.GetBytes(password)));
}
I'm not sure why you are expecting 128.
8 bits in a byte. 64 bytes. 8 * 64 = 512 bit hash.
From the MSDN Documentation:
The hash size for the SHA512Managed algorithm is 512 bits.
You could use the System.Security.Cryptography.SHA512 class
Here is an example, straigt from the MSDN
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA512 shaM = new SHA512Managed();
result = shaM.ComputeHash(data);
UnicodeEncoding UE = new UnicodeEncoding();
byte[] message = UE.GetBytes(password);
SHA512Managed hashString = new SHA512Managed();
string hexNumber = "";
byte[] hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hexNumber += String.Format("{0:x2}", x);
}
string hashData = hexNumber;
I used the following
public static string ToSha512(this string inputString)
{
if (string.IsNullOrWhiteSpace(inputString)) return string.Empty;
using (SHA512 shaM = new SHA512Managed())
{
return Convert.ToBase64String(shaM.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
}
}
Made it into an extension method in my ExtensionUtility.cs class
public static string SHA512(this string plainText)
{
using (SHA512 shaM = new SHA512Managed())
{
var buffer = Encoding.UTF8.GetBytes(plainText);
var hashedInputBytes = shaM.ComputeHash(buffer);
return BitConverter.ToString(hashedInputBytes).Replace("-", "");
}
}
Update:
new SHA512Managed()
is depricated and SHA512.Create()
should be used instead.
There is also a static Function availible since .NET5+.
The static Version is slightly faster and allocates less Memory compared to SHA512.Create()
.
So the last up to date version would be:
using System.Security.Cryptography;
using System.Text;
namespace Common;
public class Hash
{
public static string Sha512(string text) => Convert.ToHexString(SHA512.HashData(Encoding.UTF8.GetBytes(text)));
public static string Sha512(byte[] data) => Convert.ToHexString(SHA512.HashData(data));
}
Note: this functions are ThreadSafe.
This will return an uppercase 128 Byte-long Hexstring (each of the 64 Bytes is represented by 2 Byte (00 - FF).
So this code:
var theHash = Common.Hash.Sha512("this is to be hashed");
would result in:
3C1E5B4C27F3FD8D297000A74FFA04B0EA310E61E7043E85CB9EFDE55C00E730549D76DBB97864A4791F40DA27C4C292E40EF76BCEE5E88CAEA6E48E79E635B5
if you want to do some performance test on you own you can use this:
using BenchmarkDotNet.Attributes;
using System.Security.Cryptography;
using System.Text;
namespace PerformanceTests
{
[MemoryDiagnoser]
[Orderer(BenchmarkDotNet.Order.SummaryOrderPolicy.FastestToSlowest)]
[RankColumn]
public class Hashes
{
private string _inputText;
private byte[] _inputByte;
[Params(1_000, 10_000)]
public int N;
[GlobalSetup]
public void Setup()
{
const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
_inputText = new string(Enumerable.Repeat(chars, N).Select(s => s[new Random().Next(s.Length)]).ToArray());
_inputByte = new byte[N];
new Random(42).NextBytes(_inputByte);
}
[Benchmark]
public string Sha512StaticInputString() => Convert.ToHexString(SHA512.HashData(Encoding.UTF8.GetBytes(_inputText)));
[Benchmark]
public string Sha512NonStaticInputString()
{
using var sha512 = SHA512.Create();
return Convert.ToHexString(sha512.ComputeHash(Encoding.UTF8.GetBytes(_inputText)));
}
[Benchmark]
public string Sha512StaticInputByte() => Convert.ToHexString(SHA512.HashData(_inputByte));
[Benchmark]
public string Sha512NonStaticInputByte()
{
using var sha512 = SHA512.Create();
return Convert.ToHexString(sha512.ComputeHash(_inputByte));
}
}
}
results on my machine:
Note: N is the len of the input data in bytes.