Example usage for javax.crypto CipherInputStream read

List of usage examples for javax.crypto CipherInputStream read

Introduction

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

Prototype

public int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

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./*ww  w .  j a  va2  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:org.apache.camel.converter.crypto.CryptoDataFormat.java

public Object unmarshal(Exchange exchange, InputStream encryptedStream) throws Exception {
    Object unmarshalled = null;//from www  .ja  va  2 s .  c o m
    if (encryptedStream != null) {
        byte[] iv = getInlinedInitializationVector(exchange, encryptedStream);
        Key key = getKey(exchange);
        CipherInputStream cipherStream = new CipherInputStream(encryptedStream,
                initializeCipher(DECRYPT_MODE, key, iv));

        ByteArrayOutputStream plaintextStream = new ByteArrayOutputStream(bufferSize);
        HMACAccumulator hmac = getMessageAuthenticationCode(key);
        byte[] buffer = new byte[bufferSize];
        hmac.attachStream(plaintextStream);
        int read;
        while ((read = cipherStream.read(buffer)) >= 0) {
            hmac.decryptUpdate(buffer, read);
        }
        hmac.validate();
        unmarshalled = plaintextStream.toByteArray();
    }
    return unmarshalled;
}

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 ww  w .ja va2s .  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) {
    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:uk.ac.ox.webauth.Token.java

/**
 * Initialise a token with a base64 encoded Webauth token.
 * @param   tokenData   The data to be decrypted.
 * @param   sessionKey  The session key to use for the AES and Hmac.
 * @throws  GeneralSecurityException    if there was a problem with the security code used.
 *//*from www .ja va  2 s .  co  m*/
public Token(byte[] tokenData, Key sessionKey) throws GeneralSecurityException {
    // a token is:
    // {key-hint}{nonce   }{hmac    }{token-attributes     }{padding         }
    // {4 bytes }{16 bytes}{20 bytes}{make the data into multiple of 16 bytes}
    // everything after the key hint is aes encrypted

    try {
        // set up some streams
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(tokenData);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);

        // read the key hint
        int keyHint = dataInputStream.readInt();

        // prepare to AES decrypt the rest
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(DECRYPT_MODE, sessionKey, IV);
        CipherInputStream decrypt = new CipherInputStream(byteArrayInputStream, cipher);

        // throw away the nonce
        if (decrypt.read(new byte[16]) != 16) {
            throw new GeneralSecurityException("Failed to read nonce from token.");
        }

        // read the HMACSHA1 checksum
        byte[] checksum = new byte[20];
        if (decrypt.read(checksum) != 20) {
            throw new GeneralSecurityException("Failed to read HMAC SHA1 checksum from token.");
        }

        // read in the rest of the data
        ByteArrayOutputStream tokenByteArrayOutputStream = new ByteArrayOutputStream();
        for (int b = decrypt.read(); b != -1; b = decrypt.read()) {
            tokenByteArrayOutputStream.write(b);
        }
        byte[] data = tokenByteArrayOutputStream.toByteArray();
        decrypt.close();

        // check the hmacsha1
        Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
        hmacSHA1.init(sessionKey);
        if (!Arrays.equals(checksum, hmacSHA1.doFinal(data))) {
            throw new GeneralSecurityException("Invalid token, checksum mismatch.");
        }

        // create all the key-value pairs
        for (int i = 0, start = 0; (i = indexOf(SEMI_COLON, data, i)) != -1;) {
            i++;
            if (i < data.length && data[i] == SEMI_COLON) {
                i++;
                continue;
            }
            byte[] keyValuePairArray = new byte[i - start];
            System.arraycopy(data, start, keyValuePairArray, 0, keyValuePairArray.length);
            KeyValuePair kvp = new KeyValuePair(keyValuePairArray);
            kv.put(new String(kvp.key(), "US-ASCII"), kvp);
            start = i;
        }
    } catch (IOException ioe) {
        /* should never happen as it's a ByteArrayInputStream */
        ioe.printStackTrace();
    }
    valid = true;

    // create the Stringifier to use
    stringifier = new WebauthTokenStringifier();
}

From source file:com.pari.nm.utils.backup.BackupRestore.java

public boolean decrypt(File backupZipFile, File encrZipFile) throws Exception {
    try {/*from  w  w w. ja v a2 s  . c om*/
        FileOutputStream fout = new FileOutputStream(backupZipFile);
        FileInputStream fin = new FileInputStream(encrZipFile);
        Cipher cipher = Cipher.getInstance("DESEDE");

        cipher.init(Cipher.DECRYPT_MODE, getDefaultKey());

        CipherInputStream cin = new CipherInputStream(fin, cipher);
        byte[] buffer = new byte[8192];

        try {
            int read = cin.read(buffer);
            while (read != -1) {
                fout.write(buffer, 0, read);
                read = cin.read(buffer);
            }
        } finally {
            try {
                fout.close();
            } catch (Exception ignore) {
            }

            try {
                cin.close();
            } catch (Exception ignore) {
            }

            try {
                fin.close();
            } catch (Exception ignore) {
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return false;
}