I'm trying to implement the TripleDES
encryption algorithm using DES
,
I want to use 2 keys, and the flavor of the TripleDES
is EDE using (key1, key2, key1).
I know that there is a TripleDES algorithm, but my project is about implementing it using DES.
Here is my code
static Cipher cipher;
static final int[] ENC_MODE = {Cipher.ENCRYPT_MODE, Cipher.DECRYPT_MODE, Cipher.ENCRYPT_MODE};
public static void main(String[] args) throws Exception {
String text = "this is my text";
cipher = Cipher.getInstance("DES");
SecretKey key1 = KeyGenerator.getInstance("DES").generateKey();
SecretKey key2 = KeyGenerator.getInstance("DES").generateKey();
String cipherText = enc(text, key1, key2);
}
private static String enc(String plainText, SecretKey key1, SecretKey key2) throws Exception{
byte[] textBytes = null;
String encText = plainText;
for(int i=0; i<3; i++){
if (ENC_MODE[i] == Cipher.ENCRYPT_MODE){
cipher.init(ENC_MODE[i], key1);
textBytes = encText.getBytes("UTF8");
textBytes = cipher.doFinal(textBytes);
encText = Base64.getEncoder().encodeToString(textBytes);
}else if(ENC_MODE[i] == Cipher.DECRYPT_MODE){
cipher.init(ENC_MODE[i], key2);
textBytes = cipher.doFinal(textBytes); //Error Line
encText = new String(textBytes, "UTF8");
}
System.out.println("loop= " + i +" "+encText);
}
return encText;
}
my problem is that in the second loop (decryption with key2) I'm always getting this exception
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
I looked for this problem everywhere, but I didn't find a solution!
Thank you.