【问题标题】:trying to encrypt with bouncycastle throw error尝试使用 bouncycastle 加密引发错误
【发布时间】:2020-04-24 08:01:15
【问题描述】:

我正在尝试使用 bouncycastle jar 加密我的代码:

private static byte[] encrypt(byte[] plain, byte[] key, byte[] iv) throws Exception
{
    PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher(
            new AESEngine()));
    CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv);
    aes.init(true, ivAndKey);
    return cipherData(aes, plain);
}

这是我的主要内容:

    String msg="hello";
    String key="123";

    SecureRandom secureRandom = new SecureRandom();
    byte[] keyB = new byte[16];
    secureRandom.nextBytes(keyB);
    SecretKey secretKey = new SecretKeySpec(keyB, "AES");

    byte[] enc=encrypt(msg.getBytes(),key.getBytes(),keyB);

    System.out.println(new String(enc));

但我/我得到了

Exception in thread "main" java.lang.IllegalArgumentException: Key length not 128/192/256 bits.
    at org.bouncycastle.crypto.engines.AESEngine.generateWorkingKey(Unknown Source)
    at org.bouncycastle.crypto.engines.AESEngine.init(Unknown Source)
    at org.bouncycastle.crypto.modes.CBCBlockCipher.init(Unknown Source)
    at org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher.init(Unknown Source)
    at Aes.encrypt(Aes.java:122)
    at Aes.main(Aes.java:47)

【问题讨论】:

  • 异常消息会告诉您确切的问题所在。您的密钥长度不是可接受的位数。
  • 16 字节是 128 位 @T_Bacon
  • 当然,但是key.getBytes() 不会返回 128 位,是吗?
  • 作为一个快速测试,运行System.out.println(key.getBytes().length),您会看到它实际上是 3 个字节,因此只有 24 位。

标签: java aes bouncycastle


【解决方案1】:

您没有将您认为的内容传递给encrypt() 方法:

String key="123";
…
byte[] enc=encrypt(msg.getBytes(),key.getBytes(),keyB);

您传递的是编码字符串内容,而不是您在其中创建几行的键数组。

【讨论】:

  • 这种错误在调试器中很容易找到。
猜你喜欢
  • 2021-10-23
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 2017-03-17
  • 1970-01-01
  • 1970-01-01
  • 2020-12-21
  • 2013-01-13
相关资源
最近更新 更多