Skip to content
Advertisement

Getting java.security.InvalidKeyException: Key must be 128, 192, or 256 bit long twofish

Following code is written to encrypt the plain text, I am using IAIK Twofish encryption/decryption code in java below sample code works fine with 128 bit key but when i try it with 192 and 156 bit key it gives an exception that java.security.InvalidKeyException: Key must be 128, 192, or 256 bit long!

JavaScript

for above method when I am giving 128 bit key it works fine as below,

JavaScript

Advertisement

Answer

In your main method you’re transforming the SecretKey to a String that is shown in a (GUI) textfield. Printing out the contents of the key looks like:

JavaScript

Converting this String in the textfield back to a byte[] to regenerate the secretKey with “.getBytes” will fail as the colon chars will be decoded as well:

JavaScript

The IAIK-Util-class provides a “.toByteArray” method that simply ignores other chars than ‘0-9’ and ‘a-f’, see the documentation in http://javadoc.iaik.tugraz.at/iaik_jce/current/iaik/utils/Util.html:

Convert the given string with hex values to a byte array. For example “001122” is turned into {0, 0x11, 0x22}. All characters outside the range of ‘0’-‘9’, ‘a’-‘z’, and ‘A’-‘Z’ or simply ignored.

Simply change the line in doCrypto-method and all is working:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement