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.apache.synapse.securevault.BaseCipher.java

/**
 * Do cryptographic operation// ww  w.j a v a  2 s . com
 *
 * @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:com.hernandez.rey.crypto.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 w w. j av a  2s .  c o  m
 * @param key the key to use for encryption
 * @param in the input stream to encrypt
 * @param out the encrypted output stream
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws NoSuchPaddingException
 * @throws IOException
 */
public static void encrypt(final SecretKey key, final InputStream in, final OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException {
    // Create and initialize the encryption engine
    final Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key);

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

    // Read from the input and write to the encrypting output stream
    final 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);
}

From source file:hudson.console.AnnotatedLargeText.java

public long writeHtmlTo(long start, Writer w) throws IOException {
    ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream(w,
            createAnnotator(Stapler.getCurrentRequest()), context, charset);
    long r = super.writeLogTo(start, caw);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Cipher sym = PASSING_ANNOTATOR.encrypt();
    ObjectOutputStream oos = new ObjectOutputStream(new GZIPOutputStream(new CipherOutputStream(baos, sym)));
    oos.writeLong(System.currentTimeMillis()); // send timestamp to prevent a replay attack
    oos.writeObject(caw.getConsoleAnnotator());
    oos.close();/*from   w  w w  . j a v a2 s .  com*/
    StaplerResponse rsp = Stapler.getCurrentResponse();
    if (rsp != null)
        rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray())));
    return r;
}

From source file:sec_algo.commonenc.java

public void encryptFile() {
    File encrypted = new File("demo2\\" + returnFileName() + "_encrypted." + returnFileExt());
    byte[] temp, result;
    try {// w  w  w .j a  v a  2  s.  c  om
        FileInputStream in = new FileInputStream(file);
        //            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        //            byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        //            IvParameterSpec ivspec = new IvParameterSpec(iv);
        aesCipher.init(Cipher.ENCRYPT_MODE, secretkey);
        CipherOutputStream os = new CipherOutputStream(new FileOutputStream(encrypted), aesCipher);

        long startTime = System.currentTimeMillis();
        copy(in, os);
        long endTime = System.currentTimeMillis();
        System.out.println("startTime - " + startTime);
        System.out.println("endTime - " + endTime);
        encryptTime = endTime - startTime;

        in.close();
        os.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:hudson.cli.Connection.java

/**
 * Upgrades a connection with transport encryption by the specified symmetric cipher.
 *
 * @return/*from   w  w  w .  j  a v  a  2  s.  c  o  m*/
 *      A new {@link Connection} object that includes the transport encryption.
 */
public Connection encryptConnection(SecretKey sessionKey, String algorithm)
        throws IOException, GeneralSecurityException {
    Cipher cout = Cipher.getInstance(algorithm);
    cout.init(Cipher.ENCRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
    CipherOutputStream o = new CipherOutputStream(out, cout);

    Cipher cin = Cipher.getInstance(algorithm);
    cin.init(Cipher.DECRYPT_MODE, sessionKey, new IvParameterSpec(sessionKey.getEncoded()));
    CipherInputStream i = new CipherInputStream(in, cin);

    return new Connection(i, o);
}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Encrypts a file.//from   w  w w. j a va 2 s . c o m
 * 
 * @param path
 *          path of the original file.
 * @param context
 *          context to fetch preferences.
 * @param encryptPath
 *          path of the encrypted file.
 */
public long encryptFile(final String path, final String encryptPath, final Context context) {
    long empty = 123456789L;
    Date d1 = new Date();
    // Transaction.checkLongRunningProcessing("encryptFile");
    //System.err.println("Path = "+path);
    //System.err.println("encryptPath = "+encryptPath);
    try {
        //System.err.println("EN - 1");
        // Here you read the cleartext.
        final FileInputStream fis = new FileInputStream(path);
        // This stream write the encrypted text. This stream will be wrapped by another stream.
        final FileOutputStream fos = new FileOutputStream(encryptPath);

        final OutputStream outputStream;
        if (ENCRYPTION_ENABLED) {
            //System.err.println("EN - 2");
            final SecretKeySpec secret = usedSecretKey = getSecretKey(context);
            final byte[] ivBytes = usedIV = getIV(context);
            ivspec = new IvParameterSpec(ivBytes);
            //System.err.println("EN - 3");
            // Create cipher
            final Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secret, ivspec);
            //System.err.println("EN - 4");
            // Wrap the output stream
            outputStream = new CipherOutputStream(fos, cipher);
            //System.err.println("EN - 5");
        } else {
            outputStream = fos;
        }

        // Write bytes
        int b;
        //System.err.println("EN - 6");
        final byte[] d = new byte[BUFFER_SIZE];
        while ((b = fis.read(d)) != -1) {
            outputStream.write(d, 0, b);
        }
        //System.err.println("EN - 7");
        // Flush and close streams.
        outputStream.flush();
        outputStream.close();
        fis.close();

        //System.err.println("EN - 8");
        Date d2 = new Date();
        long diff = d2.getTime() - d1.getTime();
        long diffSeconds = diff / 1000 % 60;
        System.err.println("File encrypted SUCCESSFULLY. Time = " + diffSeconds);
        return diffSeconds;
        //decryptFile(encryptPath, encryptPath+"_decrypted", null);
    } catch (final Exception e) {
        Log.e(TAG, "e" + e);
        return empty;
    }
}

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);// w w w  .ja  v a2s .co  m
    cos.flush();
    cos.close();
    byte[] byteArray = bos.toByteArray();
    return byteArray;
}

