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:com.doplgangr.secrecy.FileSystem.File.java

public CipherInputStream readStream(CryptStateListener listener) {
    try {//from   www.j av  a  2  s .c  o  m
        AES_Encryptor enc = new AES_Encryptor(key);
        return new CipherInputStream(new FileInputStream(file), enc.decryptstream()) {

            @Override
            public int available() throws IOException {
                // The cipher input stream always returns 0 because
                // in certain implementations (padded ciphers), a
                // standard implementation may not be able to
                // accurately determine the number of available
                // bytes. In our case, however, we are not using a
                // padded cipher and the number of available bytes
                // 'should' be the same as the number available from
                // the underlying stream.

                int available = in.available();
                Util.log("**CipherInputStream.available: " + available);
                return available;
            }
        };
    } catch (FileNotFoundException e) {
        listener.onFailed(2);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:hudson.cli.Connection.java

/**
 * Upgrades a connection with transport encryption by the specified symmetric cipher.
 *
 * @return//from   w  ww  . j  a  v  a  2s. com
 *      A new {@link Connection} object that includes the transport encryption.
 */
public Connection encryptConnection(SecretKey sessionKey, String algorithm)
        throws IOException, GeneralSecurityException {
    Cipher cout = Cipher.getInstance(algorithm);
    cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
    CipherOutputStream o = new CipherOutputStream(out, cout);

    Cipher cin = Cipher.getInstance(algorithm);
    cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
    CipherInputStream i = new CipherInputStream(in, cin);

    return new Connection(i, o);
}

From source file:org.openTwoFactor.clientExt.edu.internet2.middleware.morphString.Crypto.java

/**
 * Get the encrypted input stream//from w ww .  j a va2s .  c o  m
 * @param in
 * @return the encrypted input stream
 */
public InputStream encrypt(InputStream in) {
    this.initCipher(true);
    return new CipherInputStream(in, this.cipher);
}

From source file:org.openmrs.module.clinicalsummary.io.DownloadSummariesTask.java

/**
 * Method that will be called to process the summary collection file. Download process will create one zipped and encrypted collection of summary
 * files.//from  ww w  . ja  v a 2 s.c  om
 * <p/>
 * this.passphrase = password;
 *
 * @throws Exception
 */
protected final void processSummaries() throws Exception {
    // TODO: The better approach would be to create zip file and then encrypt it.
    // And then Content of the zip file:
    // * Zipped file of summary files and sql file
    // * Sample file to be used for decryption testing
    String zipFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ZIP), ".");
    File zipFile = new File(TaskUtils.getZippedOutputPath(), zipFilename);
    ZipOutputStream zipOutStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MONTH, -1);
    Date cutOffDate = null;
    if (BooleanUtils.isTrue(partial)) {
        cutOffDate = calendar.getTime();
    }

    File inputPath = TaskUtils.getSummaryOutputPath();
    File[] files = inputPath.listFiles();
    if (files != null) {
        for (File file : files) {
            processStream(zipOutStream, inputPath.getAbsolutePath(), file, cutOffDate);
        }
    }
    zipOutStream.close();

    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");
    File encryptedOutFile = new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename);
    ZipOutputStream encryptedZipOutStream = new ZipOutputStream(
            new BufferedOutputStream(new FileOutputStream(encryptedOutFile)));

    int count;
    byte[] data;
    // add the 16 bytes init vector for the cipher into the output stream
    String secretFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_SECRET), ".");
    ZipEntry ivZipEntry = new ZipEntry(secretFilename);
    encryptedZipOutStream.putNextEntry(ivZipEntry);
    // write the 16 bytes init vector for the cipher into the output stream
    AlgorithmParameters params = cipher.getParameters();
    byte[] initVector = params.getParameterSpec(IvParameterSpec.class).getIV();
    encryptedZipOutStream.write(initVector);
    // add the sample file entry
    String sampleFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_SAMPLE), ".");
    ZipEntry sampleZipEntry = new ZipEntry(sampleFilename);
    encryptedZipOutStream.putNextEntry(sampleZipEntry);
    // write the sample file
    data = new byte[TaskConstants.BUFFER_SIZE];
    String sampleText = "This is sample text inside encrypted document. "
            + "If you see this text, that means your decryption parameters is correct";
    InputStream inStream = new ByteArrayInputStream(sampleText.getBytes());
    CipherInputStream sampleCipherInStream = new CipherInputStream(inStream, cipher);
    while ((count = sampleCipherInStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
        encryptedZipOutStream.write(data, 0, count);
    }
    sampleCipherInStream.close();
    // add the zipped summaries
    ZipEntry zipEntry = new ZipEntry(zipFile.getName());
    encryptedZipOutStream.putNextEntry(zipEntry);
    // write the zipped summaries
    data = new byte[TaskConstants.BUFFER_SIZE];
    InputStream zipInStream = new BufferedInputStream(new FileInputStream(zipFile));
    CipherInputStream zipCipherInStream = new CipherInputStream(zipInStream, cipher);
    while ((count = zipCipherInStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
        encryptedZipOutStream.write(data, 0, count);
    }
    zipCipherInStream.close();
    encryptedZipOutStream.close();
}

From source file:org.codice.ddf.configuration.migration.MigrationZipFile.java

private CipherInputStream getCipherInputStreamFor(InputStream inputStream) {
    return new CipherInputStream(inputStream, cipher);
}

From source file:org.openTwoFactor.clientExt.edu.internet2.middleware.morphString.Crypto.java

/**
 * the decrypted input stream/*from   w  ww . j a  v a2s.c om*/
 * @param in
 * @return the decrypted input stream
 */
public InputStream decrypt(InputStream in) {
    this.initCipher(false);
    return new CipherInputStream(in, this.cipher);
}

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

public static SecretKey decryptShareKey(ShareKeyDBEntry entry, PublicKey pubKey, PrivateKey privKey) {
    SecretKey result = null;/*from  ww  w. j  av  a  2s.  co m*/
    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:sec_algo.commonenc.java

public void decryptFile() {
    File decrypted = new File("demo2de\\" + returnFileName() + "_decrypted." + returnFileExt());
    try {/*from  w ww  .java 2 s  .  c  om*/
        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:org.opendatakit.briefcase.export.SubmissionParser.java

private static Path decryptFile(Path encFile, Path workingDir, Cipher cipher) {
    Path decryptedFile = workingDir.resolve(stripFileExtension(encFile.getFileName().toString()));
    try (InputStream is = Files.newInputStream(encFile);
            CipherInputStream cis = new CipherInputStream(is, cipher);
            OutputStream os = Files.newOutputStream(decryptedFile)) {
        byte[] buffer = new byte[2048];
        int len = cis.read(buffer);
        while (len != -1) {
            os.write(buffer, 0, len);/*from   w w  w  .j  a  va 2 s . com*/
            len = cis.read(buffer);
        }
        os.flush();
        return decryptedFile;
    } catch (IOException e) {
        throw new CryptoException("Can't decrypt file", e);
    }
}

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.
 *///ww w.  jav  a  2  s . c  o 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();
}