PKCS5 padding help
843810Nov 20 2002 — edited May 19 2004Sorry if this is a duplicate, but I couldnt find an exact explanation...
I am encrypting large (ish) files using a cipher stream, and AES with PKCS5 padding.
I am wondering why the resultant file is always different to the input file (is this normal for PKCS5 padding) but only by a very small amount.
When decrypting, if I simply read in the file up to the original (clear text) byte count, everything is fine (discarding last few bytes that were added) but if I leave them in, in seems to add a tiny bit to the resulting clear text (deciphered), thus "corrupting" the data.
Following is the encryption code:
public void encryptFileWithSessionKey(SecretKey key, byte[] iv, File sourceFile, File destFile) throws CryptoException
{
int BULK_CHUNK_SIZE = 4096;
try
{
Cipher cipherMessage = Cipher.getInstance("AES/CBC/PKCS5Padding","BC");
cipherMessage.init(Cipher.ENCRYPT_MODE,key,new IvParameterSpec(iv));
BufferedInputStream in = new BufferedInputStream(new FileInputStream(sourceFile));
CipherInputStream cipherIn = new CipherInputStream(in,cipherMessage);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] buffer = new byte[BULK_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = cipherIn.read(buffer)) != -1)
{
out.write(buffer,0,bytesRead);
}
cipherIn.close();
out.flush();
out.close();
} catch (Exception e)
{
logger.log(Level.SEVERE, "Exception", e);
throw new CryptoException("Error encrypting file. " + e.getMessage());
}
}
Thanks for any advice.
Michael.