Example usage for javax.crypto CipherOutputStream write

List of usage examples for javax.crypto CipherOutputStream write

Introduction

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

Prototype

public void write(byte b[], int off, int len) throws IOException 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this output stream.

Usage

From source file:org.apache.synapse.securevault.BaseCipher.java

/**
 * Do cryptographic operation//from   w  ww  .j  ava 2 s .  c om
 *
 * @param inputStream Input Stream
 * @return result
 */
private byte[] doCipherOperation(byte[] inputStream) {

    InputStream sourceStream = new ByteArrayInputStream(inputStream);
    if (cipherInformation.getInType() != null) {
        try {
            sourceStream = EncodingHelper.decode(sourceStream, cipherInformation.getInType());
        } catch (IOException e) {
            throw new SecureVaultException("IOError when decoding the input " + "stream for cipher ", e, log);
        }
    }

    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) {
        throw new SecureVaultException("IOError when reading the input" + " stream for cipher ", e, log);
    } finally {
        try {
            sourceStream.close();
            out.flush();
            out.close();
        } catch (IOException ignored) {
            // ignore exception
        }
    }

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

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Encrypts the message read from the specified input stream and writes the cipher text to the 
 * specified output stream./*from   w w  w.j  ava2  s . c  om*/
 * @param fis input stream from where to read the plain text message.
 * @param fos output stream to where the cipher text is written.
 * @throws Exception if an error occurs in the execution of the operation.
 */
public void encrypt(final InputStream fis, final OutputStream fos) throws Exception {
    CipherOutputStream cos = null;
    try {
        cos = new CipherOutputStream(fos, encryptCipher);
        final byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fis.read(buffer)) >= 0) {
            cos.write(buffer, 0, bytesRead);
        }
        cos.flush();
    } finally {
        try {
            fis.close();
        } catch (Exception ignore) {
        }
        try {
            cos.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:org.grycap.gpf4med.security.FileEncryptionProvider.java

/**
 * Decrypts the cipher text read from the specified input stream and writes the decrypted message to 
 * the specified output stream.//from  ww  w.  j a v a  2s.c o m
 * @param inputStream input stream from where to read the cipher text.
 * @param outputStream output stream to where the decrypted message is written.
 * @throws Exception if an error occurs in the execution of the operation.
 */
public void decrypt(final InputStream fis, final OutputStream fos) throws Exception {
    CipherOutputStream cos = null;
    try {
        cos = new CipherOutputStream(fos, decryptCipher);
        final byte[] buffer = new byte[1024];
        int bytesRead = 0;
        while ((bytesRead = fis.read(buffer)) >= 0) {
            cos.write(buffer, 0, bytesRead);
        }
        cos.flush();
    } finally {
        try {
            fis.close();
        } catch (Exception ignore) {
        }
        try {
            cos.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java

public void encrypt(InputStream in, OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException,
        BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(jcrypto.getAlgorithm());
    if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES);
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec);
    } else {//  w  w w .  ja va  2s .  c o m
        cipher.init(Cipher.ENCRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()));
    }

    CipherOutputStream cos = new CipherOutputStream(out, cipher);

    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        cos.write(buffer, 0, bytesRead);
        cos.flush();
    }
    cos.close();

    java.util.Arrays.fill(buffer, (byte) 0);
}

From source file:org.linagora.linshare.core.utils.SymmetricEnciphermentPBEwithAES.java

public void encryptStream() throws IOException {

    if (cipherMode != Cipher.ENCRYPT_MODE)
        throw new IllegalStateException("can not call encrypt, check cipher mode");

    out.write(salt, 0, SALT_NUMBER_BITES);

    byte v[] = new byte[4];
    //*** writeInt
    v[0] = (byte) (0xff & (iterations >> 24));
    v[1] = (byte) (0xff & (iterations >> 16));
    v[2] = (byte) (0xff & (iterations >> 8));
    v[3] = (byte) (0xff & iterations);
    out.write(v);/*from   ww w. j  a  va2s  .  c  o  m*/
    out.flush();

    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.flush();
    cos.close();
    out.close();
    in.close();
}

From source file:craterdog.security.MessageCryptex.java