From source file:edu.ncsu.asbransc.mouflon.recorder.UploadFile.java

protected void doUpload() {
    DbAdapter dba = new DbAdapter(this);
    dba.open();//from w  w  w  . j  a  v  a 2 s .com
    Cursor allLogs = dba.fetchAll();
    StringBuilder sb = new StringBuilder();
    allLogs.moveToFirst();
    sb.append("DateTime");
    sb.append(",");
    sb.append("Process");
    sb.append(",");
    sb.append("Type");
    sb.append(",");
    sb.append("Component");
    sb.append(",");
    sb.append("ActionString");
    sb.append(",");
    sb.append("Category");
    sb.append("\n");
    while (!allLogs.isAfterLast()) {
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_TIME)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_PROCESSTAG)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_1)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_2)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_3)));
        sb.append(",");
        sb.append(allLogs.getString(allLogs.getColumnIndex(DbAdapter.KEY_EXTRA_4)));
        sb.append("\n");
        allLogs.moveToNext();
    }
    dba.close();
    File appDir = getDir("toUpload", MODE_PRIVATE);
    UUID uuid;
    uuid = MainScreen.getOrCreateUUID(this);
    long time = System.currentTimeMillis();
    String basename = uuid.toString() + "_AT_" + time;
    String filename = basename + ".zip.enc";
    File file = new File(appDir, filename);
    FileOutputStream out = null;
    ZipOutputStream outzip = null;
    CipherOutputStream outcipher = null;
    Cipher datac = null;

    File keyfile = new File(appDir, basename + ".key.enc");
    //Log.i("sb length", Integer.toString(sb.length()));
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    String email = prefs.getString(MainScreen.EMAIL_KEY, "");
    String emailFilename = "email.txt";
    String csvFilename = "mouflon_log_" + time + ".csv";
    try {
        SecretKey aeskey = generateAESKey();
        //Log.i("secret key", bytearrToString(aeskey.getEncoded()));
        encryptAndWriteAESKey(aeskey, keyfile);
        datac = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        byte[] ivbytes = genIV();
        IvParameterSpec iv = new IvParameterSpec(ivbytes);
        datac.init(Cipher.ENCRYPT_MODE, aeskey, iv);
        out = new FileOutputStream(file);
        out.write(ivbytes);
        //Log.i("iv bytes", bytearrToString(ivbytes));
        outcipher = new CipherOutputStream(out, datac);
        outzip = new ZipOutputStream(outcipher);
        outzip.setMethod(ZipOutputStream.DEFLATED);
        //write the first file (e-mail address)
        String androidVersion = android.os.Build.VERSION.RELEASE;
        String deviceName = android.os.Build.MODEL;
        ZipEntry infoEntry = new ZipEntry("info.txt");
        outzip.putNextEntry(infoEntry);
        outzip.write((androidVersion + "\n" + deviceName).getBytes());
        outzip.closeEntry();
        ZipEntry emailEntry = new ZipEntry(emailFilename);
        outzip.putNextEntry(emailEntry);
        outzip.write(email.getBytes());
        outzip.closeEntry();
        ZipEntry csvEntry = new ZipEntry(csvFilename);
        outzip.putNextEntry(csvEntry);
        outzip.write(sb.toString().getBytes());
        outzip.closeEntry();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outzip.close();
            outcipher.close();
            out.close();
        } catch (IOException e) {
            //ignore
        } catch (NullPointerException ne) {
            //ignore
        }
    }
    //here we actually upload the files 
    String containerFilename = basename + "_container.zip";
    File containerFile = new File(appDir, containerFilename);
    zipUp(containerFile, new File[] { file, keyfile });
    boolean success = uploadFile(containerFile);
    containerFile.delete();
    file.delete();
    keyfile.delete();
    if (success && prefs.getBoolean(MainScreen.DELETE_KEY, true)) {
        DbAdapter dba2 = new DbAdapter(this);
        dba2.open();
        dba2.clearDB();
        dba2.close();
    }
    if (!success && prefs.getBoolean(MainScreen.UPLOAD_KEY, false)) {
        Editor e = prefs.edit();
        e.putInt(MainScreen.DAY_KEY, 6); //reset it to run tomorrow if it fails
        e.commit();
    }
    String s = success ? "Upload complete. Thanks!" : "Upload Failed";
    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(UploadFile.this)
            .setSmallIcon(R.drawable.ic_launcher_bw).setContentTitle("Mouflon Recorder").setContentText(s)
            .setAutoCancel(true).setOngoing(false);

    if (mManual) { //only show a notification if we manually upload the file.
        Intent toLaunch = new Intent(UploadFile.this, MainScreen.class);
        //The notification has to go somewhere.
        PendingIntent pi = PendingIntent.getActivity(UploadFile.this, 0, toLaunch,
                PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(pi);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(1, mBuilder.build());
    }
    stopSelf();
}

