Java Code Examples for javax.crypto.CipherInputStream#read()

The following examples show how to use javax.crypto.CipherInputStream#read() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_oneReadByteCorrupt() throws Exception {

        System.out.println("Running gcm_oneReadByteCorrupt test");

        // Encrypt 100 bytes with AES/GCM/PKCS5Padding
        byte[] ct = encryptedText("GCM", 100);
        // Corrupt the encrypted message
        ct = corruptGCM(ct);
        // Create stream for decryption
        CipherInputStream in = getStream("GCM", ct);

        try {
            in.read();
            System.out.println("  Fail. No exception thrown.");
        } catch (IOException e) {
            Throwable ec = e.getCause();
            if (ec instanceof AEADBadTagException) {
                System.out.println("  Pass.");
            } else {
                System.out.println("  Fail: " + ec.getMessage());
                throw new RuntimeException(ec);
            }
        }
    }
 
Example 2
Source File: CICO_PBE_SKIP_Test.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Implements int buffering type test case of the CICO SKIP test.
 *
 * @param blockNum block number to read.
 */
private void proceedSkipTestUsingIntBufferingType(CipherInputStream ciIn2,
        int blockNum) throws IOException {
    int index = blockNum * SAVE;
    int totalRead = 0;
    for (int j = 0; j < SAVE; j++, index++) {
        int buffer0 = ciIn2.read();
        if (buffer0 != -1) {
            outputText[index] = (byte) buffer0;
            totalRead++;
        } else {
            break;
        }
    }
    if (totalRead != SAVE) {
        throw new RuntimeException("Read bytes number " + totalRead
                + " does not equal to given number " + SAVE);
    }
}
 
Example 3
Source File: CICO_PBE_SKIP_Test.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Implements int buffering type test case of the CICO SKIP test.
 *
 * @param blockNum block number to read.
 */
private void proceedSkipTestUsingIntBufferingType(CipherInputStream ciIn2,
        int blockNum) throws IOException {
    int index = blockNum * SAVE;
    int totalRead = 0;
    for (int j = 0; j < SAVE; j++, index++) {
        int buffer0 = ciIn2.read();
        if (buffer0 != -1) {
            outputText[index] = (byte) buffer0;
            totalRead++;
        } else {
            break;
        }
    }
    if (totalRead != SAVE) {
        throw new RuntimeException("Read bytes number " + totalRead
                + " does not equal to given number " + SAVE);
    }
}
 
