尝试使用bouncycastle抛出错误进行加密



我正在尝试使用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)

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

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

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

相关内容

  • 没有找到相关文章

最新更新