javax.crypto.CipherInputStream Java Examples

The following examples show how to use javax.crypto.CipherInputStream. 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: FileDESUtils.java    From YCAudioPlayer with Apache License 2.0 6 votes vote down vote up
/**
 * 解密文件
 *
 * @param in
 */
public void doDecryptFile(InputStream in, String path) {
    if (in == null) {
        System.out.println("inputstream is null");
        return;
    }
    try {
        CipherInputStream cin = new CipherInputStream(in, mDecryptCipher);
        OutputStream outputStream = new FileOutputStream(path);
        byte[] bytes = new byte[1024];
        int length = -1;
        while ((length = cin.read(bytes)) > 0) {
            outputStream.write(bytes, 0, length);
            outputStream.flush();
        }
        cin.close();
        in.close();
        System.out.println("解密成功");
    } catch (Exception e) {
        System.out.println("解密失败");
        e.printStackTrace();
    }
}
 
Example #2
Source File: CipherInputStreamExceptions.java    From jdk8u60 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 #3
Source File: CipherInputStreamExceptions.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortStream() throws Exception {
    Cipher c;
    AlgorithmParameters params;
    byte[] read = new byte[200];

    System.out.println("Running cbc_shortStream");

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

    try {
        int size = in.read(read);
        in.close();
        if (size != 80) {
            throw new RuntimeException("Fail: CipherInputStream.read() " +
                    "returned " + size + ". Should have been 80");
        }
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #4
Source File: CipherInputStreamExceptions.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_suppressUnreadCorrupt() throws Exception {
    Cipher c;
    byte[] read = new byte[200];

    System.out.println("Running supressUnreadCorrupt 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.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail: " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #5
Source File: KeyStoreUtils.java    From guarda-android-wallets with GNU General Public License v3.0 6 votes vote down vote up
private  byte[]  rsaDecrypt(byte[] encrypted) throws Exception {
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ALIAS, null);
    Cipher output = Cipher.getInstance(RSA_MODE, "AndroidOpenSSL");
    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 #6
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 #7
Source File: CipherInputStreamExceptions.java    From jdk8u60 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 #8
Source File: CICOSkipTest.java    From dragonwell8_jdk 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: CICO_PBE_SKIP_Test.java    From openjdk-jdk8u 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 #10
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 #11
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 #12
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
private byte[] rsaDecryptKey(byte[] encrypted) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, UnrecoverableEntryException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException {

        KeyStore keyStore = KeyStore.getInstance(ANDROID_KEY_STORE_NAME);
        keyStore.load(null);

        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(KEY_ENCRYPTION, null);
        Cipher output = Cipher.getInstance(RSA_MODE, CIPHER_PROVIDER_NAME_ENCRYPTION_DECRYPTION_RSA);
        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[] decryptedKeyAsBytes = new byte[values.size()];
        for (int i = 0; i < decryptedKeyAsBytes.length; i++) {
            decryptedKeyAsBytes[i] = values.get(i);
        }
        return decryptedKeyAsBytes;
    }
 
Example #13
Source File: CICO_PBE_SKIP_Test.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Implements byte array buffering type test case of the CICO SKIP test.
 *
 * @param blockNum block number to read.
 */
private void proceedSkipTestUsingByteArrayBufferingType(
        CipherInputStream ciIn2, int blockNum) throws IOException {
    int index = blockNum * SAVE;
    int len1 = ciIn2.read(outputText, index, SAVE);
    // read more until SAVE bytes
    index += len1;
    int len2 = 0;
    int totalRead = len1;
    while (len1 != SAVE && len2 != -1) {
        len2 = ciIn2.read(outputText, index, SAVE - len1);
        len1 += len2;
        index += len2;
        totalRead += len2;
    }
    if (totalRead != SAVE) {
        throw new RuntimeException("Read bytes number " + totalRead
                + " does not equal to given number " + SAVE);
    }
}
 
Example #14
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 #15
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 #16
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 #17
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void cbc_shortStream() throws Exception {
    Cipher c;
    AlgorithmParameters params;
    byte[] read = new byte[200];

    System.out.println("Running cbc_shortStream");

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

    try {
        int size = in.read(read);
        in.close();
        if (size != 80) {
            throw new RuntimeException("Fail: CipherInputStream.read() " +
                    "returned " + size + ". Should have been 80");
        }
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail:  " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #18
Source File: CipherInputStreamExceptions.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_suppressUnreadCorrupt() throws Exception {
    Cipher c;
    byte[] read = new byte[200];

    System.out.println("Running supressUnreadCorrupt 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.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail: " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #19
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 #20
Source File: CICO_PBE_SKIP_Test.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Implements byte array buffering type test case of the CICO SKIP test.
 *
 * @param blockNum block number to read.
 */
private void proceedSkipTestUsingByteArrayBufferingType(
        CipherInputStream ciIn2, int blockNum) throws IOException {
    int index = blockNum * SAVE;
    int len1 = ciIn2.read(outputText, index, SAVE);
    // read more until SAVE bytes
    index += len1;
    int len2 = 0;
    int totalRead = len1;
    while (len1 != SAVE && len2 != -1) {
        len2 = ciIn2.read(outputText, index, SAVE - len1);
        len1 += len2;
        index += len2;
        totalRead += len2;
    }
    if (totalRead != SAVE) {
        throw new RuntimeException("Read bytes number " + totalRead
                + " does not equal to given number " + SAVE);
    }
}
 
Example #21
Source File: CipherInputStreamExceptions.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
static CipherInputStream getStream(String mode, byte[] ct, int length)
        throws Exception {
    Cipher c;

    if (mode.compareTo("GCM") == 0) {
        c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE");
        c.init(Cipher.DECRYPT_MODE, key, gcmspec);
    } else if (mode.compareTo("CBC") == 0) {
        c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        c.init(Cipher.DECRYPT_MODE, key, iv);
    } else {
        return null;
    }

    return new CipherInputStream(new ByteArrayInputStream(ct, 0, length), c);

}
 
Example #22
Source File: CipherInputStreamExceptions.java    From dragonwell8_jdk 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 #23
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static CipherInputStream getStream(String mode, byte[] ct, int length)
        throws Exception {
    Cipher c;

    if (mode.compareTo("GCM") == 0) {
        c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE");
        c.init(Cipher.DECRYPT_MODE, key, gcmspec);
    } else if (mode.compareTo("CBC") == 0) {
        c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        c.init(Cipher.DECRYPT_MODE, key, iv);
    } else {
        return null;
    }

    return new CipherInputStream(new ByteArrayInputStream(ct, 0, length), c);

}
 
Example #24
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 #25
Source File: CipherInputStreamExceptions.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static CipherInputStream getStream(String mode, byte[] ct, int length)
        throws Exception {
    Cipher c;

    if (mode.compareTo("GCM") == 0) {
        c = Cipher.getInstance("AES/GCM/PKCS5Padding", "SunJCE");
        c.init(Cipher.DECRYPT_MODE, key, gcmspec);
    } else if (mode.compareTo("CBC") == 0) {
        c = Cipher.getInstance("AES/CBC/PKCS5Padding", "SunJCE");
        c.init(Cipher.DECRYPT_MODE, key, iv);
    } else {
        return null;
    }

    return new CipherInputStream(new ByteArrayInputStream(ct, 0, length), c);

}
 
Example #26
Source File: CipherInputStreamExceptions.java    From TencentKona-8 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 #27
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u 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 #28
Source File: CipherInputStreamExceptions.java    From TencentKona-8 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 #29
Source File: CipherInputStreamExceptions.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static void gcm_suppressUnreadCorrupt() throws Exception {
    Cipher c;
    byte[] read = new byte[200];

    System.out.println("Running supressUnreadCorrupt 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.close();
        System.out.println("  Pass.");
    } catch (IOException e) {
        System.out.println("  Fail: " + e.getMessage());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #30
Source File: CipherStorageAndroidKeystore.java    From keystore-ultimate with Apache License 2.0 6 votes vote down vote up
private static 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(), DEFAULT_CHARSET);
    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException |
            InvalidKeyException | InvalidAlgorithmParameterException e) {
        throw new CryptoFailedException("Could not decrypt bytes", e);
    }
}