Example usage for javax.crypto CipherInputStream close

List of usage examples for javax.crypto CipherInputStream close

Introduction

In this page you can find the example usage for javax.crypto CipherInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:org.linagora.linshare.core.utils.SymmetricEnciphermentPBEwithAES.java

public void decryptStream() throws IOException {

    if (cipherMode != Cipher.DECRYPT_MODE)
        throw new IllegalStateException("can not call decrypt, check cipher mode");

    CipherInputStream cis = new CipherInputStream(in, cipher);

    // Read from encrypted input and write to output stream
    byte[] buffer = new byte[2048];
    int bytesRead;

    while ((bytesRead = cis.read(buffer)) != -1) {
        out.write(buffer, 0, bytesRead);
        //System.out.println(bytesRead);
    }//from w w w.ja  va2 s .  c o m

    out.flush();
    out.close();
    cis.close();
    in.close();

}

From source file:sec_algo.commonenc.java

public void decryptFile() {
    File decrypted = new File("demo2de\\" + returnFileName() + "_decrypted." + returnFileExt());
    try {//from  w  ww.j  a  va 2s  .  c o  m
        FileOutputStream os = new FileOutputStream(decrypted);
        //            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        //            AlgorithmParameters.getInstance("AES");
        ////            if (iv!=null)
        //             byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        //            IvParameterSpec ivspec = new IvParameterSpec(iv);
        aesCipher.init(Cipher.DECRYPT_MODE, secretkey);
        //            else cipher.init(Cipher.DECRYPT_MODE, secretkey);
        CipherInputStream is = new CipherInputStream(new FileInputStream(file), aesCipher);

        long startTime = System.currentTimeMillis();
        copy(is, os);
        long endTime = System.currentTimeMillis();
        System.out.println("startTime - " + startTime);
        System.out.println("endTime - " + endTime);
        decryptTime = endTime - startTime;

        is.close();
        os.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:de.schildbach.wallet.util.FingerprintHelper.java

private String decipher(Cipher cipher) throws IOException {
    String retVal = null;/*from   w  w w . ja v a  2  s. com*/
    String savedEncryptedPassword = getSavedEncryptedPassword();
    if (savedEncryptedPassword != null) {
        byte[] decodedPassword = decodeBytes(savedEncryptedPassword);
        CipherInputStream cipherInputStream = new CipherInputStream(new ByteArrayInputStream(decodedPassword),
                cipher);

        ArrayList<Byte> values = new ArrayList<>();
        int nextByte;
        while ((nextByte = cipherInputStream.read()) != -1) {
            values.add((byte) nextByte);
        }
        cipherInputStream.close();

        byte[] bytes = new byte[values.size()];
        for (int i = 0; i < values.size(); i++) {
            bytes[i] = values.get(i).byteValue();
        }

        retVal = new String(bytes, Charset.defaultCharset());
    }
    return retVal;
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private SecretKey getSecretKey(KeyStore keyStore) throws NoSuchAlgorithmException, UnrecoverableEntryException,
        KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
        ClassNotFoundException {//ww  w  . j a v a  2  s  .c  o  m

    if (_key != null) {
        return _key;
    }

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore
            .getEntry(SECURELOCALSTORAGEALIAS, null);

    SecretKey key;

    FileInputStream fis = _cordova.getActivity().openFileInput(SECURELOCALSTORAGEKEY);
    try {

        Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());

        CipherInputStream cipherInputStream = new CipherInputStream(fis, output);
        try {

            ObjectInputStream ois = new ObjectInputStream(cipherInputStream);

            key = (SecretKey) ois.readObject();

        } finally {
            cipherInputStream.close();
        }
    } finally {
        fis.close();
    }

    // store key for the lifetime for the app
    _key = key;
    return key;
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

@SuppressWarnings("unchecked")
private HashMap<String, String> readAndDecryptStorage(KeyStore keyStore) throws SecureLocalStorageException {

    try {/*  www .j a v  a 2  s.c o m*/
        // obtain encrypted key
        SecretKey key = getSecretKey(keyStore);

        FileInputStream fis = _cordova.getActivity().openFileInput(SECURELOCALSTORAGEFILE);
        ArrayList<Byte> values = new ArrayList<Byte>();
        try {

            Cipher output = Cipher.getInstance("DES");
            output.init(Cipher.DECRYPT_MODE, key);

            CipherInputStream cipherInputStream = new CipherInputStream(fis, output);
            try {

                int nextByte;
                while ((nextByte = cipherInputStream.read()) != -1) {
                    values.add((byte) nextByte);
                }
            } finally {
                cipherInputStream.close();
            }
        } finally {
            fis.close();
        }

        byte[] bytes = new byte[values.size()];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = values.get(i);
        }

        HashMap<String, String> hashMap;
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        try {
            hashMap = (HashMap<String, String>) ois.readObject();
        } finally {
            ois.close();
        }
        return hashMap;
    } catch (Exception e) {
        Log.e("SecureStorage", "Write", e);
        throw new SecureLocalStorageException("Error decrypting storage", e);
    }
}

From source file:org.yes.cart.shoppingcart.support.impl.AbstractCryptedTuplizerImpl.java

/**
 * Convert string tuple back to the original object.
 *
 * @param tuple string tuple//from   w w w  .  j  a  v  a  2s. c om
 *
 * @return cart object of null
 *
 * @throws CartDetuplizationException when cannot deserialize the object
 */
protected ShoppingCart toObject(String tuple) throws CartDetuplizationException {

    if (tuple == null || tuple.length() == 0) {
        return null;
    }
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tuple.getBytes());
    final Base64InputStream base64DecoderStream = new Base64InputStream(byteArrayInputStream);
    final CipherInputStream cipherInputStream = new CipherInputStream(base64DecoderStream, desUnCipher);
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(cipherInputStream);
        return (ShoppingCart) objectInputStream.readObject();

    } catch (Exception exception) {
        try {
            desUnCipher.init(Cipher.DECRYPT_MODE, secretKey); //reinit
        } catch (InvalidKeyException e) {
            LOG.error("Cant reinit desUnCipher", exception);
        }
        final String errMsg = "Unable to convert bytes assembled from tuple into object";
        LOG.error(errMsg, exception);
        throw new CartDetuplizationException(errMsg, exception);
    } finally {
        try {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
            cipherInputStream.close();
            base64DecoderStream.close();
            byteArrayInputStream.close();
        } catch (IOException ioe) { // leave this one silent as we have the object.
            LOG.error("Unable to close object stream", ioe);
        }

    }
}

