Java AES 加密:给定的最终块未正确填充

Java AES encryption: Given final block not properly padded

我在 Java 中尝试使用 AES 加密时收到此错误。我使用的是 128 位密钥。我的目标是加密稍后将插入数据库的某些数据

我是加密新手,所以任何帮助都会很有用。

代码如下所示:

public class AES2 {
    private static final String algo = "AES/CBC/PKCS5Padding";
    private static final byte[] keyValue = 
        new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't','S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };

    public static String encrypt(String Data) throws Exception {

        //KeyGenerator KeyGen = KeyGenerator.getInstance("AES");
        //KeyGen.init(128);

        //SecretKey SecKey = KeyGen.generateKey();
        Key key=generateKey();

        //generar IV
        byte[] iv = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        //cifrar
        Cipher c = Cipher.getInstance(algo);
        c.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);

        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();

        byte[] iv = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

        Cipher c = Cipher.getInstance(algo);
        c.init(Cipher.DECRYPT_MODE, key,ivParameterSpec);

        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

    private static Key generateKey() throws Exception {
        Key key = new SecretKeySpec(keyValue, "AES");
        return key;
}
}

Main class:

public class aesMain {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {

        String texto = "hola mama";
        String encryptedText=AES2.encrypt(texto);
        String decryptedText=AES2.decrypt(encryptedText);


        System.out.println("Plain text : " + texto);
        System.out.println("Encrypted Text : " + encryptedText);
        System.out.println("Decrypted Text : " + decryptedText);
    }

}

关于填充错误的事情是,它们通常不是填充中的错误,而是解密过程中的错误密钥或 IV。删除填充之前的明文将导致随机字节,然后可能被报告为错误填充。

在这种情况下,不同的 IV 用于加密和解密。然而,IV 在加密和解密期间必须相同。一个常见的过程是在加密过程中创建一个随机 IV,并将其作为密文的前缀。在解密之前,IV 被检索并从密文中剥离。

请参阅 Cipher Block Chaining 了解不正确的 IV 将如何影响解密。