My next task will be to encrypt passwords. I am working at 开发者_C百科the database access layer and my co-worker has made this request: implement an SHA-512 hash on an empty method. How can I do this?
Quite a simple process really:
byte[] data = Encoding.UTF8.GetBytes(stringPasswordForExample);
using(SHA512 sha512 = new SHA512Managed())
{
byte[] hash = sha512.ComputeHash(data); // Add Per User Salt as per the Below
}
hash
now contains a non-reversable hash of the initial data that you wanted hashed. Also, check out MSDN. A few notes:
- Always use a salt (the longer the better, and unique per user - Thanks Paul, good point.)
- SHA2* generation (and SHA in general) hash methods are built for speed, so they are not insecure, but they are not the most secure. Look at bcrypt as well as SLaks has mentioned.
You should use bcrypt, which is more secure for passwords than SHA512.
If you really need to use SHA512, you should use the SHA512Managed
class, as other answers have mentioned.
Make sure to salt your hash.
how to hash a password?
With a salt. Really.
Never, ever do this:
byte[] data = Encoding.UTF8.GetBytes(stringPasswordForExample);
But this:
byte[] data = Encoding.UTF8.GetBytes(stringPasswordForExample + salt);
This is one the most misunderstood "trick of the trade". Most people don't know what a "salt" is and when you explain it to them, they think it's pointless.
Truth is: SHA-512 or MD5 or some very weak hash, once rainbow tables are precomputed, doesn't make any difference. SHA-65536, should it exist (I'm being facetious here), would be no better than any other hashing algorithm once rainbow tables are precomputed.
A big enough "salt" makes rainbow tables impossible:
http://en.wikipedia.org/wiki/Rainbow_table
Note that even if you understand fully how hashes, salt and rainbow tables relate (and hence understand why the Wikipedia article states: "A salt is often employed with hashed passwords to make this attack more difficult, often infeasible.") there's a very high probability that your co-workers don't. Just as it is very likely that most people up and downvoting in this thread don't understand this topic.
I've seen answers here on SO with 30 upvotes where someone who couldn't understand what a salt was kept up coming with techno-buzzwords to defend his position... And yet he had all these upvotes (too lazy to find the question but it was epic).
SHA512 Class
C# example from that page:
byte[] data = new byte[DATA_SIZE];
byte[] result;
SHA512 shaM = new SHA512Managed();
result = shaM.ComputeHash(data);
精彩评论