无法克服javax.crypto.BadPaddingException

时间:2016-05-26 09:48:12

标签: java encryption cryptography steganography badpaddingexception

我正在编写一个加密图像中文本的隐写系统 - 我决定在将其嵌入图片之前加密文本。 Steganography算法使用String输入/输出。

由于我的心血来潮,我一直在尝试使用DES和AES算法,但遇到了上述异常。我将举例说明AES算法的加密/解密方法:

    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);
}

这是呼叫(加密方):

  //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);

这是调用(解密方面) - 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);

问题出在哪里?

键是相似的,字节数组也是如此(我通过打印序列来检查它) - 但我被告知我不能使用getBytes()来从String转换为{{ 1}当我打算使用byteArray解密算法时。

1 个答案:

答案 0 :(得分:1)

加密的输出是二进制的,您不能像在此代码中那样将其转换为String

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

如果您需要加密数据为String,则需要以某种方式对其进行编码,例如base64encodinghexEncoding