I am attempting to encrypt/decrypt strings using AES-256-CBC and BouncyCastle. I have completed this for keys that are of length 16 bytes (128 bits) but I am required to use a key of 128 bytes (1024 bits).
I have read numerous suggestions on SO and found that the restricted policy files for the JVM I am using had not been installed. This, theoretically, should allow keys greater than 128 bits to be used. However, after installing the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction policy files to my jdk (1.6.0.jdk/Contents/Home/lib/security
) the issue remains.
The code I am using to encrypt a String
is as follows:
String my_key = "2bc7fa12d..." // String of length 128
Security.addProvider(new BouncyCastleProvider());
byte[] original = my_key.getBytes();
key = new SecretKeySpec(original, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
byte[] encryptedValue = Base64.encode(encrypted);
return new String(encryptedValue);
But after replacing the .jar's found in the Unlimited JCE download I still experience the error:
java.security.InvalidKeyException: Key length not 128/192/256 bits.
at org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher.engineInit(Unknown Source)
at javax.crypto.Cipher.init(DashoA13*..)
at javax.crypto.Cipher.init(DashoA13*..)
at EncyrptionTest.encrypt(EncyrptionTest.java:58)
at EncyrptionTest.main(EncyrptionTest.java:33)
Any advice or solutions to this issue would be greatly appreciated.
Edit:
As requested, the code I am trying to port from Ruby into Java is as follows:
WithCred.entials_for(:to_encrypt) do |c|
attr_encrypted :my_key,
:algorithm => 'aes-256-cbc',
:key => c[:key]
end
The gem it uses to encrypt (I believe) is attr_encypted. (I am afraid I know very little about Ruby)