【问题标题】:Error while encrypting/decrypting byte arrays: IllegalBlockSizeException:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH加密/解密字节数组时出错:IllegalBlockSizeException:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
【发布时间】:2021-10-16 09:22:54
【问题描述】:

我正在使用密码加密和解密 android 中的字节数组以发送到服务器。我没有使用字符串,但我仍然收到非法块大小异常。

                try {
                    byte[] cipherNameText = {};

                    KeyGenerator keygen = null;
                    keygen = KeyGenerator.getInstance("AES");
                    keygen.init(256);
                    SecretKey key= keygen.generateKey();

                    String name = nameEdit.getText().toString();

                    Cipher cipher = null;
                    cipher = Cipher.getInstance("AES_256/CBC/NoPadding");
                    SecureRandom iv = new SecureRandom();
                    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
                    cipherNameText = cipher.doFinal(name.getBytes(StandardCharsets.UTF_8));
                    byte[] iv1 = cipher.getIV();

                    HashMap<String, byte[]> map = new HashMap<>();
                    map.put("name",key.toString().getBytes(StandardCharsets.UTF_8));

                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                } catch (NoSuchPaddingException e) {
                    e.printStackTrace();
                } catch (BadPaddingException e) {
                    e.printStackTrace();
                } catch (IllegalBlockSizeException e) {
                    e.printStackTrace();
                } catch (InvalidKeyException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

2021-08-12 20:55:17.606 15222-15222/com.example.package W/System.err: javax.crypto.IllegalBlockSizeException: error:1e00006a:Cipher functions:OPENSSL_internal:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH

2021-08-12 21:51:47.322 15606-15606/com.example.package W/System.err:在 com.example.servertutorial.MainActivity$4.onClick(MainActivity.java:212)

^this 指向“cipherNameText = cipher.doFinal(name.getBytes(StandardCharsets.UTF_8));”

【问题讨论】:

  • 通过使用NoPadding,您已承诺要加密的数据的长度是块大小(16 字节)的倍数。使用不同的填充模式,或自己填充数据。请参阅this answer 了解更多信息。

标签: java android encryption


【解决方案1】:

正如迈克尔指出的那样,问题在于使用NoPadding。消息大小不适合 AES 的块大小。填充消息可以解决这个问题。

变化:

                    cipher = Cipher.getInstance("AES_256/CBC/NoPadding");

收件人:

                            cipher = Cipher.getInstance("AES_256/CBC/PKCS5PADDING");

【讨论】:

    猜你喜欢
    • 2017-10-29
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多