Search code examples
javaaesbouncycastle

trying to encrypt with bouncycastle throw error


I am trying to encrypt using bouncycastle jar here my code:

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);
}

Here my main:

    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));

but I/m getting

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)

Solution

  • You're not passing what you think are into the encrypt() method:

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

    You're passing the encoded string content, NOT the key array you create a few lines in.