Example 4
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortRead600() throws Exception {
    System.out.println("Running cbc_shortRead600");

    // Encrypt 600 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 600);
    // Create stream with encrypted data
    CipherInputStream in = getStream("CBC", ct);

    try {
        in.read();
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 5
Source File: CipherInputStreamExceptions.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortRead600() throws Exception {
    System.out.println("Running cbc_shortRead600");

    // Encrypt 600 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 600);
    // Create stream with encrypted data
    CipherInputStream in = getStream("CBC", ct);

    try {
        in.read();
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 6
Source File: CipherInputStreamExceptions.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_oneReadByte() throws Exception {

        System.out.println("Running gcm_oneReadByte test");

        // Encrypt 100 bytes with AES/GCM/PKCS5Padding
        byte[] ct = encryptedText("GCM", 100);
        // Create stream for decryption
        CipherInputStream in = getStream("GCM", ct);

        try {
            in.read();
            System.out.println("  Pass.");
        } catch (Exception e) {
            System.out.println("  Fail: " + e.getMessage());
            throw new RuntimeException(e.getCause());
        }
    }
 
Example 7
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 6 votes vote down vote up
private  byte[] rsaDecrypt(
        byte[] encrypted,
        String keystoreAlias
) throws Exception {
    final KeyStore keyStore = loadKeyStore();
    final KeyStore.PrivateKeyEntry privateKeyEntry =
            (KeyStore.PrivateKeyEntry)keyStore.getEntry(keystoreAlias, null);
    final Cipher output = Cipher.getInstance(RSA_MODE, PROVIDER);
    output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
    final CipherInputStream cipherInputStream = new CipherInputStream(
            new ByteArrayInputStream(encrypted), output);
    final ArrayList<Byte> values = new ArrayList<>();
    int nextByte;
    while ((nextByte = cipherInputStream.read()) != -1) {
        values.add((byte)nextByte);
    }
    final byte[] bytes = new byte[values.size()];
    for(int i = 0; i < bytes.length; i++) {
        bytes[i] = values.get(i).byteValue();
    }
    return bytes;
}
 
Example 8
Source File: CICOSkipTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
int readByte(CipherInputStream ciIn2, byte[] outputText, int save,
        int index) throws IOException {
    int len1 = ciIn2.read(outputText, index, save);
    out.println("Init: index=" + index + ",len=" + len1);
    // read more until save bytes
    index += len1;
    int len2 = 0;
    while (len1 != save && len2 != -1) {
        len2 = ciIn2.read(outputText, index, save - len1);
        out.println("Cont: index=" + index + ",len=" + len2);
        len1 += len2;
        index += len2;
    }
    return index;
}
 
Example 9
Source File: CipherInputStreamExceptions.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortRead600() throws Exception {
    System.out.println("Running cbc_shortRead600");

    // Encrypt 600 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 600);
    // Create stream with encrypted data
    CipherInputStream in = getStream("CBC", ct);

    try {
        in.read();
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 10
Source File: CipherInputStreamExceptions.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_oneReadByte() throws Exception {

        System.out.println("Running gcm_oneReadByte test");

        // Encrypt 100 bytes with AES/GCM/PKCS5Padding
        byte[] ct = encryptedText("GCM", 100);
        // Create stream for decryption
        CipherInputStream in = getStream("GCM", ct);

        try {
            in.read();
            System.out.println("  Pass.");
        } catch (Exception e) {
            System.out.println("  Fail: " + e.getMessage());
            throw new RuntimeException(e.getCause());
        }
    }
 
Example 11
Source File: CipherStorageKeystoreAESCBC.java    From react-native-secure-storage with MIT License 6 votes vote down vote up
private String decryptBytes(Key key, byte[] bytes) throws CryptoFailedException {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_TRANSFORMATION);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        // read the initialization vector from the beginning of the stream
        IvParameterSpec ivParams = readIvFromStream(inputStream);
        cipher.init(Cipher.DECRYPT_MODE, key, ivParams);
        // decrypt the bytes using a CipherInputStream
        CipherInputStream cipherInputStream = new CipherInputStream(
                inputStream, cipher);
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while (true) {
            int n = cipherInputStream.read(buffer, 0, buffer.length);
            if (n <= 0) {
                break;
            }
            output.write(buffer, 0, n);
        }
        return new String(output.toByteArray(), charsetName);
    } catch (Exception e) {
        throw new CryptoFailedException("Could not decrypt bytes", e);
    }
}
 
Example 12
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortRead400() throws Exception {
    System.out.println("Running cbc_shortRead400");

    // Encrypt 400 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 400);
    // Create stream with encrypted data
    CipherInputStream in = getStream("CBC", ct);

    try {
        in.read();
        in.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example 13
Source File: KeyGenHelper.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 6 votes vote down vote up
private static byte[] rsaDecrypt(byte[] encrypted) throws Exception {
    KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null);
    Cipher output = Cipher.getInstance(RSA_MODE);
    output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());
    CipherInputStream cipherInputStream = new CipherInputStream(
            new ByteArrayInputStream(encrypted), output);
    ArrayList<Byte> values = new ArrayList<>();
    int nextByte;
    while ((nextByte = cipherInputStream.read()) != -1) {
        values.add((byte) nextByte);
    }

    byte[] bytes = new byte[values.size()];
    for (int i = 0; i < bytes.length; i++) {
        bytes[i] = values.get(i).byteValue();
    }
    return bytes;
}
 
Example 14
Source File: ReadWriteSkip.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private void doIntTest(int blockNum, CipherInputStream cis)
        throws IOException {
    int i = blockNum * SAVE;
    for (int j = 0; j < SAVE && i < outputText.length; j++, i++) {
        int b = cis.read();
        if (b != -1) {
            outputText[i] = (byte) b;
        }
    }
}
 
Example 15
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Decrypts AES decoded key from preference using RSA private key
 * @param encodedBytes
 * @return
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws UnrecoverableEntryException
 * @throws NoSuchProviderException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 */
private byte[] decryptAESKey(byte[] encodedBytes) throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, UnrecoverableEntryException, NoSuchProviderException, NoSuchPaddingException,
        InvalidKeyException, BadPaddingException, IllegalBlockSizeException {

    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);
    KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry)
            keyStore.getEntry(KEY_ALIAS_AMAZE, null);
    Cipher cipher = Cipher.getInstance(ALGO_RSA, "AndroidOpenSSL");
    cipher.init(Cipher.DECRYPT_MODE, keyEntry.getPrivateKey());

    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(encodedBytes);
    CipherInputStream inputStream = new CipherInputStream(byteArrayInputStream, cipher);
    ArrayList<Byte> bytes = new ArrayList<>();
    int nextByte;
    while ((nextByte = inputStream.read()) != -1) {
        bytes.add((byte) nextByte);
    }

    byte[] decryptedBytes = new byte[bytes.size()];
    for (int i=0; i<bytes.size(); i++) {

        decryptedBytes[i] = bytes.get(i).byteValue();
    }
    return decryptedBytes;
}
 
Example 16
Source File: CipherInputStreamExceptions.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
static void cbc_readAllIllegalBlockSize() throws Exception {
    byte[] read = new byte[200];

    System.out.println("Running cbc_readAllIllegalBlockSize test");

    // Encrypt 96 byte with AES/CBC/PKCS5Padding
    byte[] ct = encryptedText("CBC", 96);
    // Create a stream with only 95 bytes of encrypted data
    CipherInputStream in = getStream("CBC", ct, 95);

    try {
        int s, size = 0;
        while ((s = in.read(read)) != -1) {
            size += s;
        }
        throw new RuntimeException("Fail: No IllegalBlockSizeException. " +
                "CipherInputStream.read() returned " + size);

    } catch (IOException e) {
        Throwable ec = e.getCause();
        if (ec instanceof IllegalBlockSizeException) {
            System.out.println("  Pass.");
        } else {
            System.out.println("  Fail: " + ec.getMessage());
            throw new RuntimeException(ec);
        }
    }
}
 
Example 17
Source File: ReadWriteSkip.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void doIntTest(int blockNum, CipherInputStream cis)
        throws IOException {
    int i = blockNum * SAVE;
    for (int j = 0; j < SAVE && i < outputText.length; j++, i++) {
        int b = cis.read();
        if (b != -1) {
            outputText[i] = (byte) b;
        }
    }
}
 
Example 18
Source File: CipherInputStreamExceptions.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
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.");
}
 
Example 19
Source File: CipherHelper.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper routine to decrypt from an InputStream and write the
 * application data straight to an output array with minimal
 * buffer copies. The confounder and the padding are stored
 * separately and not copied into this output array.
 * @param key the DES key to use
 * @param is the InputStream from which the cipher text should be
 * read
 * @param len the length of the ciphertext data
 * @param dataOutBuf the output buffer where the application data
 * should be writte
 * @param dataOffset the offser where the application data should
 * be written.
 * @throws GSSException is an error occurs while decrypting the
 * data
 */
private void desCbcDecrypt(WrapToken token, byte[] key,
    InputStream is, int len, byte[] dataOutBuf, int dataOffset)
    throws GSSException, IOException {

    int temp = 0;

    Cipher des = getInitializedDes(false, key, ZERO_IV);

    WrapTokenInputStream truncatedInputStream =
        new WrapTokenInputStream(is, len);
    CipherInputStream cis = new CipherInputStream(truncatedInputStream,
                                                  des);
    /*
     * Remove the counfounder first.
     * CONFOUNDER_SIZE is one DES block ie 8 bytes.
     */
    temp = cis.read(token.confounder);

    len -= temp;
    // temp should be CONFOUNDER_SIZE
    // debug("Got " + temp + " bytes; CONFOUNDER_SIZE is "
    //     + CONFOUNDER_SIZE + "\n");
    // debug("Confounder is " + getHexBytes(confounder) + "\n");


    /*
     * len is a multiple of 8 due to padding.
     * Decrypt all blocks directly into the output buffer except for
     * the very last block. Remove the trailing padding bytes from the
     * very last block and copy that into the output buffer.
     */

    int blockSize = des.getBlockSize();
    int numBlocks = len / blockSize - 1;

    // Iterate over all but the last block
    for (int i = 0; i < numBlocks; i++) {
        // debug("dataOffset is " + dataOffset + "\n");
        temp = cis.read(dataOutBuf, dataOffset, blockSize);

        // temp should be blockSize
        // debug("Got " + temp + " bytes and blockSize is "
        //    + blockSize + "\n");
        // debug("Bytes are: "
        //    + getHexBytes(dataOutBuf, dataOffset, temp) + "\n");
        dataOffset += blockSize;
    }

    // Now process the last block
    byte[] finalBlock = new byte[blockSize];
    // debug("Will call read on finalBlock" + "\n");
    temp = cis.read(finalBlock);
    // temp should be blockSize
    /*
      debug("Got " + temp + " bytes and blockSize is "
      + blockSize + "\n");
      debug("Bytes are: "
      + getHexBytes(finalBlock, 0, temp) + "\n");
      debug("Will call doFinal" + "\n");
    */
    try {
        des.doFinal();
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }

    /*
     * There is always at least one padding byte. The padding bytes
     * are all the value of the number of padding bytes.
     */

    int padSize = finalBlock[blockSize - 1];
    if (padSize < 1  || padSize > 8)
        throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                               "Invalid padding on Wrap Token");
    token.padding = WrapToken.pads[padSize];
    blockSize -= padSize;

    // Copy this last block into the output buffer
    System.arraycopy(finalBlock, 0, dataOutBuf, dataOffset,
                     blockSize);
}
 
