AES Error: Given final block not properly padded

前端 未结 2 514
Happy的楠姐
Happy的楠姐 2021-01-01 07:57

I need help with this error: Given final block not properly padded. As you can see from the title, I am working with AES.

Here is the code of line where is error:

相关标签:
2条回答
  • 2021-01-01 08:15

    You have two problems, first you encode the output into a hex string but don't decode back from it in the decode method. Second you generate an random IV but don't use it again to decode.

    public byte[] encrypt(String plainText) throws Exception {
       byte[] iv = new byte[cipher.getBlockSize()];    
       AlgorithmParameterSpec spec = new IvParameterSpec(iv);
       cipher.init(Cipher.ENCRYPT_MODE, key, spec);
       return cipher.doFinal(plainText.getBytes());
    }
    
    public String decrypt(byte[] cryptedText) throws Exception {
       byte[] iv = new byte[cipher.getBlockSize()];
       AlgorithmParameterSpec spec = new IvParameterSpec(iv);
       cipher.init(Cipher.DECRYPT_MODE, key, spec);
       // decrypt the message
       byte[] decrypted = cipher.doFinal(cryptedText);
       decryptedText = new String(decrypted, "UTF-8");
       return decryptedText;
    }
    
    
    
    String decryptedText = aes.decrypt(aes.encrypt(message)).toString();     
    
    0 讨论(0)
  • 2021-01-01 08:38

    Per your comment, you are pretty close to getting the crypto working.

    You need to move the IV generation code from your encryption/decryption methods to somewhere else, like so

    public AlgorithmParameterSpec getIV() {
    AlgorithmParameterSpec ivspec;
    byte[] iv = new byte[cipher.getBlockSize()];
    new SecureRandom().nextBytes(iv);
    ivspec = new IvParameterSpec(iv);
    }
    

    then pass that ivspec into both the encrypt and decrypt methods (making them look like encrypt(String,AlgorithmParameterSpec)), so that you have the same iv for both encryption and decryption.

    Also, don't call printBase64Binary on the decryptedByteArray, instead call new String(decryptedByteArray, "UTF-8")

    0 讨论(0)
提交回复
热议问题