I have recently been experimenting with the "CryptoStream", and ran into the idea of encrypting & decrypting a text via. the Aes class. 'Namespace: System.Security.Cryptography'
After making a function that succesfully encrypted a text using two input parameters: Text, Password
static byte[] Salt = { 18,39,27,48,82,32,12,92 };
public static string EncryptAES(string txt, string Password) {
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(Password, Salt);
RijndaelManaged RJM = new RijndaelManaged();
RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
ICryptoTransform ICT = Aes.Create().CreateEncryptor(RJM.Key, RJM.IV);
using (MemoryStream MS = new MemoryStream()) {
using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Write)) {
using (StreamWriter SW = new StreamWriter(CS)) {
SW.Write(txt);
}
}
return Convert.ToBase64String(MS.ToArray());
}
}
The issue of decrypting the text took place.
My attempt of decrypt the text was the following:
public static string DecryptAES(string EncryptedTxt, string Password) {
Rfc2898DeriveBytes rfc = new Rfc2898DeriveBytes(EncryptedTxt, Salt);
RijndaelManaged RJM = new RijndaelManaged();
RJM.Key = rfc.GetBytes(RJM.KeySize / 8);
ICryptoTransform ICT = Aes.Create().CreateDecryptor(RJM.Key, RJM.IV);
using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt))) {
using (CryptoStream CS = new CryptoStream(MS, ICT, CryptoStreamMode.Read)) {
using (StreamReader SR = new StreamReader(CS)) {
return SR.ReadToEnd();
}
}
}
However; it appears that my way of converting the memorystream to string and then back was invaild, as I get the following error: Error: Value cannot be null\nParameter name: inputBuffer
The error occurs at using (MemoryStream MS = new MemoryStream(Convert.FromBase64String(EncryptedTxt)))
How can I converter the MemoryStream into string and back?
Thanks in advance :-)