I'm trying to make an encryption system with c#. This is the code for the encryption.
public static void EncryptFile(string inFile, string outFile, string @inkey)
{
try
{
UnicodeEncoding ue = new UnicodeEncoding();
byte[] key = ue.GetBytes(inkey);
FileStream fsEncrypt = new FileStream(outFile, FileMode.Create);
RijndaelManaged rmCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsEncrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
FileStream fsIn = new FileStream(inFile, FileMode.Open);
int data;
while((data=fsIn.ReadByte()) != 1){
cs.WriteByte((byte)data);
}
fsIn.Close(); cs.Close(); fsEncrypt.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Fail to encrypt", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Now, this code throws exception every time I run it, says
Specified initialization vector(IV) does not match the block size for this algorithm
I have read on other discussion about this, saying that there is a problem with the number of bytes (my key length passed into this function is 255). But I have tried making the key only 16 bytes and still not working.
After some troubleshooting I found out that this part:
CryptoStream cs = new CryptoStream(fsEncrypt, rmCrypto.CreateEncryptor(key, key), CryptoStreamMode.Write);
throws the exception. I have no idea why. Anyone can help?