AES/CBC/PKCS5Padding issue

前端 未结 2 1982
长发绾君心
长发绾君心 2021-02-06 17:08

I am trying to encrypt and decrypt some simple text. But for some reason I am getting a strange error: javax.crypto.BadPaddingException. Why would JCE generates byt

相关标签:
2条回答
  • 2021-02-06 17:49

    Cipher.update returns a byte[] as well. So you are missing part of the encrypted data when you go to decrypt. Update the last section to read as follows:

    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    c.init(Cipher.ENCRYPT_MODE, k, iv);
    byte[] someData = c.update(textData);
    byte[] moreData = c.doFinal();
    
    System.out.println("E: " + (someData.length + moreData.length));
    
    c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    c.init(Cipher.DECRYPT_MODE, k, iv);
    byte[] someDecrypted = c.update(someData);
    byte[] moreDecrypted = c.doFinal(moreData);
    
    System.out.println("R: " + (someDecrypted.length + moreDecrypted.length));
    
    0 讨论(0)
  • 2021-02-06 18:10

    You can forgo the calls to update and just pass the byte[] data directly to doFinal performing the operation of encrypting or decrypting in one step.

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