I need a code example for C#, of how to generate a hash using SHA512 using a random salt and for n number of iterations? Also, a code example of how to verify hash created by the above method.
Asked
Active
Viewed 2,872 times
1
-
http://msdn.microsoft.com/en-us/library/system.security.cryptography.sha512.aspx – Incognito Dec 14 '10 at 21:26
2 Answers
-1
Don't know what you mean by "verify", but System.Security.Cryptography.SHA512
does what you're looking for. Note that .NET's implementation is not FIPS validated, so if your customers have FIPS compilant mode turned on your program will not function.

Billy ONeal
- 104,103
- 58
- 317
- 552
-1
Checkout this link, it has code for salting and using other hashes other than sha512 and is liberally commented.
To rehash the hash all you would have to do is first compute the hash string and then use Byte to get a hex-encoded string that you could then hash again.

Zimm3r
- 3,369
- 5
- 35
- 53
-
2the link given has a very detailed implementation, but it does not mention anything about using multiple iterations for the hashing algorithm. Can you give an example of using the same hashing logic for multiple iterations? – EndlessSpace Dec 14 '10 at 21:34
-
For multiple iterations, it sounds like you want to use something like [PBKDF2](http://tools.ietf.org/html/rfc2898#section-5.2). It shouldn't be hard to modify the example above to match the algorithm described in the RFC. – Mike Dec 14 '10 at 21:55
-
@Mike: The .NET framework comes with an implementation of PBKDF2 built-in, and it's *very* easy to use (although it only supports HMACSHA1): http://msdn.microsoft.com/en-us/library/system.security.cryptography.rfc2898derivebytes.aspx – LukeH Dec 14 '10 at 22:54
-
@user428468 I updated it with how you could rehash a string multiple times. – Zimm3r Dec 15 '10 at 05:15
-
@LukeH so does that mean I can use the key generated by Rfc2898DeriveBytes like a hash(not in the literal meaning but as something that can be used as an identifier) and use it to verify user login? – EndlessSpace Dec 15 '10 at 15:12
-
@user428468: Yes, for example http://stackoverflow.com/questions/4329909/hashing-passwords-with-md5-or-sha-256-c/4330586#4330586 – LukeH Dec 15 '10 at 15:18
-
Converting the output bytes to a string is inefficient, you can compute the hash of the output buffer directly. – Dai Oct 30 '18 at 01:49