BadPaddingException
My problem is that I am getting a BadPaddingException when I am unwrapping the secret key. Was wondering if anyone had any ideas? Any help would be greatly appreciated.
*******Relevant methods in ENCRYPTION class******************
public static void main( String[] args ) {
try {
System.out.print("Enter your message to encrypt: ");
BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
String line = console.readLine();
KeyGenerator keygen = KeyGenerator.getInstance("AES");
SecretKey sessionKey = keygen.generateKey();
//Create Ciphers
Cipher symCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
Cipher asymCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// Encrypt plain text using symetric key
symCipher.init(Cipher.ENCRYPT_MODE, sessionKey);
byte[] cleartext = line.getBytes();
byte[] ciphertext = symCipher.doFinal(cleartext);
//Encrypt session key
byte[] encSK = encryptSessionKey(sessionKey, asymCipher);
//Write encrypted message to file
writeFile(encSK, ciphertext);
}
catch ( Exception ex ) {
ex.printStackTrace();
}
}
public static byte[] encryptSessionKey(SecretKey sessionKey, Cipher cipher) {
try {
cipher.init(Cipher.WRAP_MODE, getCertificate(KEY_ALIAS, KEYSTORE));
return cipher.wrap(sessionKey);
}
catch (Exception e) {
System.out.println("Error encrypting session key"+ e);
}
return null;
}
/**
*Write encrypted text to file
*/
public static void writeFile(byte[] sessionKey, byte[] cipherText) {
try {
String ciphertext = new String(cipherText);
String sessionkey = new String(sessionKey);
String encryptedFile = "EncryptedFile.txt";
BufferedWriter out = new BufferedWriter(new FileWriter(encryptedFile));
System.out.println(ciphertext);
out.write(sessionkey);
out.newLine();
out.write(ciphertext);
out.flush();
}
catch (Exception e) { System.out.println(e); }
}
}
*******************DECRYPTION class**********************
while (line != null) {
System.out.println(line);
//Cipher used to encrypt session key
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//convert text to bytes from file
byte[] wrappedSessionKey = line.getBytes();
//initialise cipher to unwrap session key with private key
cipher.init(Cipher.UNWRAP_MODE, getPrivateKey(KEY_ALIAS, KEY_PASS, KEYSTORE));
//obtain session key
Key sessionKey = cipher.unwrap(wrappedSessionKey, "AES", Cipher.SECRET_KEY); //<<<<<<<<ERROR OCCUES HERE
//decrypt message with session key
Cipher symCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
symCipher.init(Cipher.DECRYPT_MODE, sessionKey);
line = file.readLine();
byte[] plainbytes = line.getBytes();
byte[] plainText = symCipher.doFinal(plainbytes);
String string = new String(plainText);
System.out.println(string);
}
I added the writefile method because I thought maybe this might have something to do with the exception as the encryption might be getting mangled/read in wrong?
Cheers,
Pat.>

