How to easily salt a password in a C# windows form application?

Sergio Tapia picture Sergio Tapia · Jun 17, 2010 · Viewed 12.3k times · Source

How can I easily salt a password from a Textbox.Text?

Are there some built in wizardry in the .NET framework?

Answer

Randolpho picture Randolpho · Jun 17, 2010

We had a great discussion a while ago about best practices when salting a password, you might find some great ideas there:

Salting Your Password: Best Practices?

I've found that one of the easiest, while still being fairly secure, is to use a GUID as your salt. It's random and sufficiently long. It works best if you include the string formatting of the GUID (the '{' and '-' characters), but you don't have to.

Remember that the salt has to be unique per item salted and that to be most secure, you should use a cryptographically secure random number generator. Remember also that you have to store your salt along with the password, or you won't be able to check the plaintext version against the hashed version! You can store the salt un-encrypted if you like; I typically put it in a field on the same table as the password. The purpose of the salt isn't to remain hidden, it's to make rainbow tables difficult (hopefully impossible) to compute in a timely manner.

Here's a quick snippet that will work in C#:

RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buffer = new byte[1024];

rng.GetBytes(buffer);
string salt = BitConverter.ToString(buffer);
var saltedPassword = password + salt;

or...

var salt = Guid.NewGuid().ToString();
var saltedPassword = password + salt;