I am building a file encryption utility, here's my encryption code:
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.ENCRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
for(int i = 0; i < input.size(); i++){
plainText = input.get(i);
byte[] b = cipher.doFinal(plainText.getBytes("UTF-8"));
String outString = new String(b);
//to be written to file
The strings to encrypt are read in from an array (the utility does other data processing) and then encrypted, and output in an array of strings to write to a file when ready.
When decrypting, I get an error that my padding is wrong. I have been researching and gather that this is down to .getBytes() not returning the byte array exactly as it was. I am reading line by line from file that has been encrypted using my previous code. How can I ensure that my decryption function receives the correct byte array?
Here is the code:
public void decode(File f) throws Exception{
BufferedWriter out = new BufferedWriter(new FileWriter("Decrypted Archive "+f.getName()+".txt"));
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while((line = br.readLine())!=null){
byte[] b = line.getBytes("UTF-8");
line = Decoder.decrypt(b);
out.write(line+newline);
}
br.close();
out.close();
And the decrypt function:
public static String decrypt(byte[] cipherText) throws Exception{
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
SecretKeySpec key = new SecretKeySpec(encryptionKey.getBytes("UTF-8"), "AES");
cipher.init(Cipher.DECRYPT_MODE, key,new IvParameterSpec(IV.getBytes("UTF-8")));
return new String(cipher.doFinal(cipherText),"UTF-8");
}
Encryption keys etc are all the same.