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?