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:Main.java

public static void decrypt(String fileIn, String fileOut, byte key[])
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    FileInputStream fis = new FileInputStream(fileIn);
    FileOutputStream fos = new FileOutputStream(fileOut);

    // Length is 32 bytes
    //byte key[] = "1010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100000011010110101010101010100101111001001001001001001011110111100001111000011".getBytes("UTF-8");
    MessageDigest sha = MessageDigest.getInstance("SHA-256");
    key = sha.digest(key);//from w w  w  . j a  va2s. c om
    SecretKeySpec sks = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, sks);

    CipherInputStream cis = new CipherInputStream(fis, cipher);
    int b;
    byte[] d = new byte[8];
    while ((b = cis.read(d)) != -1) {
        fos.write(d, 0, b);
    }

    fos.flush();
    fos.close();
    cis.close();
}

From source file:Main.java

private static boolean handleFile(int mode, byte[] key, byte[] iv, String sourceFilePath, String destFilePath) {

    File sourceFile = new File(sourceFilePath);
    File destFile = new File(destFilePath);

    try {//w  ww  .  jav a  2  s .  co  m
        if (sourceFile.exists() && sourceFile.isFile()) {
            if (!destFile.getParentFile().exists())
                destFile.getParentFile().mkdirs();
            destFile.createNewFile();

            InputStream in = new FileInputStream(sourceFile);
            OutputStream out = new FileOutputStream(destFile);
            Cipher cipher = initCipher(mode, key, iv, AES_CFB_NOPADDING);
            CipherInputStream cin = new CipherInputStream(in, cipher);

            byte[] b = new byte[1024];
            int read = 0;
            while ((read = cin.read(b)) != -1) {
                out.write(b, 0, read);
                out.flush();
            }

            cin.close();
            in.close();
            out.close();

            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
}

From source file:MainClass.java

static void applyCipher(String inFile, String outFile, Cipher cipher) throws Exception {
    CipherInputStream in = new CipherInputStream(new FileInputStream(inFile), cipher);
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
    int BUFFER_SIZE = 8;
    byte[] buffer = new byte[BUFFER_SIZE];
    int numRead = 0;
    do {//from   ww w.j  a v  a2  s.c o  m
        numRead = in.read(buffer);
        if (numRead > 0)
            out.write(buffer, 0, numRead);
    } while (numRead == 8);
}

From source file:org.panbox.core.crypto.CryptCore.java

public static SecretKey decryptShareKey(ShareKeyDBEntry entry, PublicKey pubKey, PrivateKey privKey) {
    SecretKey result = null;//from   w w  w . j  ava  2 s . c om
    if (entry != null) {
        byte[] encSK = entry.getEncryptedKey(pubKey);
        byte[] sk = new byte[KeyConstants.SYMMETRIC_BLOCK_SIZE];
        try {
            ASYMM_CIPHER.init(Cipher.DECRYPT_MODE, privKey);
            ByteArrayInputStream bis = new ByteArrayInputStream(encSK);
            CipherInputStream cis = new CipherInputStream(bis, ASYMM_CIPHER);
            cis.read(sk);
            cis.close();
            bis.close();
            result = new SecretKeySpec(sk, entry.getAlgorithm());
        } catch (InvalidKeyException e) {
            logger.warn("Exception caught in CryptCore.decryptShareKey", e);
        } catch (IOException e) {
            logger.warn("Exception caught in CryptCore.decryptShareKey", e);
        }
    }
    return result;
}

From source file:com.dc.util.file.FileSupport.java

private static void copyEncryptedStream(InputStream input, OutputStream output, String key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    Cipher dcipher = Cipher.getInstance("AES");
    CipherInputStream cis = null;
    try {/*from  w  w w .j  a  va2 s.c  o m*/
        dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        cis = new CipherInputStream(input, dcipher);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = cis.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        output.flush();
    } finally {
        if (cis != null) {
            cis.close();
        }
    }
}

From source file:enc_mods.aes.java

/**
* Decrypts an AES key from a file using an RSA private key
*///  w ww .ja  v  a2  s  .  c o  m
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        cipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), cipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:sec_algo.commonenc.java

/**
* Decrypts an AES key from a file using an RSA private key
*///w w  w  . ja va2s.  com
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        pkCipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), pkCipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.cubusmail.server.mail.security.MailPasswordEncryptor.java

public String decryptPassword(byte[] encryptedPassword) {

    Cipher cipher;//from w  w w .j a  v  a 2s.c o  m
    try {
        log.debug("decrypt...");
        cipher = Cipher.getInstance(this.algorithm);
        cipher.init(Cipher.DECRYPT_MODE, this.keyPair.getPrivate());

        CipherInputStream cis = new CipherInputStream(new ByteArrayInputStream(encryptedPassword), cipher);
        ByteArrayOutputStream baosDecryptedData = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int len = 0;
        while ((len = cis.read(buffer)) > 0) {
            baosDecryptedData.write(buffer, 0, len);
        }
        baosDecryptedData.flush();
        cis.close();

        log.debug("...finish");

        return new String(baosDecryptedData.toByteArray());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new IllegalStateException(e.getMessage(), e);
    }
}

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  ww  .java  2 s .com*/

    out.flush();
    out.close();
    cis.close();
    in.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.//www. 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)
        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");
}