试图用bouncycastle加密时出现错误

问题描述 投票:0回答:1

我正在尝试使用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)
java aes bouncycastle
1个回答
2
投票

你没有把你认为的东西传入 encrypt() 方法,你传递的是编码的字符串内容,而不是你创建的几行键数组。

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

你要传递的是编码的字符串内容,而不是你创建的几行键数组。

© www.soinside.com 2019 - 2024. All rights reserved.