Example usage for javax.crypto CipherInputStream CipherInputStream

List of usage examples for javax.crypto CipherInputStream CipherInputStream

Introduction

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

Prototype

public CipherInputStream(InputStream is, Cipher c) 

Source Link

Document

Constructs a CipherInputStream from an InputStream and a Cipher.

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   ww  w  .  j a  v  a 2 s  . co m*/

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

}

From source file:org.opendatakit.briefcase.util.ExportToCsv.java

private String getSubmissionValue(EncryptionInformation ei, TreeElement model, Element element) {
    // could not find element, return null
    if (element == null) {
        return null;
    }//from  ww w . j  av  a 2 s .  c  o m

    StringBuilder b = new StringBuilder();

    int maxChildren = element.getChildCount();
    for (int i = 0; i < maxChildren; i++) {
        if (element.getType(i) == Node.TEXT) {
            b.append(element.getText(i));
        }
    }
    String rawElement = b.toString();

    // Field-level encryption support -- experimental
    if (JavaRosaParserWrapper.isEncryptedField(model)) {

        InputStreamReader isr = null;
        try {
            Cipher c = ei.getCipher("field:" + model.getName(), model.getName());

            isr = new InputStreamReader(
                    new CipherInputStream(new ByteArrayInputStream(Base64.decodeBase64(rawElement)), c),
                    "UTF-8");

            b.setLength(0);
            int ch;
            while ((ch = isr.read()) != -1) {
                char theChar = (char) ch;
                b.append(theChar);
            }
            return b.toString();

        } catch (IOException e) {
            e.printStackTrace();
            log.severe(" element name: " + model.getName() + " exception: " + e.toString());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
            log.severe(" element name: " + model.getName() + " exception: " + e.toString());
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
            log.severe(" element name: " + model.getName() + " exception: " + e.toString());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            log.severe(" element name: " + model.getName() + " exception: " + e.toString());
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            log.severe(" element name: " + model.getName() + " exception: " + e.toString());
        } finally {
            if (isr != null) {
                try {
                    isr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return rawElement;
}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Decrypts a file./*from   ww  w .j a  v a 2s. c  o  m*/
 * 
 * @param path
 *          path of the encrypted file.
 * @param decryptedPath
 *          the path where file should be decrypted.
 * @param context
 *          context to fetch preferences.
 * @param decryptAsyncTask
 *          the AsyncTask that calls this method and needs to be updated. Ignored if null.
 */
public long decryptFile(final String path, final String decryptedPath, final Context context) {
    long empty = 123456789L;
    Date d1 = new Date();
    // Transaction.checkLongRunningProcessing("decryptFile");
    //System.err.println("Path = "+path);
    //System.err.println("decryptedPath = "+decryptedPath);
    try {
        final FileInputStream fis = new FileInputStream(path);
        final FileOutputStream fos = new FileOutputStream(decryptedPath);

        final InputStream inputStream;
        if (ENCRYPTION_ENABLED) {
            //System.err.println("DE - 1");
            //        final SecretKeySpec secret = getSecretKey(context);
            final SecretKeySpec secret = usedSecretKey;
            // Decrypt the message
            final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
            //System.err.println("DE - 2");
            // cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(getIV(context)));
            cipher.init(Cipher.DECRYPT_MODE, secret, ivspec);
            //System.err.println("DE - 3");
            inputStream = new CipherInputStream(fis, cipher);
            //System.err.println("DE - 4");
        } else {
            inputStream = fis;
        }

        int b;
        final byte[] d = new byte[BUFFER_SIZE];
        int totalBytesWritten = 0;
        while ((b = inputStream.read(d)) != -1) {
            fos.write(d, 0, b);
            /*if (decryptAsyncTask != null) {
              totalBytesWritten += BUFFER_SIZE;
              decryptAsyncTask.updateProgress(totalBytesWritten);
            }*/
        }
        fos.flush();
        fos.close();
        inputStream.close();

        Date d2 = new Date();
        long diff = d2.getTime() - d1.getTime();
        long diffSeconds = diff / 1000 % 60;
        System.err.println("File decrypted SUCCESSFULLY. Time = " + diffSeconds);
        return diffSeconds;
    } catch (final Exception e) {
        Log.e(TAG, "e" + e);
        return empty;
    }
}

From source file:com.csipsimple.backup.SipProfileJson.java

/**
 * Restore a sip configuration//ww  w. j  a  va  2s .  c o m
 * 
 * @param ctxt
 * @param fileToRestore
 * @return
 */
public static boolean restoreSipConfiguration(Context ctxt, File fileToRestore, String filePassword) {
    if (fileToRestore == null || !fileToRestore.isFile()) {
        return false;
    }

    StringBuffer contentBuf = new StringBuffer();

    try {
        BufferedReader buf;
        String line;
        InputStream is = new FileInputStream(fileToRestore);
        if (!TextUtils.isEmpty(filePassword)) {
            Cipher c;
            try {
                c = Cipher.getInstance("AES");
                SecretKeySpec k = new SecretKeySpec(filePassword.getBytes(), "AES");
                c.init(Cipher.ENCRYPT_MODE, k);
                is = new CipherInputStream(is, c);
            } catch (NoSuchAlgorithmException e) {
                Log.e(THIS_FILE, "NoSuchAlgorithmException :: ", e);
            } catch (NoSuchPaddingException e) {
                Log.e(THIS_FILE, "NoSuchPaddingException :: ", e);
            } catch (InvalidKeyException e) {
                Log.e(THIS_FILE, "InvalidKeyException :: ", e);
            }
        }

        InputStreamReader fr = new InputStreamReader(is);
        buf = new BufferedReader(fr);
        while ((line = buf.readLine()) != null) {
            contentBuf.append(line);
        }
        fr.close();
    } catch (FileNotFoundException e) {
        Log.e(THIS_FILE, "Error while restoring", e);
    } catch (IOException e) {
        Log.e(THIS_FILE, "Error while restoring", e);
    }

    JSONArray accounts = null;
    JSONObject settings = null;
    // Parse json if some string here
    if (contentBuf.length() > 0) {
        try {
            JSONObject mainJSONObject = new JSONObject(contentBuf.toString());
            // Retrieve accounts
            accounts = mainJSONObject.getJSONArray(KEY_ACCOUNTS);
            // Retrieve settings
            settings = mainJSONObject.getJSONObject(KEY_SETTINGS);

        } catch (JSONException e) {
            Log.e(THIS_FILE, "Error while parsing saved file", e);
        }
    } else {
        return false;
    }

    if (accounts != null && accounts.length() > 0) {
        restoreSipAccounts(ctxt, accounts);
    }

    if (settings != null) {
        restoreSipSettings(ctxt, settings);
        return true;
    }

    return false;
}

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   ww w .  ja va  2  s. com
 * 
 * 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:org.linagora.linshare.core.utils.SymmetricEnciphermentPBEwithAES.java

/**
 * give a CipherInputStream to decrypt data, if you want to decrypt data yourself
 * in must be given in class constructor
 * @return// www . java2 s . c o m
 */
public CipherInputStream getCipherInputStream() {
    if (in == null)
        throw new IllegalStateException("can not give intialised CipherInputStream, check inputstream");
    return new CipherInputStream(in, cipher);
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

public PutObjectResult put(File file, boolean encrypted) throws Exception {

    if (!encrypted || privateKey == null) {
        return put(file);
    }/*from  w  w  w .j a v a 2s .  c  om*/

    long decryptedLength = file.length();
    String path = getBucketPath(file);

    byte[] rawKey = AesUtil.generateKey();
    Cipher cipher = Cipher.getInstance(AesUtil.ALGORITHM);
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(rawKey, AesUtil.ALGORITHM));

    int encryptedLength = cipher.getOutputSize((int) file.length());

    InputStream inputStream = null;

    try {
        inputStream = new FileInputStream(file);
        inputStream = new CipherInputStream(inputStream, cipher);
        put(path, inputStream, encryptedLength);
    } finally {
        IOUtil.close(inputStream);
    }

    byte[] encryptedKey = RsaUtil.encrypt(privateKey, rawKey);

    DataProperties properties = new DataProperties();
    properties.put(PROP_ALGORITHM, AesUtil.ALGORITHM);
    properties.put(PROP_DECRYPTED_LENGTH, decryptedLength);
    properties.put(PROP_ENCRYPTED_LENGTH, encryptedLength);
    properties.put(PROP_KEY, encryptedKey);
    properties.put(PROP_ORIG_FILE_PATH, file.getAbsolutePath());
    properties.put(PROP_LAST_MODIFIED, file.lastModified());
    uploadProperties(path, properties);

    PutObjectResult response = new PutObjectResult();
    response.file = file;
    response.properties = properties;
    response.bucketPath = path;
    return response;
}

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

/**
 * Encrypt or decrypt data with AES256./*from   w  ww  . j a  v a 2s.  c o m*/
 *
 * @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: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./*from  w w  w.j a v a2 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) {
    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);
    }
}

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 ww w. j  a  v a2 s  . com
 *
 * 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");
}