Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

android - java.security.InvalidKeyException: Illegal key size

When I run this code in Android it produces no errors, but when I run it in a standard Java program it produces the exception: java.security.InvalidKeyException: Illegal key size.

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(CHUNK_ENCRYPTION_KEY.getBytes(), 0, 32, "AES");
IvParameterSpec initVector = new IvParameterSpec(AES_INITIALIZATION_VECTOR.getBytes(), 0 , 16);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, initVector);

CHUNK_ENCRYPTION_KEY is a 32 byte key hard-coded into the program. AES_INITIALIZATION_VECTOR is a 16 byte hard-coded initialization vector.

Does anyone know why it would work on Android and not on a Desktop?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

On a default desktop JVM installation (using the JRE or JDK from Sun/Oracle), AES is limited to 128-bit key size. This is a remnant of import/export laws on cryptographic software. To unlock the larger AES key sizes, you need to download and apply the "JCE Unlimited Strength Jurisdiction Policy Files" (see at the bottom of this page).

The key size restriction is enforced by the code within the Cipher class. Changing cryptographic providers (e.g. to one of the Bouncy Castle or IAIK providers) won't let you circumvent this restriction.

On an unrelated note, you do not want to use the raw getBytes() method on a String, because the result depends on the current locale (not everyone uses UTF-8 or even ASCII-compatible encodings). If you do want to represent your key as a literal string, at least use an explicit encoding, such as: CHUNK_ENCRYPTION_KEY.getBytes("UTF-8")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...