Example 20
Source File: CipherHelper.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Helper routine to decrypt from an InputStream and write the
 * application data straight to an output array with minimal
 * buffer copies. The confounder and the padding are stored
 * separately and not copied into this output array.
 * @param key the DES key to use
 * @param is the InputStream from which the cipher text should be
 * read
 * @param len the length of the ciphertext data
 * @param dataOutBuf the output buffer where the application data
 * should be writte
 * @param dataOffset the offser where the application data should
 * be written.
 * @throws GSSException is an error occurs while decrypting the
 * data
 */
private void desCbcDecrypt(WrapToken token, byte[] key,
    InputStream is, int len, byte[] dataOutBuf, int dataOffset)
    throws GSSException, IOException {

    int temp = 0;

    Cipher des = getInitializedDes(false, key, ZERO_IV);

    WrapTokenInputStream truncatedInputStream =
        new WrapTokenInputStream(is, len);
    CipherInputStream cis = new CipherInputStream(truncatedInputStream,
                                                  des);
    /*
     * Remove the counfounder first.
     * CONFOUNDER_SIZE is one DES block ie 8 bytes.
     */
    temp = cis.read(token.confounder);

    len -= temp;
    // temp should be CONFOUNDER_SIZE
    // debug("Got " + temp + " bytes; CONFOUNDER_SIZE is "
    //     + CONFOUNDER_SIZE + "\n");
    // debug("Confounder is " + getHexBytes(confounder) + "\n");


    /*
     * len is a multiple of 8 due to padding.
     * Decrypt all blocks directly into the output buffer except for
     * the very last block. Remove the trailing padding bytes from the
     * very last block and copy that into the output buffer.
     */

    int blockSize = des.getBlockSize();
    int numBlocks = len / blockSize - 1;

    // Iterate over all but the last block
    for (int i = 0; i < numBlocks; i++) {
        // debug("dataOffset is " + dataOffset + "\n");
        temp = cis.read(dataOutBuf, dataOffset, blockSize);

        // temp should be blockSize
        // debug("Got " + temp + " bytes and blockSize is "
        //    + blockSize + "\n");
        // debug("Bytes are: "
        //    + getHexBytes(dataOutBuf, dataOffset, temp) + "\n");
        dataOffset += blockSize;
    }

    // Now process the last block
    byte[] finalBlock = new byte[blockSize];
    // debug("Will call read on finalBlock" + "\n");
    temp = cis.read(finalBlock);
    // temp should be blockSize
    /*
      debug("Got " + temp + " bytes and blockSize is "
      + blockSize + "\n");
      debug("Bytes are: "
      + getHexBytes(finalBlock, 0, temp) + "\n");
      debug("Will call doFinal" + "\n");
    */
    try {
        des.doFinal();
    } catch (GeneralSecurityException e) {
        GSSException ge = new GSSException(GSSException.FAILURE, -1,
            "Could not use DES cipher - " + e.getMessage());
        ge.initCause(e);
        throw ge;
    }

    /*
     * There is always at least one padding byte. The padding bytes
     * are all the value of the number of padding bytes.
     */

    int padSize = finalBlock[blockSize - 1];
    if (padSize < 1  || padSize > 8)
        throw new GSSException(GSSException.DEFECTIVE_TOKEN, -1,
                               "Invalid padding on Wrap Token");
    token.padding = WrapToken.pads[padSize];
    blockSize -= padSize;

    // Copy this last block into the output buffer
    System.arraycopy(finalBlock, 0, dataOutBuf, dataOffset,
                     blockSize);
}