I'm trying to do an exercise to encrypt a file.txt with a DES algorithm. I must save the generated key in a file without extension. I think this part is well solved. But I have troubles to decrypting the encrypted file using the same key. I'm getting the error: "Given final block not properly padded".
Exercise: 1. Encryption Program: Read a text file, encrypts it using the DES algorithm and the result is written to a new file, another file stored in the key used for encryption. 2. decryption program: read the program saved by the encryption key, decrypts the text stored by the encryption program and displays it on the screen.
NOTES: uses FileInputStream and FileOutputStream, performs encryption in blocks of 8 bytes and performs decryption in blocks of 16 bytes.
ENCRYPTING
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Encrypt {
public static void main(String[] args) {
try {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
FileOutputStream fosKey = new FileOutputStream("..\\KEY");
SecretKeyFactory keyfac = SecretKeyFactory.getInstance("DES");
DESKeySpec keyspec = (DESKeySpec) keyfac.getKeySpec(key, DESKeySpec.class);
fosKey.write(keyspec.getKey());
fosKey.close();
Cipher crypt = Cipher.getInstance("DES");
crypt.init(Cipher.ENCRYPT_MODE, key);
FileInputStream fis = new FileInputStream("..\\File.txt");
FileOutputStream fos = new FileOutputStream("..\\FileCrypted.txt");
byte[] arrayBytes = new byte[8];
int bytesReads;
while ((bytesReads = fis.read(arrayBytes)) != -1) {
fos.write(crypt.doFinal(arrayBytes), 0, bytesReads);
}
fis.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
DECRYPTING
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class Decrypt {
public static void main(String[] args) {
try {
FileInputStream fisKey = new FileInputStream("..\\KEY");
byte[] arrayKey = new byte[fisKey.available()];
fisKey.read(arrayKey);
SecretKey key = new SecretKeySpec(arrayKey, "DES");
Cipher decrypt = Cipher.getInstance("DES");
decrypt.init(Cipher.DECRYPT_MODE, key);
FileInputStream fis = new FileInputStream("..\\FileCrypted.txt");
byte[] encText = new byte[16];
int bytesReads;
while ((bytesReads = fis.read(encText)) != -1) {
fis.read(decrypt.doFinal(encText), 0, bytesReads);
}
fis.close();
System.out.println(new String(encText));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Cipher.getInstance("DES");may have different defaults based on the security provider, which might break compatibility across multiple JVM's. It most likely defaults toCipher.getInstance("DES/ECB/PKCS5Padding");