Example usage for javax.crypto CipherOutputStream flush

List of usage examples for javax.crypto CipherOutputStream flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream by forcing any buffered output bytes that have already been processed by the encapsulated cipher object to be written out.

Usage

From source file:Main.java

public static void encrypt(String fileIn, String fileOut, byte key[])
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    // Here you read the cleartext.
    FileInputStream fis = new FileInputStream(fileIn);
    // This stream write the encrypted text. This stream will be wrapped by another stream.
    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);// ww w.  j av  a  2s  .co  m
    SecretKeySpec sks = new SecretKeySpec(key, "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();
}

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

public static byte[] _asymmetricDecrypt(byte[] symKey, PrivateKey pKey)
        throws InvalidKeyException, IOException {
    ASYMM_CIPHER.init(Cipher.DECRYPT_MODE, pKey);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    CipherOutputStream cos = new CipherOutputStream(bos, ASYMM_CIPHER);
    cos.write(symKey);// ww  w .  j ava  2  s  .  c o m
    cos.flush();
    cos.close();
    byte[] byteArray = bos.toByteArray();
    return byteArray;
}

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

public static byte[] encryptSymmetricKey(byte[] symKey, PublicKey pKey) throws SymmetricKeyEncryptionException {
    try {//  w  w w .  ja  va2s  .  c  o  m
        ASYMM_CIPHER.init(Cipher.ENCRYPT_MODE, pKey);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        CipherOutputStream cos = new CipherOutputStream(bos, ASYMM_CIPHER);
        cos.write(symKey);
        cos.flush();
        cos.close();
        byte[] byteArray = bos.toByteArray();
        return byteArray;
    } catch (Exception e) {
        throw new SymmetricKeyEncryptionException(e);
    }
}

From source file:com.data.pack.Util.java

public static void copyFile(InputStream in, OutputStream out, int flag) throws IOException {
    byte[] buffer = new byte[1024];
    int read;/* w  ww.j  av a2s.c  o  m*/

    try {

        Cipher encipher = null;
        try {
            encipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Cipher decipher = null;
        try {
            decipher = Cipher.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        KeyGenerator kgen = null;
        try {
            kgen = KeyGenerator.getInstance("AES");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        byte[] keyStart = "fitnesSbridge".getBytes();
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();

        // byte key[] =
        // {0x00,0x32,0x22,0x11,0x00,0x00,0x00,0x00,0x00,0x23,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
        skey = kgen.generateKey();
        // Lgo
        try {
            encipher.init(Cipher.ENCRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherInputStream cis = new CipherInputStream(in, encipher);
        try {
            decipher.init(Cipher.DECRYPT_MODE, skey);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        CipherOutputStream cos = new CipherOutputStream(out, decipher);

        try {

            if (flag == 2) {
                cos = new CipherOutputStream(out, encipher);
            } else {
                cos = new CipherOutputStream(out, decipher);
            }
            while ((read = in.read()) != -1) {
                cos.write(read);
                cos.flush();
            }

            cos.flush();
            cos.close();
            in.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } catch (Exception e) {
        // TODO: handle exception
    }

    //
    // byte[] keyStart = "this is a key".getBytes();
    // KeyGenerator kgen = KeyGenerator.getInstance("AES");
    // SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    // sr.setSeed(keyStart);
    // kgen.init(128, sr); // 192 and 256 bits may not be available
    // SecretKey skey = kgen.generateKey();
    // byte[] key = skey.getEncoded();
    //
    //
    // byte[] b = baos.toByteArray();
    // while ((read = in.read(buffer)) != -1) {
    //
    // // decrypt
    // byte[] decryptedData = Util.decrypt(key,buffer);
    // out.write(decryptedData, 0, read);
    // }
    // } catch (NoSuchAlgorithmException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // catch (Exception e) {
    // // TODO: handle exception
    // }
    //
}

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

public byte[] encryptPassowrd(String password) {

    Cipher cipher;//w  ww. jav a2s. c o m
    try {
        cipher = Cipher.getInstance(this.algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, this.keyPair.getPublic());

        ByteArrayOutputStream baosEncryptedData = new ByteArrayOutputStream();
        CipherOutputStream cos = new CipherOutputStream(baosEncryptedData, cipher);

        cos.write(password.getBytes("UTF-8"));
        cos.flush();
        cos.close();

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

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

private static void encryptFile(File file, EncryptedFormInformation formInfo)
        throws IOException, EncryptionException {
    File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc");

    if (encryptedFile.exists() && !encryptedFile.delete()) {
        throw new IOException(
                "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?");
    }//from   w w  w .j  a v  a  2 s  . c o  m

    // add elementSignatureSource for this file...
    formInfo.appendFileSignatureSource(file);

    RandomAccessFile randomAccessFile = null;
    CipherOutputStream cipherOutputStream = null;
    try {
        Cipher c = formInfo.getCipher();

        randomAccessFile = new RandomAccessFile(encryptedFile, "rws");
        ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
        cipherOutputStream = new CipherOutputStream(encryptedData, c);
        InputStream fin = new FileInputStream(file);
        byte[] buffer = new byte[2048];
        int len = fin.read(buffer);
        while (len != -1) {
            cipherOutputStream.write(buffer, 0, len);
            len = fin.read(buffer);
        }
        fin.close();
        cipherOutputStream.flush();
        cipherOutputStream.close();

        randomAccessFile.write(encryptedData.toByteArray());

        Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName());
    } catch (Exception e) {
        String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName();
        Log.e(t, msg, e);
        e.printStackTrace();
        throw new EncryptionException(msg, e);
    } finally {
        IOUtils.closeQuietly(cipherOutputStream);

        if (randomAccessFile != null) {
            randomAccessFile.close();
        }
    }
}

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. ja v  a  2s .  c  o  m
 * @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   w  w  w .  jav a  2 s  .c  om
 * @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 {/*from   w w w  . ja v a  2s. co 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  ava  2s .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();
}