I am using the following code to create an encrypted file. I am doing some research for my thesis and really only care about the encrypted file, however,
I wanted to test the encrypted file by decrypting it. The decrypted file is never correct. So the million dollar question is "What am I doing wrong?"
private static void encrypted(
FileInputStream inputFile, FileOutputStream outputFile)
{
Cipher DESCipher;
Cipher TestDESCipher;
try
{
SecretKey desKey = getDESKey();
DESCipher = Cipher.getInstance("DES");
TestDESCipher = Cipher.getInstance("DES");
// Initialize the cipher for encryption
DESCipher.init(Cipher.ENCRYPT_MODE, desKey);
TestDESCipher.init(Cipher.DECRYPT_MODE, desKey);
CipherOutputStream desCipherStream = new CipherOutputStream(
outputFile, DESCipher);
byte[] b = new byte[8];
int i = inputFile.read(b);
while (i > 0)
{
if (debug)
{
System.out.write(b);
}
desCipherStream.write(b, 0, i);
i = inputFile.read(b);
}
inputFile.close();
desCipherStream.close();
outputFile.close();
// //////////////////////////////////////////start decrypt test
FileInputStream decInFile = new FileInputStream(
"C:\\Documents and Settings\\Walter\\My Documents\\AFIT\\Thesis Work\\Encryption Work\\Text\\DES\\text test.txt");
FileOutputStream decOutFile = new FileOutputStream(
"C:\\Documents and Settings\\Walter\\My Documents\\AFIT\\Thesis Work\\Encryption Work\\Text\\DES\\text test decrypted.txt");
CipherInputStream desDecryptCipherStream = new CipherInputStream(
decInFile, TestDESCipher);
byte[] c = new byte[8];
i = desDecryptCipherStream.read(c);
while (i > 0)
{
System.out.write(c);
decOutFile.write(c, 0, i);
i = desDecryptCipherStream.read(c);
}
decInFile.close();
desDecryptCipherStream.close();
decOutFile.close();
// ////////////////////////////////////////// end decrypt test
}
catch (Exception e)
{
e.getMessage();
e.printStackTrace();
}
}
Here is the contents of the plaintext input file:
This is an example.
Here is the contents of the encrypted file:
��3���f�g�b`��C��3��8w
Here is the contents of the decrypted file:
�P�e�a�C�v,(���
The program encrypted and decrypted the following correctly:
bytes[] plaintext = "This is an example.".getBytes();
But when I tried to put the text in a file and tried to use
CipherOutputStream the problem arises.
I've tried to use a single cipher that was reinitialized to
DECRYPT, and I've tried to use two separate ciphers, but the results were the same.
I know I am using the same key and padding scheme, so what is going wrong?