I am working on a Rijndael256 encrypt and decrypt method in C# and it appears that my encrypt method is "working", however; my decrypt method randomly returns an error about the IV or Data I want to be decrypted stating "Invalid length for a Base-64 char array or string." The decrypt will work once or twice and then error. I am guessing it has something to do with the randomly generated IV size or something simple, but any guidance would be great.
private string encryptData(string data)
{
byte[] encKey = ASCIIEncoding.UTF8.GetBytes("pemgail9uzpgzl88");
Rijndael aes = Rijndael.Create();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = encKey;
ICryptoTransform crypto = aes.CreateEncryptor(aes.Key, aes.IV);
byte[] txt = ASCIIEncoding.UTF8.GetBytes(data);
byte[] cipherText = crypto.TransformFinalBlock(txt, 0, txt.Length);
return Convert.ToBase64String(cipherText) + "&iv=" + Convert.ToBase64String(aes.IV);
}
My decrypt method:
private string decryptData(string encData, string encIV)
{
byte[] encKey = ASCIIEncoding.UTF8.GetBytes("pemgail9uzpgzl88");
string returnValue = Convert.ToBase64String(encKey);
byte[] myIv = Convert.FromBase64String(encIV);
byte[] myMessage = ASCIIEncoding.UTF8.GetBytes(encData);
Rijndael aes = Rijndael.Create();
aes.KeySize = 256;
aes.BlockSize = 256;
aes.IV = myIv;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
aes.Key = encKey;
ICryptoTransform crypto = aes.CreateDecryptor(aes.Key, aes.IV);
byte[] txt = Convert.FromBase64String(encData);
byte[] cipherText = crypto.TransformFinalBlock(txt, 0, txt.Length);
return Encoding.UTF8.GetString(cipherText);
}
As a test I am encrypting the data, redirecting the test page to itself and then taking the values in the QueryStrings to use for the decrypt method.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["data"] != null && Request.QueryString["iv"] != null)
{
string test = decryptData(Request.QueryString["data"], Request.QueryString["iv"]);
Response.Write(test);
}
else
{
string test = encryptData("BrassMonkey");
Response.Redirect("Rijindael.aspx?data=" + test);
}
}