From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandler.java

/**
 * Encrypt or decrypt data with AES256./*from   ww w .  j a v a2 s  . com*/
 *
 * @param data The data to encrypt.
 * @param output The output to write the encrypted data to.
 * @param decrypt true to decrypt the data, false to encrypt it.
 *
 * @throws IOException If there is an error reading the data.
 */
private void encryptDataAES256(InputStream data, OutputStream output, boolean decrypt) throws IOException {
    byte[] iv = new byte[16];

    if (decrypt) {
        // read IV from stream
        data.read(iv);
    } else {
        // generate random IV and write to stream
        SecureRandom rnd = new SecureRandom();
        rnd.nextBytes(iv);
        output.write(iv);
    }

    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec keySpec = new SecretKeySpec(encryptionKey, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(iv);
        cipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, keySpec, ivSpec);
    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }

    CipherInputStream cis = new CipherInputStream(data, cipher);
    try {
        IOUtils.copy(cis, output);
    } catch (IOException exception) {
        // starting with java 8 the JVM wraps an IOException around a GeneralSecurityException
        // it should be safe to swallow a GeneralSecurityException
        if (!(exception.getCause() instanceof GeneralSecurityException)) {
            throw exception;
        }
        LOG.debug("A GeneralSecurityException occured when decrypting some stream data", exception);
    } finally {
        cis.close();
    }
}

From source file:Crypto.java

/**
 * Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
 * to disk as (output) File./*from w ww  . ja  v  a  2  s  .c o m*/
 * 
 * I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
 *  and still have a correctly decrypted file in the end. Seems to work so left it in.
 *  
 * @param input - File object representing encrypted data on disk 
 * @param output - File object of cleartext data to write out after decrypting
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws IOException
 */
