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:uk.ac.ox.webauth.Token.java

/**
 * Encode the token and return it.//from  ww  w  . j a v  a  2s . c  o  m
 * @param   sessionKey  The session key to use to AES encrypt and feed the HMAC.
 * @return  The escaped, encrypted and base64 encoded token.
 * @throws  GeneralSecurityException    if there was a problem with the security code used.
 */
public String encrypt(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

    // this is where we want to final data packet to end up
    ByteArrayOutputStream data = new ByteArrayOutputStream();
    try {
        data.write(unixTimestampBytes(System.currentTimeMillis()));

        // set up the AES encryption
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(ENCRYPT_MODE, sessionKey, IV);
        CipherOutputStream encrypt = new CipherOutputStream(data, cipher);

        // write the nonce
        byte[] nonce = new byte[16];
        RAND.nextBytes(nonce);
        encrypt.write(nonce);

        // put together the actual key-value pair data to send
        ByteArrayOutputStream paddedKeyValueData = new ByteArrayOutputStream();
        for (KeyValuePair kvp : kv.values()) {
            paddedKeyValueData.write(kvp.bytes());
        }

        // and pad it (including the size of the hmac to be added later)
        int padding = 16 - ((20 + paddedKeyValueData.size()) % 16);
        for (int i = 0; i < padding; i++) {
            paddedKeyValueData.write(padding);
        }
        byte[] paddedKeyValueDataArray = paddedKeyValueData.toByteArray();

        // then work out and write the SHA1 HMAC
        Mac hmacSHA1 = Mac.getInstance("HmacSHA1");
        hmacSHA1.init(sessionKey);
        encrypt.write(hmacSHA1.doFinal(paddedKeyValueDataArray));

        // then write the actual key-value pair data and padding and close it
        encrypt.write(paddedKeyValueDataArray);
        encrypt.close();
    } catch (IOException ioe) {
        /* should never happen as it's a ByteArrayOutputStream */
        ioe.printStackTrace();
    }

    // return the token after base64 encoding it
    return new String(Base64.encodeBase64(data.toByteArray()));
}

From source file:org.opendatakit.services.utilities.EncryptionUtils.java

