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

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

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes the specified byte to this output stream.

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();//from   w w  w .  j  a v  a  2s .com
    // 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();

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

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