public void ReadEncryptedFile(File input, File output)
        throws IllegalBlockSizeException, BadPaddingException, IOException {
    FileInputStream fin;
    FileOutputStream fout;
    CipherInputStream cin;
    long totalread = 0;
    int nread = 0;
    byte[] inbuf = new byte[MAX_FILE_BUF];

    fout = new FileOutputStream(output);
    fin = new FileInputStream(input);

    // creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
    cin = new CipherInputStream(fin, mDecipher);

    while ((nread = cin.read(inbuf)) > 0) {
        Db("read " + nread + " bytes");
        totalread += nread;

        // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
        byte[] trimbuf = new byte[nread];
        for (int i = 0; i < nread; i++)
            trimbuf[i] = inbuf[i];

        // write out the size-adjusted buffer
        fout.write(trimbuf);
    }

    fout.flush();
    cin.close();
    fin.close();
    fout.close();

    Db("wrote " + totalread + " encrypted bytes");
}

From source file:com.filelocker.encryption.AES_Encryption.java

/**
 * Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
 * to disk as (output) File./*from   w ww  . j  a va 2  s  . c om*/
 *
 * I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
 *  and still have a correctly decrypted file in the end. Seems to work so left it in.
 *
 * @param input - File object representing encrypted data on disk
 * @param output - File object of cleartext data to write out after decrypting
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws IOException
 */
public void ReadEncryptedFile(File input, File output)
        throws IllegalBlockSizeException, BadPaddingException, IOException {
    FileInputStream fin;
    FileOutputStream fout;
    CipherInputStream cin;
    long totalread = 0;
    int nread = 0;
    byte[] inbuf = new byte[MAX_FILE_BUF];

    fout = new FileOutputStream(output);
    fin = new FileInputStream(input);

    // creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
    cin = new CipherInputStream(fin, vDecipher);

    while ((nread = cin.read(inbuf)) > 0) {
        Db("read " + nread + " bytes");
        totalread += nread;

        // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
        byte[] trimbuf = new byte[nread];
        for (int i = 0; i < nread; i++)
            trimbuf[i] = inbuf[i];

        // write out the size-adjusted buffer
        fout.write(trimbuf);
    }

    fout.flush();
    cin.close();
    fin.close();
    fout.close();

    Db("wrote " + totalread + " dencrypted bytes");
    Db("Decryption Complete File Unlocked");
}

From source file:ropes.Crypto.java

/**
* Read from the encrypted file (input) and turn the cipher back into cleartext. Write the cleartext buffer back out
* to disk as (output) File.//  w ww.j a  va  2s .  c  om
* 
* I left CipherInputStream in here as a test to see if I could mix it with the update() and final() methods of encrypting
*  and still have a correctly decrypted file in the end. Seems to work so left it in.
*  
* @param input - File object representing encrypted data on disk 
* @param output - File object of cleartext data to write out after decrypting
* @throws IllegalBlockSizeException
* @throws BadPaddingException
* @throws IOException
*/
public void ReadEncryptedFile(File input, File output) {
    try {
        FileInputStream fin;
        FileOutputStream fout;
        CipherInputStream cin;
        long totalread = 0;
        int nread = 0;
        byte[] inbuf = new byte[MAX_FILE_BUF];

        fout = new FileOutputStream(output);
        fin = new FileInputStream(input);

        // creating a decoding stream from the FileInputStream above using the cipher created from setupDecrypt()
        cin = new CipherInputStream(fin, mDecipher);

        while ((nread = cin.read(inbuf)) > 0) {
            Db("read " + nread + " bytes");
            totalread += nread;

            // create a buffer to write with the exact number of bytes read. Otherwise a short read fills inbuf with 0x0
            byte[] trimbuf = new byte[nread];
            for (int i = 0; i < nread; i++)
                trimbuf[i] = inbuf[i];

            // write out the size-adjusted buffer
            fout.write(trimbuf);
        }

        fout.flush();
        cin.close();
        fin.close();
        fout.close();

        Db("wrote " + totalread + " encrypted bytes");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
}