I'm trying to do a simple encryption/decryption program. The code below works fine if I never convert the encrypted text into a string. My problem occurs when i convert it to a string and then I convert it back into bytes. I want to eventually create a GUI, so I figured that if there is a encrypted text it will be assigned to a variable from a text field via a string. Please help if you can. Sorry for any confusion.
Here is the error:
Code:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
KeyGenerator keyGen = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keyGen.generateKey();
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, myDesKey);
String message = "TEST";
byte[] input = message.getBytes();
System.out.println(input);
// Encrypt
byte[] messageEncrypted = cipher.doFinal(input);
// Decrypt
String text = messageEncrypted.toString();
System.out.println(text);
System.out.println(messageEncrypted);
byte[] textMessageEncrypted;
textMessageEncrypted = text.getBytes();
System.out.println(textMessageEncrypted);
cipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] messageDecrypted = cipher.doFinal(textMessageEncrypted);
System.out.println("Text Decrypted: " + new String(messageDecrypted));
}
}
Code:
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..) at com.sun.crypto.provider.DESCipher.engineDoFinal(DashoA13*..)[B@4bdb699b