@Override
public void encryptStream(SecretKey sharedKey, InputStream input, OutputStream output) throws IOException {
    logger.entry();/*from   w w  w.  java2 s  . com*/
    CipherOutputStream cipherOutput = null;
    byte[] buffer = new byte[2048];
    try {
        logger.debug("Creating a special output stream to do the work...");
        cipherOutput = encryptionOutputStream(sharedKey, output);

        logger.debug("Reading from the input and writing to the encrypting output stream...");
        // Can't use IOUtils.copy(input, cipherOutput) here because need to purge buffer later...
        int bytesRead;
        while ((bytesRead = input.read(buffer)) != -1) {
            cipherOutput.write(buffer, 0, bytesRead);
        }
        cipherOutput.flush();
    } finally {
        logger.debug("Purging any plaintext hanging around in memory...");
        Arrays.fill(buffer, (byte) 0);

        if (cipherOutput != null)
            cipherOutput.close();
    }
    logger.exit();
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

protected File createDataFile(InputStream data, String username, char[] password) throws IOException {
    try {//from  w ww  .ja  v a2 s .com
        String fileName = UUID.randomUUID().toString();

        File folder = new File(storageFolder, username);
        folder = new File(folder, fileName.substring(0, 2));
        folder.mkdirs();

        File file = new File(folder, fileName);

        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(username, password));

        OutputStream fOut = new BufferedOutputStream(new FileOutputStream(file));
        CipherOutputStream out = new CipherOutputStream(fOut, cipher);

        InputStream in = new BufferedInputStream(data);
        byte[] buffer = new byte[2048];
        int readed;
        while ((readed = in.read(buffer)) != -1) {
            out.write(buffer, 0, readed);
        }
        in.close();

        out.flush();
        out.close();
        fOut.flush();
        fOut.close();

        return file;
    } catch (Exception ex) {
        // TODO: better exception handling
        Logger.getAnonymousLogger().log(Level.SEVERE, "ERROR", ex);
        throw new RuntimeException(ex);
    } finally {
        data.close();
    }
}

From source file:com.denel.facepatrol.MainActivity.java

private void decryptfile(Context mcontext, SecretKey key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

    File infile = mcontext.getDatabasePath(dbname_en);
    InputStream fis = new FileInputStream(infile);
    File outfile = mcontext.getDatabasePath(dbname);
    // parent directory for his file if it doesn't exist,
    // in this case it returns a false.
    outfile.getParentFile().mkdirs();//ww w  .  java  2 s . co m
    // This stream write the decrypted text. This stream will be wrapped by another stream. 
    FileOutputStream fos = new FileOutputStream(outfile);
    // Length is 16 byte // Careful when taking user input!!! 
    // http://stackoverflow.com/a/3452620/1188357 
    SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES");
    // Create cipher 
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, sks);
    // Wrap the output stream 
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes 
    int b;
    byte[] d = new byte[8];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    } // Flush and close streams. 
    cos.flush();
    cos.close();
    fis.close();
    // delete the encrypted file
    if (infile.exists()) {
        infile.delete();
    }
}

From source file:com.denel.facepatrol.MainActivity.java

private void encryptfile(Context mcontext, SecretKey key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {

    // This will probably change when I will the database will be downloaded from the server
    boolean db_file_exists = mcontext.getDatabasePath(dbname).exists();
    InputStream fis = null;//from  ww  w. j  a  va 2s  .  co  m
    File infile = mcontext.getDatabasePath(dbname);
    // check if database file exists to prevent downloading the file each start
    if (db_file_exists) {
        fis = new FileInputStream(infile);
    } else {
        fis = mcontext.getAssets().open(dbname);
    }
    // This stream write the encrypted text. This stream will be wrapped by another stream. 
    FileOutputStream fos = new FileOutputStream(mcontext.getDatabasePath(dbname_en).getAbsolutePath());
    // Length is 16 byte // Careful when taking user input!!! http://stackoverflow.com/a/3452620/1188357 
    SecretKeySpec sks = new SecretKeySpec(key.getEncoded(), "AES");
    // Create cipher 
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, sks);
    // Wrap the output stream 
    CipherOutputStream cos = new CipherOutputStream(fos, cipher);
    // Write bytes 
    int b;
    byte[] d = new byte[8];
    while ((b = fis.read(d)) != -1) {
        cos.write(d, 0, b);
    } // Flush and close streams. 
    cos.flush();
    cos.close();
    fis.close();
    // delete the decrypted file
    if (infile.exists()) {
        infile.delete();
    }
}

From source file:org.apache.camel.converter.crypto.CryptoDataFormat.java

public void marshal(Exchange exchange, Object graph, OutputStream outputStream) throws Exception {
    byte[] iv = getInitializationVector(exchange);
    Key key = getKey(exchange);/*w  ww .  j av  a  2s  .  c o  m*/

    CipherOutputStream cipherStream = new CipherOutputStream(outputStream,
            initializeCipher(ENCRYPT_MODE, key, iv));
    InputStream plaintextStream = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
    HMACAccumulator hmac = getMessageAuthenticationCode(key);
    if (plaintextStream != null) {
        inlineInitVector(outputStream, iv);
        byte[] buffer = new byte[bufferSize];
        int read;
        try {
            while ((read = plaintextStream.read(buffer)) > 0) {
                cipherStream.write(buffer, 0, read);
                cipherStream.flush();
                hmac.encryptUpdate(buffer, read);
            }
            // only write if there is data to write (IBM JDK throws exception if no data)
            byte[] mac = hmac.getCalculatedMac();
            if (mac != null && mac.length > 0) {
                cipherStream.write(mac);
            }
        } finally {
            IOHelper.close(cipherStream, "cipher", LOG);
        }
    }
}