Skip to Main Content

Java Security

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Getting a java.security.InvalidAlgorithmParameterException: Wrong IV length

843810Jan 30 2004 — edited Feb 2 2004
Hello,
I am trying to encrypt a string within the same class. I am using the same key for both encrypting and decrypting. Not being familiar with JCE I am not sure what the exception here means -

java.security.InvalidAlgorithmParameterException: Wrong IV length: must be 8 bytes long. I am using JDK 1.4.2.

Here is the code for encrypting and decrypting(its adapted from the Scott Oaks book) -

private AToken getSOAPAuthToken(String p_userName) throws Exception
{
KeyGenerator kg = KeyGenerator.getInstance("DES");
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
Key key = kg.generateKey();
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("keyFile"));
oos.writeObject(key);
c.init(Cipher.ENCRYPT_MODE,key);
byte input[] = p_userName.getBytes();
byte encrypted[] = c.doFinal(input);
String userToken = new sun.misc.BASE64Encoder().encode(input);
String userVector = new sun.misc.BASE64Encoder().encode(encrypted);
AToken sat = new AToken(userToken,userVector);
return aToken;
}
private void decryptToken(AToken p_sat) throws Exception
{
Cipher c = Cipher.getInstance("DES/CBC/PKCS5Padding");
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("keyFile"));
Key key = (Key)ois.readObject();
String userVector = p_sat.getUserToken();
byte iv[] = new sun.misc.BASE64Decoder().decodeBuffer(userVector);
IvParameterSpec dps = new IvParameterSpec(iv);
c.init(Cipher.DECRYPT_MODE, key,dps);
byte encrypted[] = new sun.misc.BASE64Decoder().decodeBuffer(p_sat.getUserToken());
byte output[] = c.doFinal(encrypted);
s_logger.info("The value of output is " + new String(output));
}

Comments

843810
The answer is in the exception message. When using DES/CBC, you need an initialization vector of 8 bytes. These 8 bytes are needed for the CBC. You need the IV both for encryption and decryption (and the IV should be the same for both operations).

Cheers,

--Arnout

1 - 1
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Mar 1 2004
Added on Jan 30 2004
1 comment
1,592 views