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.camel.converter.crypto.CryptoDataFormat.java

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

    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);
        }
    }
}

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./*ww  w .  java2s  . co  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.jenkinsci.plugins.fabric8.support.hack.AnnotatedLargeText.java

public long writeHtmlTo(long start, Writer w) throws IOException {
    ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream(w,
            this.createAnnotator(Stapler.getCurrentRequest()), this.context, this.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());
    oos.writeObject(caw.getConsoleAnnotator());
    oos.close();/*w  w  w.  j a  v a  2s . c o  m*/
    StaplerResponse rsp = Stapler.getCurrentResponse();
    if (rsp != null) {
        rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray())));
    }
    return r;
}

From source file:jfs.sync.meta.AbstractMetaStorageAccess.java

/**
 * flushing listing as meta data info for pathAndName[0] in rootPath
 *
 * @param rootPath/* w w w  .  ja  va 2  s .co m*/
 * @param pathAndName
 * path and name for the file and path for which this update takes place
 * @param listing
 */
public void flushMetaData(String rootPath, String[] pathAndName, Map<String, FileInfo> listing) {
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("flushMetaData() flushing " + listing);
        } // if
        OutputStream os = getOutputStream(rootPath, getMetaDataPath(pathAndName[0]), false);

        try {
            byte[] credentials = getCredentials(pathAndName[0]);
            Cipher cipher = SecurityUtils.getCipher(getCipherSpec(), Cipher.ENCRYPT_MODE, credentials);
            os = new CipherOutputStream(os, cipher);
        } catch (InvalidKeyException e) {
            LOG.error("flushMetaData()", e);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("flushMetaData()", e);
        } catch (NoSuchPaddingException e) {
            LOG.error("flushMetaData()", e);
        } // try/catch

        ObjectOutputStream oos = new ObjectOutputStream(os);

        for (FileInfo info : listing.values()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("flushMetaData() writing " + info.getName());
            } // if
            oos.writeObject(info);
        } // for
        oos.flush();
        os.close();
        if (LOG.isDebugEnabled()) {
            Map<String, FileInfo> backtest = getMetaData(rootPath, pathAndName[0]);
            for (FileInfo info : backtest.values()) {
                LOG.debug("flushMetaData() reading " + info.getName());
            } // for
        } // if
    } catch (IOException ioe) {
        LOG.error("flushMetaData() error writing meta data ", ioe);
    } // try/catch
}

From source file:uploadProcess.java

public static boolean decrypt(File inputFolder, String fileName, String patientID) {
    try {/*from www  .  j  av a2  s.  c o  m*/
        //Download File from Cloud..
        DropboxUpload download = new DropboxUpload();
        download.downloadFile(fileName, StoragePath.getDropboxDir() + patientID, inputFolder);

        String ukey = GetKey.getPatientKey(patientID);
        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;
    } catch (Exception e) {
        System.out.println("Error: " + e);
    }
    return false;
}

From source file:org.structr.cloud.CloudConnection.java

@Override
public void start() {

    // setup read and write threads for the connection
    if (socket.isConnected() && !socket.isClosed()) {

        try {/* w w  w . jav  a  2  s . com*/

            decrypter = Cipher.getInstance(CloudService.STREAM_CIPHER);
            encrypter = Cipher.getInstance(CloudService.STREAM_CIPHER);

            // this key is only used for the first two packets
            // of a transmission, it is replaced by the users
            // password hash afterwards.
            setEncryptionKey("StructrInitialEncryptionKey", 128);

            sender = new Sender(this, new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(
                    new CipherOutputStream(socket.getOutputStream(), encrypter), 32768, true))));
            receiver = new Receiver(this, new DataInputStream(new BufferedInputStream(
                    new GZIPInputStream(new CipherInputStream(socket.getInputStream(), decrypter), 32768))));

            receiver.start();
            sender.start();

            // start actual thread
            super.start();

        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

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

public static byte[] encryptSymmetricKey(byte[] symKey, PublicKey pKey) throws SymmetricKeyEncryptionException {
    try {//from   w  w  w  .  ja v a  2s  . 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:org.jenkinsci.plugins.fabric8.support.hack.AnnotatedLargeText.java

@Override
public long writeLogTo(long start, int size, Writer w) throws IOException {
    if (isHtml()) {
        ConsoleAnnotationOutputStream caw = new ConsoleAnnotationOutputStream(w,
                this.createAnnotator(Stapler.getCurrentRequest()), this.context, this.charset);
        long r = super.writeLogTo(start, size, caw);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Cipher sym = PASSING_ANNOTATOR.encrypt();
        ObjectOutputStream oos = new ObjectOutputStream(
                new GZIPOutputStream(new CipherOutputStream(baos, sym)));
        oos.writeLong(System.currentTimeMillis());
        oos.writeObject(caw.getConsoleAnnotator());
        oos.close();/*from  w ww.  j a v a 2 s . co  m*/
        StaplerResponse rsp = Stapler.getCurrentResponse();
        if (rsp != null) {
            rsp.setHeader("X-ConsoleAnnotator", new String(Base64.encode(baos.toByteArray())));
        }
        return r;
    } else {
        return super.writeLogTo(start, size, w);
    }
}

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.//w  w w .  j a va 2  s .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:com.csipsimple.backup.SipProfileJson.java

/**
 * Save current sip configuration//from  w  ww  .  jav a  2  s  .  c o  m
 * 
 * @param ctxt
 * @return
 */
public static boolean saveSipConfiguration(Context ctxt, String filePassword) {
    File dir = PreferencesWrapper.getConfigFolder(ctxt);
    if (dir != null) {
        Date d = new Date();
        File file = new File(dir.getAbsoluteFile() + File.separator + "backup_"
                + DateFormat.format("yy-MM-dd_kkmmss", d) + ".json");
        Log.d(THIS_FILE, "Out dir " + file.getAbsolutePath());

        JSONObject configChain = new JSONObject();
        try {
            configChain.put(KEY_ACCOUNTS, serializeSipProfiles(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }
        try {
            configChain.put(KEY_SETTINGS, serializeSipSettings(ctxt));
        } catch (JSONException e) {
            Log.e(THIS_FILE, "Impossible to add profiles", e);
        }

        try {
            // Create file
            OutputStream fos = new FileOutputStream(file);
            if (!TextUtils.isEmpty(filePassword)) {
                Cipher c;
                try {
                    c = Cipher.getInstance("AES");
                    SecretKeySpec k = new SecretKeySpec(filePassword.getBytes(), "AES");
                    c.init(Cipher.ENCRYPT_MODE, k);
                    fos = new CipherOutputStream(fos, c);
                } catch (NoSuchAlgorithmException e) {
                    Log.e(THIS_FILE, "NoSuchAlgorithmException :: ", e);
                } catch (NoSuchPaddingException e) {
                    Log.e(THIS_FILE, "NoSuchPaddingException :: ", e);
                } catch (InvalidKeyException e) {
                    Log.e(THIS_FILE, "InvalidKeyException :: ", e);
                }
            }
            FileWriter fstream = new FileWriter(file.getAbsoluteFile());
            BufferedWriter out = new BufferedWriter(fstream);
            out.write(configChain.toString(2));
            // Close the output stream
            out.close();
            return true;
        } catch (Exception e) {
            // Catch exception if any
            Log.e(THIS_FILE, "Impossible to save config to disk", e);
            return false;
        }
    }
    return false;
}