I've written C# ASP.NET code that encrypts a password and stores it in an Access database. The code retrieves the encrypted password but can not decrypt it. Please see encryption and decryption code below. I can only guess that the encrypted string is "corrupted" when storing in Access and thus can not be decrypted. The password is encrypted as a base64 string. Can anyone explain why? Perhaps someone knows of other encryption/decryption code.
static SymmetricAlgorithm encryptionAlgorithm = InitializeEncryptionAlgorithm();
static SymmetricAlgorithm InitializeEncryptionAlgorithm()
{
SymmetricAlgorithm rijaendel = RijndaelManaged.Create();
rijaendel.GenerateKey();
rijaendel.GenerateIV();
return rijaendel;
}
///
/// Encrypts the string and returns a base64 encoded encrypted string.
///
/// The clear text.
///
public static string EncryptString(string clearText)
{
byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);
byte[] encrypted = encryptionAlgorithm.CreateEncryptor().TransformFinalBlock(clearTextBytes, 0, clearTextBytes.Length);
return Convert.ToBase64String(encrypted);
}
///
/// Decrypts the base64 encrypted string and returns the cleartext.
///
/// The clear text.
///
/// was encrypted using a different encryptor (for example, if we recompile and
/// receive an old string).
///
public static string DecryptString(string encryptedEncodedText)
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedEncodedText);
byte[] decryptedBytes = encryptionAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
Niradhip ChakrabortyPosted May 21, 2008, 3:28 PM
http://www.developerfusion.co.uk/show/157/