简体   繁体   English

鉴于最终阻塞没有正确填充AES256

[英]Given final block not properly padded AES256

I have a key, and the I want to decrypt the data using this key, but Given final block not properly padded error appears. 我有一个密钥,我想用这个密钥解密数据,但是给出最后一个块没有正确填充错误出现。

 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));
    byte[] encryptedBytes_updates = cipher.update(encryptedBytes);
    String decryptedText = new String(cipher.doFinal(encryptedBytes_updates));

I tried some advices from forums, but no luck. 我试过一些来自论坛的建议,但没有运气。

May be someone can help? 可能有人可以帮忙吗?

If the message you're decoding is less than 16 bytes, one of the issues may be that you're using the wrong IV. 如果您正在解码的消息少于16个字节,则其中一个问题可能是您使用了错误的IV。 Specifically, this line is incorrect: 具体来说,这一行不正确:

cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()]));

You're creating an IvParameterSpec from a byte array of all 0's (because you just created it, but didn't fill it with any data). 你是从所有0的字节数组创建一个IvParameterSpec (因为你刚创建它,但没有用任何数据填充它)。 If you're doing the same thing while encrypting, this is the reason encryption/decryption works locally for you. 如果您在加密时做同样的事情,这就是加密/解密在本地为您工作的原因。

What you need to do is create the IvParameterSpec using a byte array containing the IV that the server sends you. 您需要做的是使用包含服务器发送给您的IV的字节数组创建IvParameterSpec If the server isn't sending you the IV in a separate field, it may be that the IV has been prepended or appended to the encrypted data you receive (this is a fairly common practice). 如果服务器没有在单独的字段中向您发送IV,则可能是IV已经预先附加或附加到您收到的加密数据(这是一种相当普遍的做法)。 I would trying pulling off the first block (16 bytes) of the encrypted data and use that as the IV. 我会尝试拉出加密数据的第一个块(16个字节)并将其用作IV。 If that doesn't work, try the last block of encrypted data. 如果这不起作用,请尝试最后一块加密数据。 Or better yet, ask whoever runs the server or read the manual to determine where to get the IV from. 或者更好的是,询问运行服务器的人员或阅读手册以确定从何处获取IV。

Also, this looks incorrect as well: 此外,这看起来也不正确:

byte[] encryptedBytes_updates = cipher.update(encryptedBytes);
String decryptedText = new String(cipher.doFinal(encryptedBytes_updates));

Why would you take encryptedBytes_updates and feed it back in to the cipher? 为什么要使用encryptedBytes_updates并将其反馈给密码? update decrypts the data, then you're trying to decrypt it again using doFinal . update解密数据,然后您尝试使用doFinal再次解密它。 Do this instead: 改为:

String decryptedText = new String(cipher.doFinal(encryptedBytes));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM