Example usage for javax.crypto CipherOutputStream CipherOutputStream

List of usage examples for javax.crypto CipherOutputStream CipherOutputStream

Introduction

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

Prototype

public CipherOutputStream(OutputStream os, Cipher c) 

Source Link

Document

Constructs a CipherOutputStream from an OutputStream and a Cipher.

Usage

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

public void setInputStream(InputStream is) throws IOException {
    this.tmpFile = TempFile.createTempFile("hadoopoffice-protected", ".zip");

    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
    ZipArchiveEntry ze;// w  ww  .  j  av a2 s  .co m
    while ((ze = (ZipArchiveEntry) zis.getNextEntry()) != null) {
        // rewrite zip entries to match the size of the encrypted data (with padding)
        ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
        zeNew.setComment(ze.getComment());
        zeNew.setExtra(ze.getExtra());
        zeNew.setTime(ze.getTime());
        zos.putArchiveEntry(zeNew);
        FilterOutputStream fos2 = new FilterOutputStream(zos) {
            // do not close underlyzing ZipOutputStream
            @Override
            public void close() {
            }
        };
        OutputStream nos;
        if (this.ciEncoder != null) { // encrypt if needed
            nos = new CipherOutputStream(fos2, this.ciEncoder);
        } else { // do not encrypt
            nos = fos2;
        }
        IOUtils.copy(zis, nos);
        nos.close();
        if (fos2 != null) {
            fos2.close();
        }
        zos.closeArchiveEntry();

    }
    zos.close();
    fos.close();
    zis.close();
    IOUtils.closeQuietly(is);
    this.zipFile = new ZipFile(this.tmpFile);

}

From source file:uploadProcess.java

public static boolean decrypt(File inputFolder, String fileName, String patientID, String viewKey) {
    try {/*from ww  w  .j a v a2s .  c o  m*/

        String ukey = GetKey.getPatientKey(patientID);
        if (viewKey.equals(ukey)) {
            //Download File from Cloud..
            DropboxUpload download = new DropboxUpload();
            download.downloadFile(fileName, StoragePath.getDropboxDir() + patientID, inputFolder);

            File inputFile = new File(inputFolder.getAbsolutePath() + File.separator + fileName);
            FileInputStream fis = new FileInputStream(inputFile);
            File outputFolder = new File(inputFolder.getAbsolutePath() + File.separator + "temp");
            if (!outputFolder.exists()) {
                outputFolder.mkdir();
            }
            FileOutputStream fos = new FileOutputStream(
                    outputFolder.getAbsolutePath() + File.separator + fileName);
            byte[] k = ukey.getBytes();
            SecretKeySpec key = new SecretKeySpec(k, "AES");
            Cipher enc = Cipher.getInstance("AES");
            enc.init(Cipher.DECRYPT_MODE, key);
            CipherOutputStream cos = new CipherOutputStream(fos, enc);
            byte[] buf = new byte[1024];
            int read;
            while ((read = fis.read(buf)) != -1) {
                cos.write(buf, 0, read);
            }
            fis.close();
            fos.flush();
            cos.close();
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

From source file:sec_algo.commonenc.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *///from w  w  w.  ja v  a  2  s .  c o m
public void saveKey(File out, File publicKeyFile) {
    try {
        // read public key to be used to encrypt the AES key
        byte[] encodedKey = new byte[(int) publicKeyFile.length()];
        new FileInputStream(publicKeyFile).read(encodedKey);

        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        // write AES key
        pkCipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:enc_mods.aes.java

/**
 * Encrypts the AES key to a file using an RSA public key
 *///from www.  ja  v  a 2s. c om
public void saveKey(File out, File publicKeyFile) {
    try {
        // read public key to be used to encrypt the AES key
        byte[] encodedKey = new byte[(int) publicKeyFile.length()];
        new FileInputStream(publicKeyFile).read(encodedKey);

        // create public key
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey pk = kf.generatePublic(publicKeySpec);

        // write AES key
        cipher.init(Cipher.ENCRYPT_MODE, pk);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), cipher);
        os.write(key);
        os.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.wso2.carbon.apimgt.core.impl.FileEncryptionUtility.java

/**
 * Encrypts the contents of a file and stores it in a new file
 *
 * @param inputFilePath    absolute path of the file to encrypt
 * @param outputFilePath   expected absolute path of the new encrypted file
 * @throws APIManagementException  if an error occurs encrypting the file
 *//*  w w w .j  a  v  a  2s .  c o m*/
public void encryptFile(String inputFilePath, String outputFilePath) throws APIManagementException {
    InputStream inputStream = null;
    CipherOutputStream cipherOutStream = null;
    try {
        Cipher aesCipher = Cipher.getInstance(EncryptionConstants.AES);
        SecretKeySpec aesKeySpec = new SecretKeySpec(getAESKey(), EncryptionConstants.AES);
        aesCipher.init(Cipher.ENCRYPT_MODE, aesKeySpec);

        Files.deleteIfExists(Paths.get(outputFilePath));
        inputStream = APIFileUtils.readFileContentAsStream(inputFilePath);
        cipherOutStream = new CipherOutputStream(new FileOutputStream(outputFilePath), aesCipher);
        IOUtils.copy(inputStream, cipherOutStream);
        APIFileUtils.deleteFile(inputFilePath);
        log.debug("Successfully encrypted file using stored AES key");
    } catch (NoSuchPaddingException | NoSuchAlgorithmException | IOException | InvalidKeyException e) {
        String msg = "Error while encrypting the file at " + inputFilePath;
        throw new APIManagementException(msg, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(cipherOutStream);
    }
}

From source file:models.logic.CipherDecipher.java

public static void encryptOrDecrypt(SecretKey key, int mode, InputStream is, OutputStream os) throws Throwable {
    Cipher cipher = Cipher.getInstance("AES");
    if (mode == Cipher.ENCRYPT_MODE) {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        CipherInputStream cis = new CipherInputStream(is, cipher);
        doCopy(cis, os);/*  w  w w. j  a  v a  2s  . com*/
    } else if (mode == Cipher.DECRYPT_MODE) {
        cipher.init(Cipher.DECRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(os, cipher);
        doCopy(is, cos);
    }
}

From source file:it.doqui.index.ecmengine.business.personalization.encryption.content.EncryptingContentWriterDecorator.java

public OutputStream getContentOutputStream() throws ContentIOException {
    logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] BEGIN");

    IvParameterSpec iv = null;// w ww . j a v a2 s . co  m

    try {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec),
                    "SunJCE");
        } catch (NoSuchProviderException e) {
            logger.warn(
                    "[EncryptingContentWriterDecorator::getContentOutputStream] Unknown provider \"SunJCE\". Using default...");
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(transformationSpec));
        }

        if (transformationSpec.getMode() != null && !transformationSpec.getMode().equalsIgnoreCase("ECB")) {
            iv = new IvParameterSpec(transformationSpec.getIv());
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }

        logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] "
                + "Cipher initialized: ENCRYPT - " + cipher.getProvider() + " - " + cipher.getAlgorithm());

        CipherOutputStream cos = new CipherOutputStream(writer.getContentOutputStream(), cipher);

        return cos;
    } catch (NoSuchPaddingException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid padding: "
                + transformationSpec.getPadding());
        throw new EncryptionRuntimeException("Invalid padding: " + transformationSpec.getPadding(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm: "
                + transformationSpec.getAlgorithm());
        throw new EncryptionRuntimeException("Invalid algorithm: " + transformationSpec.getAlgorithm(), e);
    } catch (InvalidKeyException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid key!");
        throw new EncryptionRuntimeException("Invalid key!", e);
    } catch (InvalidAlgorithmParameterException e) {
        logger.warn("[EncryptingContentWriterDecorator::getContentOutputStream] Invalid algorithm parameter: "
                + iv);
        throw new EncryptionRuntimeException("Invalid algorithm parameter: " + iv, e);
    } finally {
        logger.debug("[EncryptingContentWriterDecorator::getContentOutputStream] END");
    }
}

