Search in sources :

Example 16 with CipherInputStream

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

the class CipherInputStreamExceptions method gcm_shortReadAEAD.

/* Short read stream,
     * This test
     *   1) Encrypt 100 bytes with AES/GCM/PKCS5Padding
     *   2) Reads 100 bytes from stream to decrypt the message and closes
     *   3) Make sure no value is returned by read()
     *   4) Make sure no exception is thrown
     */
static void gcm_shortReadAEAD() throws Exception {
    Cipher c;
    byte[] read = new byte[100];
    System.out.println("Running gcm_shortReadAEAD");
    byte[] pt = new byte[600];
    pt[0] = 1;
    // Encrypt provided 600 bytes with AES/GCM/PKCS5Padding
    byte[] ct = encryptedText("GCM", pt);
    // Create stream for decryption
    CipherInputStream in = getStream("GCM", ct);
    int size = 0;
    try {
        size = in.read(read);
        in.close();
        if (read.length != 100) {
            throw new RuntimeException("Fail: read size = " + read.length + "should be 100.");
        }
        if (read[0] != 1) {
            throw new RuntimeException("Fail: The decrypted text does " + "not match the plaintext: '" + read[0] + "'");
        }
    } catch (IOException e) {
        System.out.println("  Fail: " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
    System.out.println("  Pass.");
}
Also used : RuntimeException(java.lang.RuntimeException) CipherInputStream(javax.crypto.CipherInputStream) Cipher(javax.crypto.Cipher) IOException(java.io.IOException)

Example 17 with CipherInputStream

use of javax.crypto.CipherInputStream in project AndroidChromium by JackyAndroid.

the class TabState method readState.

/**
     * Restores a particular TabState file from storage.
     * @param input Location of the TabState file.
     * @param encrypted Whether the file is encrypted or not.
     * @return TabState that has been restored, or null if it failed.
     */
private static TabState readState(FileInputStream input, boolean encrypted) throws IOException {
    DataInputStream stream = null;
    if (encrypted) {
        Cipher cipher = CipherFactory.getInstance().getCipher(Cipher.DECRYPT_MODE);
        if (cipher != null) {
            stream = new DataInputStream(new CipherInputStream(input, cipher));
        }
    }
    if (stream == null) {
        stream = new DataInputStream(input);
    }
    try {
        if (encrypted && stream.readLong() != KEY_CHECKER) {
            // Got the wrong key, skip the file
            return null;
        }
        TabState tabState = new TabState();
        tabState.timestampMillis = stream.readLong();
        int size = stream.readInt();
        if (encrypted) {
            // If it's encrypted, we have to read the stream normally to apply the cipher.
            byte[] state = new byte[size];
            stream.readFully(state);
            tabState.contentsState = new WebContentsState(ByteBuffer.allocateDirect(size));
            tabState.contentsState.buffer().put(state);
        } else {
            // If not, we can mmap the file directly, saving time and copies into the java heap.
            FileChannel channel = input.getChannel();
            tabState.contentsState = new WebContentsState(channel.map(MapMode.READ_ONLY, channel.position(), size));
            // Skip ahead to avoid re-reading data that mmap'd.
            long skipped = input.skip(size);
            if (skipped != size) {
                Log.e(TAG, "Only skipped " + skipped + " bytes when " + size + " should've " + "been skipped. Tab restore may fail.");
            }
        }
        tabState.parentId = stream.readInt();
        try {
            tabState.openerAppId = stream.readUTF();
            if ("".equals(tabState.openerAppId))
                tabState.openerAppId = null;
        } catch (EOFException eof) {
            // Could happen if reading a version of a TabState that does not include the app id.
            Log.w(TAG, "Failed to read opener app id state from tab state");
        }
        try {
            tabState.contentsState.setVersion(stream.readInt());
        } catch (EOFException eof) {
            // On the stable channel, the first release is version 18. For all other channels,
            // chrome 25 is the first release.
            tabState.contentsState.setVersion(isStableChannelBuild() ? 0 : 1);
            // Could happen if reading a version of a TabState that does not include the
            // version id.
            Log.w(TAG, "Failed to read saved state version id from tab state. Assuming " + "version " + tabState.contentsState.version());
        }
        try {
            tabState.syncId = stream.readLong();
        } catch (EOFException eof) {
            tabState.syncId = 0;
            // Could happen if reading a version of TabState without syncId.
            Log.w(TAG, "Failed to read syncId from tab state. Assuming syncId is: 0");
        }
        try {
            tabState.shouldPreserve = stream.readBoolean();
        } catch (EOFException eof) {
            // Could happen if reading a version of TabState without this flag set.
            tabState.shouldPreserve = false;
            Log.w(TAG, "Failed to read shouldPreserve flag from tab state. " + "Assuming shouldPreserve is false");
        }
        tabState.mIsIncognito = encrypted;
        try {
            tabState.themeColor = stream.readInt();
            tabState.mHasThemeColor = true;
        } catch (EOFException eof) {
            // Could happen if reading a version of TabState without a theme color.
            tabState.themeColor = Color.WHITE;
            tabState.mHasThemeColor = false;
            Log.w(TAG, "Failed to read theme color from tab state. " + "Assuming theme color is white");
        }
        return tabState;
    } finally {
        stream.close();
    }
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) FileChannel(java.nio.channels.FileChannel) EOFException(java.io.EOFException) Cipher(javax.crypto.Cipher) DataInputStream(java.io.DataInputStream)

Example 18 with CipherInputStream

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

the class UDPBroadcaster method decrypt.

byte[] decrypt(byte[] data) {
    if (decryptCipher == null) {
        return data;
    }
    try {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ByteArrayInputStream inStream = new ByteArrayInputStream(data);
        CipherInputStream cipherInputStream = new CipherInputStream(inStream, decryptCipher);
        byte[] buf = new byte[1024];
        int bytesRead;
        while ((bytesRead = cipherInputStream.read(buf)) >= 0) {
            outputStream.write(buf, 0, bytesRead);
        }
        return outputStream.toByteArray();
    } catch (IOException e) {
        LOG.debug("decrypt failed", e);
        throw new RuntimeException(e);
    }
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException)

Example 19 with CipherInputStream

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

the class CICODESFuncTest method runTest.

private static void runTest(Provider p, String algo, String mo, String pad, ReadModel whichRead) throws GeneralSecurityException, IOException {
    // Do initialization
    byte[] plainText = TestUtilities.generateBytes(TEXT_LENGTH);
    byte[] iv = TestUtilities.generateBytes(IV_LENGTH);
    AlgorithmParameterSpec aps = new IvParameterSpec(iv);
    try {
        KeyGenerator kg = KeyGenerator.getInstance(algo, p);
        out.println(algo + "/" + mo + "/" + pad + "/" + whichRead);
        SecretKey key = kg.generateKey();
        Cipher ci1 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
        if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
            throw new RuntimeException("NoSuchAlgorithmException not throw when mode" + " is CFB72 or OFB20");
        }
        Cipher ci2 = Cipher.getInstance(algo + "/" + mo + "/" + pad, p);
        if ("ECB".equalsIgnoreCase(mo)) {
            ci1.init(Cipher.ENCRYPT_MODE, key);
            ci2.init(Cipher.DECRYPT_MODE, key);
        } else {
            ci1.init(Cipher.ENCRYPT_MODE, key, aps);
            ci2.init(Cipher.DECRYPT_MODE, key, aps);
        }
        ByteArrayOutputStream baOutput = new ByteArrayOutputStream();
        try (CipherInputStream cInput = new CipherInputStream(new ByteArrayInputStream(plainText), ci1);
            CipherOutputStream ciOutput = new CipherOutputStream(baOutput, ci2)) {
            // Read from the input and write to the output using 2 types
            // of buffering : byte[] and int
            whichRead.read(cInput, ciOutput, ci1, plainText.length);
        }
        // Verify input and output are same.
        if (!Arrays.equals(plainText, baOutput.toByteArray())) {
            throw new RuntimeException("Test failed due to compare fail ");
        }
    } catch (NoSuchAlgorithmException nsaEx) {
        if ("CFB72".equalsIgnoreCase(mo) || "OFB20".equalsIgnoreCase(mo)) {
            out.println("NoSuchAlgorithmException is expected for CFB72 and OFB20");
        } else {
            throw new RuntimeException("Unexpected exception testing: " + algo + "/" + mo + "/" + pad + "/" + whichRead, nsaEx);
        }
    }
}
Also used : SecretKey(javax.crypto.SecretKey) CipherOutputStream(javax.crypto.CipherOutputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AlgorithmParameterSpec(java.security.spec.AlgorithmParameterSpec) KeyGenerator(javax.crypto.KeyGenerator)

Example 20 with CipherInputStream

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

the class LengthLimitException method runTest.

private static void runTest(Cipher[] pair, String info, ReadMethod whichRead) throws IOException {
    byte[] plainText = TestUtilities.generateBytes(PLAIN_TEXT_LENGTH);
    out.println("Testing: " + info + "/" + whichRead);
    try (ByteArrayInputStream baInput = new ByteArrayInputStream(plainText);
        CipherInputStream ciInput1 = new CipherInputStream(baInput, pair[0]);
        CipherInputStream ciInput2 = new CipherInputStream(ciInput1, pair[1])) {
        // Skip 5 bytes after read 45 bytes and repeat until finish
        // (Read from the input and write to the output using 2 types
        // of buffering : byte[] and int)
        // So output has size:
        // (OVERALL/BLOCK)* SAVE = (800 / 50) * 45 = 720 bytes
        int numOfBlocks = plainText.length / BLOCK;
        // Output buffer.
        byte[] outputText = new byte[numOfBlocks * SAVE];
        int index = 0;
        for (int i = 0; i < numOfBlocks; i++) {
            index = whichRead.readByte(ciInput2, outputText, SAVE, index);
            // discard bytes, otherwise try to read discard bytes by read.
            if (ciInput2.available() >= DISCARD) {
                ciInput2.skip(DISCARD);
            } else {
                for (int k = 0; k < DISCARD; k++) {
                    ciInput2.read();
                }
            }
        }
        // Verify output is same as input
        if (!TestUtilities.equalsBlockPartial(plainText, outputText, BLOCK, SAVE)) {
            throw new RuntimeException("Test failed with compare fail");
        }
    }
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream)

Aggregations

CipherInputStream (javax.crypto.CipherInputStream)54 Cipher (javax.crypto.Cipher)31 ByteArrayInputStream (java.io.ByteArrayInputStream)18 IOException (java.io.IOException)17 InputStream (java.io.InputStream)14 NullCipher (javax.crypto.NullCipher)10 RuntimeException (java.lang.RuntimeException)9 SecretKeySpec (javax.crypto.spec.SecretKeySpec)7 Key (java.security.Key)6 CipherOutputStream (javax.crypto.CipherOutputStream)6 IvParameterSpec (javax.crypto.spec.IvParameterSpec)6 GeneralSecurityException (java.security.GeneralSecurityException)5 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)4 InvalidKeyException (java.security.InvalidKeyException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 BufferedInputStream (java.io.BufferedInputStream)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 DataInputStream (java.io.DataInputStream)3 Throwable (java.lang.Throwable)3 AlgorithmParameterSpec (java.security.spec.AlgorithmParameterSpec)3