Input stream encryption

674 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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.