I am using this code for Encrypt and Dycrpt the data using asp.net .
But i am getting the error:--
**Specified initialization vector (IV) does not match the block size for this algorithm**.
here is a code:-
my .cs file is:-
public static class Encrypt_Decrypt
{
static Encrypt_Decrypt()
{
}
public static string EncryptString(string ClearText)
{
byte[] clearTextBytes = Encoding.UTF8.GetBytes(ClearText);
System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
MemoryStream ms = new MemoryStream();
byte[] rgbIV = Encoding.ASCII.GetBytes("hanuservicestalknsolve");
byte[] key = Encoding.ASCII.GetBytes("hanuservicestalknsolve");
CryptoStream cs = new CryptoStream(ms, rijn.CreateEncryptor(key, rgbIV),CryptoStreamMode.Write);
cs.Write(clearTextBytes, 0, clearTextBytes.Length);
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
private static string DecryptString(string EncryptedText)
{
byte[] encryptedTextBytes = Convert.FromBase64String(EncryptedText);
MemoryStream ms = new MemoryStream();
System.Security.Cryptography.SymmetricAlgorithm rijn = SymmetricAlgorithm.Create();
byte[] rgbIV = Encoding.ASCII.GetBytes("hanuservicestalknsolve");
byte[] key = Encoding.ASCII.GetBytes("hanuservicestalknsolve");
CryptoStream cs = new CryptoStream(ms, rijn.CreateDecryptor(key, rgbIV),
CryptoStreamMode.Write);
cs.Write(encryptedTextBytes, 0, encryptedTextBytes.Length);
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
Here is my aspx.cs code:
string eventi = Encrypt_Decrypt.EncryptString(DataBinder.Eval(e.Item.DataItem, "name_of_post_id").ToString());
string post = Encrypt_Decrypt.EncryptString(DataBinder.Eval(e.Item.DataItem, "compreq_eventid").ToString());
From the documentation of SymmetricAlgorithm.IV
:
The size of the IV property must be the same as the BlockSize property divided by 8.
I suspect you'll find that rijn.BlockSize
is 128, so you should provide a 32-byte IV.
(It's not clear why your variable is called rgbIV
, and you don't have any of the appropriate using
statements. I hope you're not using a fixed IV and key in your real code, too... otherwise it's not providing much security.)
See more on this question at Stackoverflow