From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java

@SuppressWarnings("resource")
public void run() {

    SingletonForSSFMP info = null;/*from  w ww.  j  av a 2s  .co  m*/
    SingletonForSSFMP2 info2 = null;
    SingletonForSSFMP3 info3 = null;

    switch (abs) {
    case 0:
        info = SingletonForSSFMP.getInstance();
        break;
    case 1:
        info2 = SingletonForSSFMP2.getInstance();
        break;
    case 2:
        info3 = SingletonForSSFMP3.getInstance();
        break;
    default:
        //info = SingletonForMyStreamer.getInstance();
        break;
    }

    int seqTsEnc = 0; //info.getSeqTsEnc();
    if (!modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsEnc();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsEnc();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsEnc();
        }
    } else if (modeLive.equals("capturedTimeShifted")) {
        if ((abs == 0) && (info != null)) {
            seqTsEnc = info.getSeqTsCapturedTimeShifted();
        } else if ((abs == 1) && (info2 != null)) {
            seqTsEnc = info2.getSeqTsCapturedTimeShifted();
        } else if ((abs == 2) && (info3 != null)) {
            seqTsEnc = info3.getSeqTsCapturedTimeShifted();
        }
    }

    if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
        seqTsEnc = info.getSeqTsLast();
    } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
        seqTsEnc = info2.getSeqTsLast();
    } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
        seqTsEnc = info3.getSeqTsLast();
    }

    log.debug(MARKER_Encrypter, "{} Begin : Encryption of seqTsEnc : {}",
            Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

    Key sKey;
    Cipher c;
    FileOutputStream keyOut;
    FileWriter ivOut;
    FileInputStream fis;
    BufferedInputStream bis;
    FileOutputStream fos;
    CipherOutputStream cos;

    try {

        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

        sKey = makeKey(128); // Key length is 128bit
        c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        //         log.debug(MARKER_Encrypter, "{} [c.getAlgorithm()] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), c.getAlgorithm());
        c.init(Cipher.ENCRYPT_MODE, sKey);

        // Set Key File Name at random
        String keyPre = RandomStringUtils.randomAlphabetic(10);
        keyOut = new FileOutputStream(streamPath + FILE_SEPARATOR + keyPre + seqTsEnc + ".key");

        if ((abs == 0) && (info != null)) {
            info.addKeyArrayList(keyPre);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addKeyArrayList(keyPre);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addKeyArrayList(keyPre);
        }

        byte[] keyOutByte = sKey.getEncoded();
        keyOut.write(keyOutByte);
        keyOut.close();

        byte[] iv = c.getIV();
        //         log.debug(MARKER_Encrypter, "{} [iv.length] {} [byte]", Thread.currentThread().getStackTrace()[1].getMethodName(), iv.length);

        String ivHex = "";
        for (int i = 0; i < iv.length; i++) {
            String ivHexTmp = String.format("%02x", iv[i]).toUpperCase();
            ivHex = ivHex + ivHexTmp;
        }

        String ivPre = RandomStringUtils.randomAlphabetic(10);
        ivOut = new FileWriter(streamPath + FILE_SEPARATOR + ivPre + seqTsEnc + ".iv");
        ivOut.write(ivHex);
        ivOut.close();

        //         log.debug(MARKER_Encrypter, "{} [iv] {}", Thread.currentThread().getStackTrace()[1].getMethodName(), ivHex);

        if ((abs == 0) && (info != null)) {
            info.addIvArrayList(ivHex);
        } else if ((abs == 1) && (info2 != null)) {
            info2.addIvArrayList(ivHex);
        } else if ((abs == 2) && (info3 != null)) {
            info3.addIvArrayList(ivHex);
        }

        fis = new FileInputStream(TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequence" + seqTsEnc + ".ts");
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
        cos = new CipherOutputStream(fos, c);
        if (modeLive.equals("capturedTimeShifted")) {
            fis = new FileInputStream(
                    TEMP_PATH_FOR_ENC + FILE_SEPARATOR + "fileSequenceEncoded" + seqTsEnc + ".ts");
            bis = new BufferedInputStream(fis);
            fos = new FileOutputStream(streamPath + FILE_SEPARATOR + "fileSequenceEnc" + seqTsEnc + ".ts");
            cos = new CipherOutputStream(fos, c);
        }

        byte[] buf = new byte[TS_PACKET_LENGTH];

        int ch;
        while ((ch = bis.read(buf)) != -1) {
            cos.write(buf, 0, ch);
        }
        cos.close();
        fos.close();
        bis.close();
        fis.close();

        log.debug(MARKER_Encrypter, "{} End : Encryption of seqTsEnc : {}",
                Thread.currentThread().getStackTrace()[1].getMethodName(), seqTsEnc);

        if ((abs == 0) && (info != null) && info.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 1) && (info2 != null) && info2.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        } else if ((abs == 2) && (info3 != null) && info3.getFlagLastTs()) {
            log.debug(MARKER_Encrypter, "{} ALL ENCRYPTION FINISHED!!! {}",
                    Thread.currentThread().getStackTrace()[1].getMethodName(), abs);
        }

    } catch (NoSuchProviderException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } // try
}

From source file:org.openTwoFactor.clientExt.edu.internet2.middleware.morphString.Crypto.java

/**
 * the encrypted output stream//ww  w  .  j  a v  a2  s  .  c om
 * @param out
 * @return the encrypted output stream
 */
public OutputStream encrypt(OutputStream out) {
    this.initCipher(true);
    return new CipherOutputStream(out, this.cipher);
}