private static void encryptFile(File file, File encryptedFile, EncryptedFormInformation formInfo)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {

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

    try {//  ww w . j  a v  a 2 s.  co m
        Cipher c = formInfo.getCipher();

        OutputStream fout;
        fout = new FileOutputStream(encryptedFile);
        fout = new CipherOutputStream(fout, c);
        InputStream fin;
        fin = new FileInputStream(file);
        byte[] buffer = new byte[2048];
        int len = fin.read(buffer);
        while (len != -1) {
            fout.write(buffer, 0, len);
            len = fin.read(buffer);
        }
        fin.close();
        fout.flush();
        fout.close();
        WebLogger.getLogger(formInfo.appName).i(t,
                "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName());
    } catch (IOException e) {
        WebLogger.getLogger(formInfo.appName).e(t,
                "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(formInfo.appName).e(t,
                "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (NoSuchPaddingException e) {
        WebLogger.getLogger(formInfo.appName).e(t,
                "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (InvalidKeyException e) {
        WebLogger.getLogger(formInfo.appName).e(t,
                "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (InvalidAlgorithmParameterException e) {
        WebLogger.getLogger(formInfo.appName).e(t,
                "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw 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;//from w ww  . j  ava2  s . 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.aperigeek.dropvault.web.dao.MongoFileService.java

protected File createDataFile(InputStream data, String username, char[] password) throws IOException {
    try {/*  w ww  . j av  a  2s  .  c om*/
        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:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void generateKey(KeyStore keyStore) throws SecureLocalStorageException {

    try {/* ww  w . ja v a 2  s  .  com*/
        _key = null;

        SecretKey key = KeyGenerator.getInstance("DES").generateKey();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            try {
                oos.writeObject(key);
            } finally {
                oos.close();
            }
        } finally {
            bos.close();
        }

        // store key encrypted with keystore key pair
        KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore
                .getEntry(SECURELOCALSTORAGEALIAS, null);

        Cipher input = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        input.init(Cipher.ENCRYPT_MODE, privateKeyEntry.getCertificate().getPublicKey());

        FileOutputStream fos = _cordova.getActivity().openFileOutput(SECURELOCALSTORAGEKEY,
                Context.MODE_PRIVATE);
        try {
            CipherOutputStream cipherOutputStream = new CipherOutputStream(fos, input);
            try {
                cipherOutputStream.write(bos.toByteArray());
            } finally {
                cipherOutputStream.close();
            }
        } finally {
            fos.close();
        }

    } catch (Exception e) {
        Log.e("SecureStorage", "Read", e);
        throw new SecureLocalStorageException("Error generating key", e);
    }
}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();/*  www  .  j a v a2 s.  co m*/
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}

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;//www.ja  v a2  s . c  om
    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.opendatakit.services.utilities.EncryptionUtils.java

private static void encryptIntoFile(String contents, File submissionFile, File encryptedFile,
        EncryptedFormInformation formInfo) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {

    // add elementSignatureSource for this file...
    formInfo.appendSubmissionFileSignatureSource(contents, submissionFile);

    try {/*from   w  w  w  .  j  a v a  2 s  .c o m*/
        Cipher c = formInfo.getCipher();

        OutputStream fout;
        fout = new FileOutputStream(encryptedFile);
        fout = new CipherOutputStream(fout, c);
        InputStream fin;
        fin = new ByteArrayInputStream(contents.getBytes(CharEncoding.UTF_8));
        byte[] buffer = new byte[2048];
        int len = fin.read(buffer);
        while (len != -1) {
            fout.write(buffer, 0, len);
            len = fin.read(buffer);
        }
        fin.close();
        fout.flush();
        fout.close();
        WebLogger.getLogger(formInfo.appName).i(t, "Encrpyted: content -> " + encryptedFile.getName());
    } catch (IOException e) {
        WebLogger.getLogger(formInfo.appName).e(t, "Error encrypting: content -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(formInfo.appName).e(t, "Error encrypting: content -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (NoSuchPaddingException e) {
        WebLogger.getLogger(formInfo.appName).e(t, "Error encrypting: content -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (InvalidKeyException e) {
        WebLogger.getLogger(formInfo.appName).e(t, "Error encrypting: content -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    } catch (InvalidAlgorithmParameterException e) {
        WebLogger.getLogger(formInfo.appName).e(t, "Error encrypting: content -> " + encryptedFile.getName());
        WebLogger.getLogger(formInfo.appName).printStackTrace(e);
        throw e;
    }
}

From source file:com.zacwolf.commons.crypto._CRYPTOfactory.java

public final void encryptToOutputStream(final byte[] bytes, final OutputStream outputStream)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, IOException {
    ready();/*from  w  w  w . j  a v a  2 s. com*/
    activecrypts++;
    try {
        final Cipher ecipher = crypter.getEcipher();
        final byte[] salt = ecipher.getIV();
        if (salt == null) {
            outputStream.write(0);
        } else {
            outputStream.write(salt.length);
            outputStream.write(salt);
        }
        outputStream.flush();
        CipherOutputStream cop = null;
        try {
            cop = new CipherOutputStream(outputStream, ecipher) {
                /*
                 * WebSphere 7 has a known bug with it's implementation of ibmjceprovider.jar
                 * concerning writing byte-arrays in a serialized object when the byte-array length
                 * is zero.
                 * see: http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14597510
                 * 
                 * Added an override of the CipherOutputStream write method so that it is only called when
                 * the byte array has length > 0
                 */
                @Override
                public void write(final byte[] b, final int off, final int len) throws IOException {
                    if (len > 0) {
                        super.write(b, off, len);
                        //super.flush(); Do NOT flush here, as it slows the process down exponentially
                    }
                }
            };
            cop.write(bytes);
            cop.flush();
        } finally {
            if (cop != null) {
                cop.flush();
                cop.close();
            }
            outputStream.flush();
            outputStream.close();
        }
    } finally {
        activecrypts--;
    }
}

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();// w w  w.  j  a v  a  2s  . c om
    // 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();
    }
}