Example usage for org.bouncycastle.jcajce.io CipherOutputStream flush

List of usage examples for org.bouncycastle.jcajce.io CipherOutputStream flush

Introduction

In this page you can find the example usage for org.bouncycastle.jcajce.io CipherOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream by forcing any buffered output bytes that have already been processed by the encapsulated cipher object to be written out.

Usage

From source file:com.joyent.manta.util.CipherClonerTest.java

License:Open Source License

private void canCloneCipher(final SupportedCipherDetails cipherDetails) throws Exception {
    final SecretKey secretKey = SecretKeyUtils.generate(cipherDetails);
    final byte[] iv = cipherDetails.generateIv();
    final byte[] inputData = RandomUtils.nextBytes(cipherDetails.getBlockSizeInBytes() * 3);

    // notice we are specifically calling getBouncyCastleCipher()
    final Cipher originalCipher = cipherDetails.getBouncyCastleCipher();
    originalCipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

    final Cipher clonedCipher = new CipherCloner().createClone(originalCipher);

    final ByteArrayOutputStream originalOutput = new ByteArrayOutputStream();
    final CipherOutputStream originalCipherOutput = new CipherOutputStream(originalOutput, originalCipher);
    originalCipherOutput.write(inputData);
    originalCipherOutput.flush();
    // we don't want to close originalCipherOutput because that would finalize originalCipher
    // and allow it to be reused below

    final ByteArrayOutputStream clonedOutput = new ByteArrayOutputStream();
    final CipherOutputStream clonedCipherOutput = new CipherOutputStream(clonedOutput, clonedCipher);
    clonedCipherOutput.write(inputData);
    clonedCipherOutput.flush();//from  ww w .j  a v  a2s. com

    final byte[] originalEncrypted = originalOutput.toByteArray();
    final byte[] clonedEncrypted = clonedOutput.toByteArray();

    Assert.assertEquals(originalEncrypted.length, clonedEncrypted.length);
    AssertJUnit.assertArrayEquals(originalEncrypted, clonedEncrypted);
}