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.cubusmail.server.mail.security.MailPasswordEncryptor.java

public String decryptPassword(byte[] encryptedPassword) {

    Cipher cipher;//from  w ww .  ja  v  a2  s.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:sec_algo.commonenc.java

/**
* Decrypts an AES key from a file using an RSA private key
*///from   w  ww. j  av a2s .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
        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:de.marius_oe.cfs.cryption.Crypter.java

/**
 * Decrypts the given input stream and stores the decrypted bytes in the
 * destinationFile. If compressStream is <code>true</code>, the given stream
 * has been compressed and is uncompressed after decryption.
 *
 * @param inStream/*from ww  w  .  j ava2  s  .c o m*/
 *            source stream with encrypted data and iv at the beginning
 * @param destinationStream
 *            stream for the decrypted data
 * @param compressStream
 *            whether the stream was compressed before encryption
 */
public static void decrypt(InputStream inStream, OutputStream destinationStream, boolean compressStream) {
    logger.debug("decrypting inputstream - compressed: {}", compressStream);

    try {
        // reading iv of stream
        int ivLength = inStream.read();
        byte[] iv = new byte[ivLength];
        inStream.read(iv);

        logger.debug("Decrypt InputStream.");
        inStream = new CipherInputStream(inStream, getCipher(Cipher.DECRYPT_MODE, iv));

        if (compressStream) {
            logger.debug("Decompress InputStream.");

            try {
                inStream = new ZipInputStream(inStream);
                ((ZipInputStream) inStream).getNextEntry();
            } catch (IOException e) {
                logger.debug("Error occured during unzipping - Reason: {}", e.getLocalizedMessage());
                throw new RuntimeException(e);
            }
        }

        // copy stream
        int bytesCopied = IOUtils.copy(inStream, destinationStream);

        logger.debug("decryption done. copied {} decrypted bytes to the outputstream", bytesCopied);

        inStream.close();
        destinationStream.close();
    } catch (IOException e) {
        logger.error("Decryption failed - Reason: {}", e.getLocalizedMessage());
        throw new RuntimeException(e);
    }
}

From source file:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedTempData.java

public InputStream getInputStream() throws FileNotFoundException {
    if (this.ciDecrypt != null) { // decrypt tempdata
        LOG.debug("Returning decrypted InputStream for " + this.tempFile.getAbsolutePath());
        LOG.debug("Size of temp file: " + this.tempFile.length());
        return new CipherInputStream(new FileInputStream(this.tempFile), this.ciDecrypt);
    }/* www .  j  av a2  s. c o  m*/
    return new FileInputStream(this.tempFile);
}

From source file:org.jenkinsci.plugins.fabric8.support.hack.AnnotatedLargeText.java

private ConsoleAnnotator createAnnotator(StaplerRequest req) throws IOException {
    try {// ww  w  .  j av a 2s.  c om
        String e = req != null ? req.getHeader("X-ConsoleAnnotator") : null;
        if (e != null) {
            Cipher sym = PASSING_ANNOTATOR.decrypt();
            ObjectInputStreamEx ois = new ObjectInputStreamEx(
                    new GZIPInputStream(new CipherInputStream(
                            new ByteArrayInputStream(Base64.decode(e.toCharArray())), sym)),
                    Jenkins.getInstance().pluginManager.uberClassLoader);

            ConsoleAnnotator var7;
            try {
                long timestamp = ois.readLong();
                if (TimeUnit2.HOURS.toMillis(1L) <= Math.abs(System.currentTimeMillis() - timestamp)) {
                    return ConsoleAnnotator.initial(this.context == null ? null : this.context.getClass());
                }

                var7 = (ConsoleAnnotator) ois.readObject();
            } finally {
                ois.close();
            }

            return var7;
        }
    } catch (ClassNotFoundException var12) {
        throw new IOException(var12);
    }

    return ConsoleAnnotator.initial(this.context == null ? null : this.context.getClass());
}

From source file:enc_mods.aes.java

/**
* Decrypts an AES key from a file using an RSA private key
*//*www . ja  v  a2 s .co 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:jatoo.properties.FileProperties.java

public synchronized FileProperties load() throws IOException {

    InputStream stream = null;//from   www  .j  a v a2 s  . c o  m

    try {

        stream = new FileInputStream(file);

        if (cipherDecrypt != null) {
            stream = new CipherInputStream(stream, cipherDecrypt);
        }

        load(stream);
    }

    catch (IOException e) {
        throw e;
    }

    finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
            }
        }
    }

    return this;
}

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

public static String decrypt(byte[] data, Path keyPath)
        throws IOException, DecoderException, NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidKeyException, InvalidAlgorithmParameterException {

    String keyData = new String(readFileToByteArray(keyPath.toFile()), StandardCharsets.UTF_8);
    byte[] keyBytes = decodeHex(keyData.toCharArray());
    SecretKey secretKey = new SecretKeySpec(keyBytes, MigrationZipConstants.KEY_ALGORITHM);
    Cipher cipher = Cipher.getInstance(MigrationZipConstants.CIPHER_ALGORITHM);
    IvParameterSpec iv = new IvParameterSpec(MigrationZipConstants.CIPHER_IV);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
    String decryptedContent;//from ww w .j av a2  s  .  com
    try (InputStream is = new CipherInputStream(ByteSource.wrap(data).openStream(), cipher)) {
        decryptedContent = IOUtils.toString(is, StandardCharsets.UTF_8);
    }
    return decryptedContent;
}

From source file:org.pieShare.pieShareApp.service.fileService.fileEncryptionService.FileEncryptionService.java

@Override
public void decryptFile(File source, File target) {
    try {/*from w  w  w  .java2  s.co  m*/
        //CipherInputStream stream = new CipherInputStream(new FileInputStream(this.fileService.getAbsolutePath(file).toFile()), this.getCipher(Cipher.DECRYPT_MODE));
        FileInputStream fileStream = new FileInputStream(source);
        CipherInputStream stream = new CipherInputStream(fileStream, this.getCipher(Cipher.DECRYPT_MODE));
        //Base64InputStream base64Input = new Base64InputStream(fileStream);
        //FileOutputStream outputStream = new FileOutputStream(this.fileService.getAbsolutePath(workingFile).toFile());
        FileOutputStream outputStream = new FileOutputStream(target);
        this.rewriteFile(stream, outputStream);
    } catch (FileNotFoundException ex) {
        PieLogger.error(this.getClass(), "Error!", ex);
    } catch (IOException ex) {
        PieLogger.error(this.getClass(), "Error!", ex);
    } catch (InvalidKeyException ex) {
        PieLogger.error(this.getClass(), "Error!", ex);
    }
}

From source file:org.alfresco.encryption.AbstractEncryptor.java

/**
 * {@inheritDoc}/*from  ww w .  ja  va2  s.  c o  m*/
 */
@Override
public InputStream decrypt(String keyAlias, AlgorithmParameters params, InputStream input) {
    Cipher cipher = getCipher(keyAlias, params, Cipher.DECRYPT_MODE);
    if (cipher == null) {
        return input;
    }

    try {
        return new CipherInputStream(input, cipher);
    } catch (Throwable e) {
        throw new AlfrescoRuntimeException("Decryption failed for key alias: " + keyAlias, e);
    }
}