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!
-
private static void doCrypto(int cipherMode, String key, File inputFile, File outputFile) throws CryptoException {
try {
SecretKey secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION, "IAIK");
cipher.init(cipherMode, secretKey);
FileInputStream inputStream = new FileInputStream(inputFile);
byte[] inputBytes = new byte[(int) inputFile.length()];
inputStream.read(inputBytes);
byte[] outputBytes = cipher.doFinal(inputBytes);
FileOutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);
inputStream.close();
outputStream.close();
} catch (NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException | BadPaddingException
| IllegalBlockSizeException | IOException ex) {
throw new CryptoException("Error encrypting/decrypting file", ex);
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for above method when I am giving 128 bit key it works fine as below,
KeyGenerator keyGen = KeyGenerator.getInstance("Twofish", "IAIK");
keyGen.init(192);
txtSecretKey.setText(iaik.utils.Util.toString(key.getEncoded()));
SekertKey key = key.generateKey();
encrypt(txtSecretKey.getText(), inputFile, encryptedFile);
Caused by: java.security.InvalidKeyException: Key must be 128, 192, or 256 bit long!
at iaik.security.cipher.N.a(Unknown Source)
at iaik.security.cipher.i.a(Unknown Source)
at iaik.security.cipher.a.engineInit(Unknown Source)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1189)
at com.opensourse.crypto.twofish.CryptoUtils.doCrypto(CryptoUtils.java:38)