How to hash a string with salt using a multi-algorithm method
It is considered a very bad idea to store user credentials in plain text, especially passwords. For that very reason it is always a good idea to hash passwords before you store them, ideally with a unique salt that you can store in another location. That way if for whatever reason your database is compromised your users passwords will not be in plain text and it will require a bit of work in order to find out what each password is, especially if the salt for each password is stored somewhere else.
The following method is a multi algorithm method, that means that with this single method you can use more than one algorithm to hash your data. The snippet below shows an example how to hash your data with a single method using seven different algorithms.
Our main method that will do all the work for us:
1 2 3 4 5 6 | private string StringToHash(string data, string salt, HashAlgorithm algorithm) { byte[] saltedBytes = Encoding.UTF8.GetBytes(data + salt); // Combine the data with the salt byte[] hashedBytes = algorithm.ComputeHash(saltedBytes); // Compute the hash value of our input return BitConverter.ToString(hashedBytes); } |
And here are some test cases:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Result is b3ede0fa69b68faabcfdee906047533a string test1 = StringToHash("this is my test string", "salt1", new MD5CryptoServiceProvider()).ToLower().Replace("-", ""); // Result is e95567165e2b9815fb55b96ab04de1a2fb0f5b38 string test2 = StringToHash("this is my test string", "salt2", new RIPEMD160Managed()).ToLower().Replace("-", ""); // Result is 57930f00f573418b21d3a7703d12515ccf691290 string test3 = StringToHash("this is my test string", "salt3", new SHA1CryptoServiceProvider()).ToLower().Replace("-", ""); // Result is 49d6907da3df816167b35c7215a2d26b9d84d7388c8552c30e55d4c19c86f5bb string test4 = StringToHash("this is my test string", "salt4", new SHA256CryptoServiceProvider()).ToLower().Replace("-", ""); // Result is dcafea354cd439f84d2f1f696091887383f5b1dd5ee049342a3e5944615a46fdff1626ff95405cb31cd45b571548f6bc string test5 = StringToHash("this is my test string", "salt5", new SHA384CryptoServiceProvider()).ToLower().Replace("-", ""); // Result is 1ab5c1be81a4e3be552dad98306edc3554dd55d83d28b397af61a150351527b2de65cbb3995ad45a36395dab94aaf34155c27894303547e50a485bfdda683c99 string test6 = StringToHash("this is my test string", "salt6", new SHA512CryptoServiceProvider()).ToLower().Replace("-", ""); // Result is 818800f4a59e246e string test7 = StringToHash("this is my test string", "salt7", new MACTripleDES()).ToLower().Replace("-", ""); |
Leave a Reply