java - 无法克服 javax.crypto.BadPaddingException

标签 java encryption cryptography steganography badpaddingexception

我正在编写一个隐写术系统,该系统对图像中的文本进行加密 - 我决定在将文本嵌入图片中之前也对文本进行加密。隐写术算法适用于字符串输入/输出。

由于我的突发奇想,我一直在尝试使用 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() 来从字符串转换当我打算使用 AES/DES 解密算法时,转换为 byteArray

最佳答案

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

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

如果您需要将加密数据作为String,则需要以某种方式对其进行编码,例如通过 base64encoding或通过 hexEncoding

关于java - 无法克服 javax.crypto.BadPaddingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37457236/

相关文章:

javascript - 使用转换后的 JS 函数在 Python 中进行反混淆

c# - 如何使用 PEM 文件中的 rsa 解密

java使用 key 对加密和解密?

java - KeyFactory 有哪些不同类型的实例?

linux - 如何在允许 Linux 中给定用户读/写的同时加密数据

java - hibernate 条件中的表达式

java - Selenium Java Provar - 为什么我的操作 moveToElement 不执行

security - 自定义 JBoss DataSorurce 密码加密?

java - 获取分配给剖面 View 中特定剖面的所有作业

java - 如何使用 native Java 创建证书签名请求