数据不是块大小对齐

数据不是块大小对齐

本文介绍了如何解决javax.crypto.IllegalBlockSizeException:数据不是块大小对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个关于使用河豚进行加密的任务。 java中的解密。

I am doing an assignment about use blowfish to do encryption & decryption in java.

我添加了一个提供程序,并获得了实例Blowfish / ECB / NoPadding,但是当我进行加密时仍然会出现此错误。

I had added a provider, and get instance "Blowfish/ECB/NoPadding", but I still get this error when I do the encryption.

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

例如:

public static byte[] encrypt(byte to_encrypt[], byte strkey[]) {
    try {
        SecretKeySpec key = new SecretKeySpec(strkey, "Blowfish");
        Cipher cipher = Cipher.getInstance("Blowfish/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(to_encrypt); // <=========== error
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

导致

javax.crypto.IllegalBlockSizeException: data not block size aligned
    at org.bouncycastle2.jce.provider.JCEBlockCipher.engineDoFinal(JCEBlockCipher.java:686)
    at javax.crypto.Cipher.doFinal(Cipher.java:1171)

谢谢。

推荐答案

您已明确要求提供商不进行填充(请注意 NoPadding 在实例名称中)。因此,您的输入将不会被填充。

You've explicitly asked for a provider that doesn't do padding (notice the NoPadding in the instance name). Consequently, your input will not be padded.

此外,这是一个分组密码,因此输入必须是块长度的倍数。由于加密提供程序没有填充,您需要确保输入是块大小的倍数,否则加密/解密将无法进行,您将收到此错误。

Furthermore, this is a block cipher, so the input must be a multiple of the block length. With the crypto provider not doing padding, you need to ensure yourself that your input is a multiple of the block size, else encryption/decryption will not be possible and you'll get this error.

因此,您有两个选项可以解决此问题:

Thus you have two options in order to solve this:


  1. 将输入自行填充到块大小的倍数。

  2. 如果您不想手动执行,请选择执行填充的提供程序(例如 PKCS5Padding )。鉴于您的问题的性质,这可能是最好的选择。

  1. Pad the input yourself to a multiple of the block size.
  2. Choose a provider that does padding (e.g. PKCS5Padding), if you don't want to do it manually. Given the nature of your question, this is likely to be the best option.

这篇关于如何解决javax.crypto.IllegalBlockSizeException:数据不是块大小对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 00:22