C# Encryption exception
i Team,
I have the following encryption code in C#. I am getting an exception as Specified initialization vector (IV) does not match the block size for this algorithm.
Could you please tell me what is the missing link here?
//Key and IV for RSA Encryption
byte[] ketByte = Encoding.UTF8.GetBytes("C3CA193570B26E5C3CBB50FD805A01S2");
byte[] IVByte = Encoding.UTF8.GetBytes("C3FG563570FG565C3CBB50FD805A01S2");
//Read image
Image sourceImg = Image.FromFile(@"D:\ImageSource\Cha1.bmp");
//Convert to Byte[]
byte[] byteArray = ImageToByteArray(sourceImg);
//Encrypt
byte[] encryptedByteArray = EncryptByte(byteArray, ketByte, IVByte);
public static byte[] EncryptByte(byte[] palinData, byte[] Key, byte[] theInitializationVector)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
S开发者_StackOverflow中文版ystem.Security.Cryptography.Rijndael algorithm = System.Security.Cryptography.Rijndael.Create();
algorithm.Key = Key;
algorithm.IV = theInitializationVector; //Exception
System.Security.Cryptography.CryptoStream cStream = new System.Security.Cryptography.CryptoStream(ms,algorithm.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
cStream.Write(palinData, 0, palinData.Length);
cStream.Close();
byte[] encryptedData = ms.ToArray();
return encryptedData;
}
Thanks
Lijo
From SymmetricAlgorithm.IV Property documentation:
The size of the IV property must be the same as the BlockSize property.
And the BlockSize property:
Gets or sets the block size, in bits, of the cryptographic operation.
i don't know how many bits the UTF-8 encoded form of "C3CA193570B26E5C3CBB50FD805A01S2" is, but it's almost certainly not correct (Do you know how many bytes a UTF-8 encoded characters takes? i don't). You also don't know the blocksize of the Rijendal cipher, nor should you have to.
You should almost certainly be using PasswordDeriveBytes instead:
PasswordDeriveBytes pdb =
new PasswordDeriveBytes("C3CA193570B26E5C3CBB50FD805A01S2", null);
IVByte = pdb.GetBytes(algorithm.BlockSize / 8); //divide by 8 for bits to bytes
Finally, from a security point of view: while the Key is secret, the Initialization Vector (IV) is not. The IV is usually public, sent along with the encrypted data. In other words, your IV should not be the same as the Key.
Your initialization vector isn't the correct size, IVs are usually 16 bytes.
Try halving the size of your vector:
byte[] IVByte = Encoding.UTF8.GetBytes("C3FG563570FG565C");
What do you expect
byte[] ketByte = Encoding.UTF8.GetBytes("C3CA193570B26E5C3CBB50FD805A01S2");
byte[] IVByte = Encoding.UTF8.GetBytes("C3FG563570FG565C3CBB50FD805A01S2");
are doing? Because they are not loading those hex values into the byte array. They are creating a 32-byte array containing the ASCII values of each character.
精彩评论