I found some code online that works fairly well for what I am trying to do. I need something that will encrypt a password, save it to a database, and retrieve with ease. The below code does almost everything I am looking for.
string UserName = txtUser.Text;
string password = txtPass.Text;
string encrKey = "keyvalue";
byte[] byteKey = { };
byte[] IV = {25, 47, 60, 88, 99, 106, 125, 139};
byteKey = Encoding.UTF8.GetBytes(encrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputArray = Encoding.UTF8.GetBytes(password);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byteKey, IV), CryptoStreamMode.Write);
cs.Write(inputArray, 0, inputArray.Length);
cs.FlushFinalBlock();
password = Convert.ToBase64String(ms.ToArray());
SqlCommand cmd = new SqlCommand("INSERT INTO USers (UserName, Password) VALUES (@UserName, @Password)", myConnection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@UserName", UserName);
cmd.Parameters.AddWithValue("@Password", password);
SqlDataReader rdr = cmd.ExecuteReader();
The issue that I am running into is the code errors out when the password is 8 characters or longer. I get this error:
System.Security.Cryptography.CryptographicException: Specified key is not a valid size for this algorithm. The error is generated on the Cryptostream line.
Do I need to use a different type for my keys?
The common practice is not to encrypt a password in the database but to hash it.
When the user attempts to login, you take his typed password, hash it and compare to the hash stored in your db.
The industry standard hashing algorithm is SHA-1, which is readly available in .NET.
For even greater security you use a “Salt” in your hashing.
You can read more about it here: Salting Your Password: Best Practices?