how to create hash value from random bytes using secureRandom equivalent class in C# using SHA-512

493 Views Asked by At

Equivalent code for this Java code in C#

SecureRandom random = new SecureRandom();
byte randBytes[] = new byte[64];
random.nextBytes(randBytes);
MessageDigest md = MessageDigest.getInstance("SHA-512");
md.update(randBytes);
byte[] hash = md.digest();
byte[] encodedHash = Base64.encodeBase64(hash);
1

There are 1 best solutions below

0
xanatos On BEST ANSWER

It should be:

var randBytes = new byte[64];

using (var random = RandomNumberGenerator.Create())
{
    random.GetBytes(randBytes);
}

byte[] hash;

using (var md = SHA512.Create())
{
    hash = md.ComputeHash(randBytes);
}

string encodedHash = Convert.ToBase64String(hash);

Unclear the use of calculating the hash of some random bytes.

Note that technically in Java encodedHash is in utf8 format. If you really want it in utf8:

byte[] encodedHash2 = Encoding.UTF8.GetBytes(encodedHash);