I'm struggling to get an encryption program to run as i'm trying to use Twofish. Is there a way to use cipherinputstream, or cipheroutputstream with an algorithm in a different package? or a way to put the Twofish algorithm into java.crypto.cipher? or is there a better way to do it?
Asked
Active
Viewed 653 times
0
-
which Twofish implementation are you using? – jtahlborn Jul 23 '15 at 15:45
1 Answers
0
Java doesn't have a twofish implementation by itself, so you need to use a cryptographic (JCA/JCE) provider that has one, such as Bouncy Castle:
public class TwofishInStreams {
public static void main(String[] args) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Cipher twofish = Cipher.getInstance("twofish/cbc/pkcs5padding");
SecretKey twoFishKey = new SecretKeySpec(new byte[16], "twofish");
IvParameterSpec iv = new IvParameterSpec(new byte[16]);
twofish.init(Cipher.ENCRYPT_MODE, twoFishKey, iv);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (CipherOutputStream cos = new CipherOutputStream(baos, twofish)) {
cos.write("owlstead".getBytes(StandardCharsets.UTF_8));
}
System.out.println(Hex.toHexString(baos.toByteArray()));
}
}
Please read the Bouncy Castle documentation on how to use the provider and don't forget to install the unlimited crypto files from Oracle.
Obviously this is just an example: you should not use a zero byte key or zero byte IV like this.

Maarten Bodewes
- 90,524
- 13
- 150
- 263