Hi
I am not very clear about your approach. However I am give the microsoft example code in addition with a SALT and PASSWORD to encrypt.
When you call like MessageBox.Show(RijndaelMemoryExample.Test("my test string")); It returns the same input string after encryption and then decryption.
<pre lang="msil">class RijndaelMemoryExample
{
public static string Test(string original)
{
try
{
string saltText = "Test salt";
string password = "Test password";
System.Security.Cryptography.RijndaelManaged myRijndael = new System.Security.Cryptography.RijndaelManaged();
byte[] salt = Encoding.ASCII.GetBytes(saltText);
Rfc2898DeriveBytes rfcKey = new Rfc2898DeriveBytes(password, salt);
myRijndael.Key = rfcKey.GetBytes(myRijndael.KeySize / 8);
myRijndael.IV = rfcKey.GetBytes(myRijndael.BlockSize / 8);
byte[] encrypted = encryptStringToBytes_AES(original, myRijndael.Key, myRijndael.IV);
string roundtrip = decryptStringFromBytes_AES(encrypted, myRijndael.Key, myRijndael.IV);
return roundtrip;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.Message);
return "";
}
}
static byte[] encryptStringToBytes_AES(string plainText, byte[] Key, byte[] IV)
{
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
MemoryStream msEncrypt = null;
System.Security.Cryptography.RijndaelManaged aesAlg = null;
try
{
aesAlg = new System.Security.Cryptography.RijndaelManaged();
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
msEncrypt = new MemoryStream();
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(plainText);
}
}
}
finally
{
if (aesAlg != null)
aesAlg.Clear();
}
return msEncrypt.ToArray();
}
static string decryptStringFromBytes_AES(byte[] cipherText, byte[] Key, byte[] IV)
{
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
System.Security.Cryptography.RijndaelManaged aesAlg = null;
string plaintext = null;
try
{
aesAlg = new System.Security.Cryptography.RijndaelManaged();
aesAlg.Key = Key;
aesAlg.IV = IV;
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
plaintext = srDecrypt.ReadToEnd();
}
}
}
finally
{
if (aesAlg != null)
aesAlg.Clear();
}
return plaintext;
}
}