public string EncryptPassWord(string password)
{
if (string.IsNullOrEmpty(password)) throw new ArgumentNullException("password");
string en_password = null;
RijndaelManaged aesPassword = null;
try
{
Rfc2898DeriveBytes passwordkey = new Rfc2898DeriveBytes(password, _salt);
aesPassword = new RijndaelManaged();
aesPassword.Padding = PaddingMode.None;
ICryptoTransform passwordEncryptor = aesPassword.CreateEncryptor(aesPassword.Key, aesPassword.IV);
using (MemoryStream passEncryptor = new MemoryStream())
{
passEncryptor.Write(BitConverter.GetBytes(aesPassword.IV.Length), 0, sizeof(int));
passEncryptor.Write(aesPassword.IV, 0, aesPassword.IV.Length);
using (CryptoStream cspassEncrypt = new CryptoStream(passEncryptor, passwordEncryptor, CryptoStreamMode.Write))
{
using (StreamWriter swpassEncryptor = new StreamWriter(cspassEncrypt))
{
swpassEncryptor.Write(password);
}
}
en_password = Convert.ToBase64String(passEncryptor.ToArray());
}
}
finally
{
if (aesPassword != null) { aesPassword.Clear(); }
}
return en_password;
}
public string DecryptPassword(string dePassword)
{
if (string.IsNullOrEmpty(dePassword)) throw new ArgumentNullException("dePassword");
RijndaelManaged aesDePassword = null;
string deCPassword = null;
try
{
Rfc2898DeriveBytes dePassKey = new Rfc2898DeriveBytes(dePassword, _salt);
byte[] bytes = Convert.FromBase64String(dePassword);
using(MemoryStream msPassDecrypt = new MemoryStream(bytes))
{
aesDePassword = new RijndaelManaged();
aesDePassword.Padding = PaddingMode.None;
aesDePassword.Key = dePassKey.GetBytes(aesDePassword.KeySize / 8);
aesDePassword.IV = ReadByteArray(msPassDecrypt);
ICryptoTransform passDecryptor = aesDePassword.CreateDecryptor(aesDePassword.Key, aesDePassword.IV);
using (CryptoStream csPassDecrypt = new CryptoStream(msPassDecrypt, passDecryptor, CryptoStreamMode.Read))
{
using(StreamReader srPassDecrypt = new StreamReader(csPassDecrypt))
{
deCPassword = srPassDecrypt.ReadToEnd();
}
}
}
}
finally
{
if (aesDePassword != null)
{
aesDePassword.Clear();
}
}
return deCPassword;
}
private static byte[] ReadByteArray(Stream s)
{
byte[] rawLength = new byte[sizeof(int)];
if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
{
throw new SystemException("Stream did not contain properly formatted byte array");
}
byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];
if(s.Read(buffer, 0, buffer.Length) != buffer.Length)
{
throw new SystemException("Did not read byte array properly");
}
return buffer;
}
Replies
Know the answer? Post it — somebody with the same question will find it here.