javac#.net-corehashsecure-random

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


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);

Solution

  • 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);