From source file:org.apache.synapse.commons.security.wrappers.CipherWrapper.java

/**
 * Returns the output of the cipher operation.
 * This expose the 'getSecret' abstraction and hide operation of the underlying cipher
 *
 * @param inputStream Input as a stream. This can be either cipher or plain text
 * @return Secret as String.This can be either cipher or plain text
 */// ww w . j  av a 2  s.com
public String getSecret(InputStream inputStream) {

    InputStream sourceStream = null;
    if (cipherInformation.getInType() != null) {
        try {
            sourceStream = EncodingHelper.decode(inputStream, cipherInformation.getInType());
        } catch (IOException e) {
            handleException("IOError when decoding the input stream for cipher ", e);
        }
    } else {
        sourceStream = inputStream;
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    CipherOutputStream out = new CipherOutputStream(baos, cipher);

    byte[] buffer = new byte[64];
    int length;
    try {
        while ((length = sourceStream.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
    } catch (IOException e) {
        handleException("IOError when reading the input stream for cipher ", e);
    } finally {
        try {
            sourceStream.close();
            out.flush();
            out.close();
        } catch (IOException ignored) {
            // ignore exception
        }
    }

    String secret;
    if (cipherInformation.getOutType() != null) {
        secret = EncodingHelper.encode(baos, cipherInformation.getOutType());
    } else {
        secret = baos.toString();
    }
    return secret;
}

From source file:com.doplgangr.secrecy.FileSystem.Vault.java

public String addFile(final Context context, final Uri uri) {
    String filename = uri.getLastPathSegment();
    try {//from ww w.  j  a  v a2  s .  c om
        String realPath = getPath(context, uri);
        Util.log(realPath, filename);
        filename = new java.io.File(realPath).getName();
        // If we can use real path, better use one.
    } catch (Exception ignored) {
        // Leave it.
    }
    if (!filename.contains("_thumb") && !filename.contains(".nomedia")) {
        ContentResolver cR = context.getContentResolver();
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String type = mime.getExtensionFromMimeType(cR.getType(uri));
        if (type != null)
            filename = Base64Coder.encodeString(FilenameUtils.removeExtension(filename)) + "." + type;
    }
    InputStream is = null;
    OutputStream out = null;
    try {
        InputStream stream = context.getContentResolver().openInputStream(uri);
        java.io.File addedFile = new java.io.File(path + "/" + filename);
        addedFile.delete();
        addedFile.createNewFile();
        is = new BufferedInputStream(stream);
        byte buffer[] = new byte[Config.bufferSize];
        int count;
        AES_Encryptor enc = new AES_Encryptor(key);
        out = new CipherOutputStream(new FileOutputStream(addedFile), enc.encryptstream());
        while ((count = is.read(buffer)) != -1)
            out.write(buffer, 0, count);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return filename;
}

From source file:TripleDES.java

/**
 * Use the specified TripleDES key to encrypt bytes from the input stream
 * and write them to the output stream. This method uses CipherOutputStream
 * to perform the encryption and write bytes at the same time.
 *//* w  ww  .  ja v  a2s. c  o m*/
public static void encrypt(SecretKey key, InputStream in, OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException {
    // Create and initialize the encryption engine
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);

    // Create a special output stream to do the work for us
    CipherOutputStream cos = new CipherOutputStream(out, cipher);

    // Read from the input and write to the encrypting output stream
    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        cos.write(buffer, 0, bytesRead);
    }
    cos.close();

    // For extra security, don't leave any plaintext hanging around memory.
    java.util.Arrays.fill(buffer, (byte) 0);
}