I have this method, with takes in path to a file on the system, encrypts it, and then writes the encrypted file to disk using the file path as a name and ".enc" extension. It works fine, and I am able to decrypt the file later with a different function:
Here's the problem. Instead of writing to disk, I want to get the encrypted stream directly into a byte[] array. I'm trying to do this as follows:
This seems to work, but the returned byte[] does not appear to be the correct size -- even though I am using the exact same key (this.key) and initialization vector (this.iv) in both methods.
Unencrypted file: 327,286 bytes
Encrypted file #1: 327,296 bytes (first method)
Encrypted file #2: 327,280 bytes (second method)
When I try to decyrpt the #2 file, I get the following exception:
PKCS7 padding is invalid and cannot be removed
I'm obviously not doing something right in method #2. The byte[] in #2 is exactly 16 bytes smaller. I don't know if this is a conicidence, but that is the size of the Key and IV in the Rijndael class. Any help is appreciated. Thanks...
Code:
public void Encrypt(string fileName)
{
FileStream fsCrypt=new FileStream(fileName + ".enc", FileMode.Create);
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(key,iv),
CryptoStreamMode.Write);
FileStream fsIn=new FileStream(fileName,FileMode.Open);
int data;
while ((data=fsIn.ReadByte())!=-1)
cs.WriteByte((byte) data);
fsIn.Close();
cs.Close();
fsCrypt.Close();
}
Code:
public byte[] Encrypt(byte[] plainFile)
{
MemoryStream cryptoStream = new MemoryStream();
Stream fsCrypt = (Stream)cryptoStream;
RijndaelManaged RMCrypto = new RijndaelManaged();
CryptoStream cs = new CryptoStream(fsCrypt,
RMCrypto.CreateEncryptor(this.key,this.iv),
CryptoStreamMode.Write);
Stream fsIn = (Stream)new MemoryStream( plainFile );
int data;
while ((data=fsIn.ReadByte())!=-1)
cs.WriteByte((byte) data);
byte[] temp = new byte[ cryptoStream.Length ];
int count = 0;
while ((data=cryptoStream.ReadByte())!=-1)
{
temp[count++] = (byte)data;
}
fsIn.Close();
cs.Close();
fsCrypt.Close();
return temp;
}
Unencrypted file: 327,286 bytes
Encrypted file #1: 327,296 bytes (first method)
Encrypted file #2: 327,280 bytes (second method)
When I try to decyrpt the #2 file, I get the following exception:
PKCS7 padding is invalid and cannot be removed
I'm obviously not doing something right in method #2. The byte[] in #2 is exactly 16 bytes smaller. I don't know if this is a conicidence, but that is the size of the Key and IV in the Rijndael class. Any help is appreciated. Thanks...
Last edited: