Search in sources :

Example 36 with CipherOutputStream

use of javax.crypto.CipherOutputStream in project jdk8u_jdk by JetBrains.

the class CICO method runTest.

public void runTest(String algo, String mo, String pad, int whichRead) throws Exception {
    Cipher ci1 = null;
    Cipher ci2 = null;
    byte[] iv = null;
    AlgorithmParameterSpec aps = null;
    SecretKey key = null;
    try {
        // Do initialization
        Random rdm = new Random();
        rdm.nextBytes(plainText);
        KeyGenerator kg = KeyGenerator.getInstance(algo, PROVIDER);
        if (!kg.getAlgorithm().equals(algo)) {
            throw new RuntimeException("Unexpected algorithm <" + kg.getAlgorithm() + ">, expected value is <" + algo + ">");
        }
        kg.init(KEY_LENGTH);
        key = kg.generateKey();
        ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        if (mo.equalsIgnoreCase("ECB")) {
            ci1.init(Cipher.ENCRYPT_MODE, key);
        } else {
            ci1.init(Cipher.ENCRYPT_MODE, key, aps);
        }
        if (!mo.equalsIgnoreCase("ECB")) {
            iv = ci1.getIV();
            aps = new IvParameterSpec(iv);
        } else {
            aps = null;
        }
        ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, PROVIDER);
        if (mo.equalsIgnoreCase("ECB")) {
            ci2.init(Cipher.DECRYPT_MODE, key);
        } else {
            ci2.init(Cipher.DECRYPT_MODE, key, aps);
        }
        ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
        try (CipherInputStream ciInput = new CipherInputStream(baInput, ci1);
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput, ci2)) {
            // mark and reset methods
            if (ciInput.markSupported()) {
                throw new RuntimeException("CipherInputStream unexpectedly supports the mark and reset methods");
            }
            // of buffering : byte[] and int
            switch(whichRead) {
                case 0:
                    int buffer0 = ciInput.read();
                    while (buffer0 != -1) {
                        ciOutput.write(buffer0);
                        buffer0 = ciInput.read();
                    }
                    break;
                case 1:
                    byte[] buffer1 = new byte[20];
                    int len1 = ciInput.read(buffer1);
                    while (len1 != -1) {
                        ciOutput.write(buffer1, 0, len1);
                        len1 = ciInput.read(buffer1);
                    }
                    break;
                case NREADS - 1:
                    byte[] buffer2 = new byte[ci1.getOutputSize(plainText.length)];
                    int offset2 = 0;
                    int len2 = 0;
                    while (len2 != -1) {
                        len2 = ciInput.read(buffer2, offset2, buffer2.length - offset2);
                        offset2 += len2;
                    }
                    ciOutput.write(buffer2, 0, buffer2.length);
                    break;
            }
        }
        // Get the output
        byte[] recoveredText = new byte[baOutput.size()];
        recoveredText = baOutput.toByteArray();
        if (!java.util.Arrays.equals(plainText, recoveredText)) {
            throw new RuntimeException("Original text is not equal with recovered text, with " + algo + "/" + mo + "/" + pad + "/" + whichRead);
        }
    // Compare input and output
    } catch (NoSuchAlgorithmException e) {
        //OFB20 is for negative testing
        if (!mo.equalsIgnoreCase("OFB20")) {
            System.out.println("Unexpected NoSuchAlgorithmException with " + algo + "/" + mo + "/" + pad + "/" + whichRead);
            throw new RuntimeException("Test failed!");
        }
    } catch (IOException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) {
        System.out.println("Unexpected Exception with " + algo + "/" + mo + "/" + pad + "/" + whichRead);
        System.out.println("Test failed!");
        throw e;
    }
}
Also used : CipherOutputStream(javax.crypto.CipherOutputStream) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) CipherInputStream(javax.crypto.CipherInputStream) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) InvalidKeyException(java.security.InvalidKeyException) SecretKey(javax.crypto.SecretKey) Random(java.util.Random) ByteArrayInputStream(java.io.ByteArrayInputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) NoSuchProviderException(java.security.NoSuchProviderException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Example 37 with CipherOutputStream

use of javax.crypto.CipherOutputStream in project jackrabbit-oak by apache.

the class UDPBroadcaster method encrypt.

byte[] encrypt(byte[] data) {
    if (encryptCipher == null) {
        return data;
    }
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, encryptCipher);
        cipherOutputStream.write(data);
        cipherOutputStream.flush();
        cipherOutputStream.close();
        byte[] encryptedBytes = outputStream.toByteArray();
        return encryptedBytes;
    } catch (IOException e) {
        LOG.debug("encrypt failed", e);
        throw new RuntimeException(e);
    }
}
Also used : CipherOutputStream(javax.crypto.CipherOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 38 with CipherOutputStream

use of javax.crypto.CipherOutputStream in project bnd by bndtools.

the class PasswordCryptor method encrypt.

public OutputStream encrypt(char[] password, OutputStream out) throws Exception {
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
    final Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    return new CipherOutputStream(out, cipher);
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) SecretKey(javax.crypto.SecretKey) CipherOutputStream(javax.crypto.CipherOutputStream) Cipher(javax.crypto.Cipher)

Example 39 with CipherOutputStream

use of javax.crypto.CipherOutputStream in project apex-malhar by apache.

the class AbstractFileOutputOperatorTest method testChainFilters.

@Test
public void testChainFilters() throws NoSuchAlgorithmException, IOException {
    EvenOddHDFSExactlyOnceWriter writer = new EvenOddHDFSExactlyOnceWriter();
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(128);
    final SecretKey secretKey = keygen.generateKey();
    byte[] iv = "TestParam16bytes".getBytes();
    final IvParameterSpec ivps = new IvParameterSpec(iv);
    FilterStreamProvider.FilterChainStreamProvider<FilterOutputStream, OutputStream> chainStreamProvider = new FilterStreamProvider.FilterChainStreamProvider<FilterOutputStream, OutputStream>();
    chainStreamProvider.addStreamProvider(new FilterStreamCodec.GZipFilterStreamProvider());
    // The filter is to keep track of the offsets to handle multi member gzip issue with openjdk
    // http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4691425
    final CounterFilterStreamContext evenCounterContext = new CounterFilterStreamContext();
    final CounterFilterStreamContext oddCounterContext = new CounterFilterStreamContext();
    chainStreamProvider.addStreamProvider(new FilterStreamProvider.SimpleFilterReusableStreamProvider<CounterFilterOutputStream, OutputStream>() {

        @Override
        protected FilterStreamContext<CounterFilterOutputStream> createFilterStreamContext(OutputStream outputStream) throws IOException {
            if (evenCounterContext.isDoInit()) {
                evenCounterContext.init(outputStream);
                return evenCounterContext;
            } else {
                oddCounterContext.init(outputStream);
                return oddCounterContext;
            }
        }
    });
    chainStreamProvider.addStreamProvider(new FilterStreamProvider.SimpleFilterReusableStreamProvider<CipherOutputStream, OutputStream>() {

        @Override
        protected FilterStreamContext<CipherOutputStream> createFilterStreamContext(OutputStream outputStream) throws IOException {
            try {
                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
                cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivps);
                return new FilterStreamCodec.CipherFilterStreamContext(outputStream, cipher);
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
    });
    writer.setFilterStreamProvider(chainStreamProvider);
    File evenFile = new File(testMeta.getDir(), EVEN_FILE);
    File oddFile = new File(testMeta.getDir(), ODD_FILE);
    List<Long> evenOffsets = new ArrayList<Long>();
    List<Long> oddOffsets = new ArrayList<Long>();
    writer.setFilePath(testMeta.getDir());
    writer.setAlwaysWriteToTmp(false);
    writer.setup(testMeta.testOperatorContext);
    for (int i = 0; i < 10; ++i) {
        writer.beginWindow(i);
        for (int j = 0; j < 1000; ++j) {
            writer.input.put(i);
        }
        writer.endWindow();
        if ((i % 2) == 1) {
            writer.beforeCheckpoint(i);
            evenOffsets.add(evenCounterContext.getCounter());
            oddOffsets.add(oddCounterContext.getCounter());
        }
    }
    writer.teardown();
    /*
    evenOffsets.add(evenFile.length());
    oddOffsets.add(oddFile.length());
    */
    checkCompressedFile(evenFile, evenOffsets, 0, 5, 1000, secretKey, iv);
    checkCompressedFile(oddFile, oddOffsets, 1, 5, 1000, secretKey, iv);
}
Also used : CipherOutputStream(javax.crypto.CipherOutputStream) FilterOutputStream(java.io.FilterOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) CipherOutputStream(javax.crypto.CipherOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) KeyGenerator(javax.crypto.KeyGenerator) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) ConstraintViolationException(javax.validation.ConstraintViolationException) SecretKey(javax.crypto.SecretKey) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) FilterOutputStream(java.io.FilterOutputStream) File(java.io.File) Test(org.junit.Test)

Aggregations

CipherOutputStream (javax.crypto.CipherOutputStream)39 Cipher (javax.crypto.Cipher)27 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 IOException (java.io.IOException)13 SecretKeySpec (javax.crypto.spec.SecretKeySpec)9 CipherInputStream (javax.crypto.CipherInputStream)8 IvParameterSpec (javax.crypto.spec.IvParameterSpec)7 FileOutputStream (java.io.FileOutputStream)6 SecretKey (javax.crypto.SecretKey)6 OutputStream (java.io.OutputStream)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 NullCipher (javax.crypto.NullCipher)5 InvalidKeyException (java.security.InvalidKeyException)4 KeyGenerator (javax.crypto.KeyGenerator)4 BufferedOutputStream (java.io.BufferedOutputStream)3 DataOutputStream (java.io.DataOutputStream)3 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)3 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)3 AEADBlockCipher (org.bouncycastle.crypto.modes.AEADBlockCipher)3 GCMBlockCipher (org.bouncycastle.crypto.modes.GCMBlockCipher)3