简体   繁体   中英

Can't overcome the javax.crypto.BadPaddingException

I'm writing a steganography system which encrypt a text within an image - i decided that i want to encrypt the text as well before i embed it in the picture. The Steganography algorithm works with String input/output.

Due to my whim, i've been trying to use DES and AES algorithm but ran into the Exception above. i'll show for example the encryption/decryption methods of the AES algorithm:

    public static byte[] encryptText(String plainText,SecretKey secKey) throws Exception{
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
    byte[] byteCipherText = aesCipher.doFinal(plainText.getBytes());
    return byteCipherText;}


    public static String decryptText(byte[] byteCipherText, SecretKey secKey) throws Exception {
    // AES defaults to AES/ECB/PKCS5Padding in Java 7
    Cipher aesCipher = Cipher.getInstance("AES");
    aesCipher.init(Cipher.DECRYPT_MODE, secKey);
    byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
    return new String(bytePlainText);
}

And here is the calling (Encryption side):

  //sending the text to encrypt using AES algorithm
byte[] cipherText = new AES_Algorithm().encrypt(messageDesc.getText(), key);
  //converting into a String to encrypt using Steganography
newStringtoEncrypt = new String (cipherText);

And here is the calling (Decryption side) - THE EXCEPTION :

  //AES encrypted String after the Steganography's decryption 
String decMessage = dec.decode(path, name);
  //converting the String to byte []
byte [] byteArray = decMessage.getBytes();
try{
    //HERE IS WHERE I GET THE EXCEPTION
    //sending the byte array to decryption
  String original = AES_Algorithm().decrypt(byteArray, key);

Where is the problem?

The keys are similar and the byte arrays as well (i checked it by printing the sequence) - but i have been told that i can't use getBytes() in order to convert from String to byteArray when i intend to use AES/DES decryption algorithm.

The output from the encryption is binary, you can't just convert it to String as you do in this code:

byte[] cipherText = new AES_Algorithm().encrypt(messageDesc.getText(), key);
//converting into a String to encrypt using Steganography
newStringtoEncrypt = new String (cipherText);

If you need the encrypted data as String , you need to encode it somehow, eg by base64encoding or by hexEncoding

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM