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.zuinnote.hadoop.office.format.common.parser.msexcel.internal.EncryptedCachedDiskStringsTable.java

/**
 * Reads from the original Excel document the string table and puts it into a
 * compressed and encrypted file./*from  w  ww  .  j  a  va2s  .c  o m*/
 * 
 * @param is
 * @throws java.io.IOException
 */

@Override
public void readFrom(InputStream is) throws IOException {
    this.currentItem = 0;
    // read from source and write into tempfile
    // open temp file depending on options compressed/encrypted
    OutputStream tempOS = null;
    if ((this.ca != null) || (this.compressTempFile)) {
        tempOS = new FileOutputStream(this.tempFile);
        if (this.ca != null) { // encrypt file if configured
            tempOS = new CipherOutputStream(tempOS, this.ciEncrypt);
        }
        if (this.compressTempFile) { // compress file if configured
            tempOS = new GZIPOutputStream(tempOS, EncryptedCachedDiskStringsTable.compressBufferSize);
        }
    } else { // not encrypted and not compressed: configure a random access file for
             // writing/reading = highest performance
        this.tempRAF = new RandomAccessFile(this.tempFile, "rw");
    }
    // read from source
    // use Stax event reader
    XMLEventReader xer = null;
    try {
        xer = StaxHelper.newXMLInputFactory().createXMLEventReader(this.originalIS);
        while (xer.hasNext()) {
            XMLEvent xe = xer.nextEvent();
            // check if it is a string item (entry in string table)
            if (xe.isStartElement() && xe.asStartElement().getName().getLocalPart().equalsIgnoreCase("si")) {
                String siText = this.parseSIText(xer);
                // add string to temp file
                this.addString(siText, tempOS);
                this.count++;
            }
        }
        // close tempfile
        // make tempFile available as a reader
    } catch (XMLStreamException e) {
        LOG.error("Cannot read original SharedStringTable from document. Exception " + e);
        throw new IOException(e);
    } catch (FormatNotUnderstoodException e) {
        LOG.error("Cannot read properly SharedStringTable from document. Exception " + e);
        throw new IOException(e);
    } finally {
        // close temporary Stream (tempfile should be deleted using the close method of
        // this class and not here)
        if (tempOS != null) {
            tempOS.close();
        }
    }
    // open the input stream towards the temp file
    this.accessTempFile(0L);

}

From source file:at.tfr.securefs.xnio.MessageHandlerImpl.java

@Override
public void handleMessage(String json, MessageSender messageSender) throws IOException {

    log.debug("handleMessage: " + json);
    final Message message = objectMapper.readValue(json, Message.class);

    Path path = configuration.getBasePath().resolve(message.getPath());
    if (!path.relativize(configuration.getBasePath()).toString().equals("..")) {
        throw new SecurityException("invalid path spec: " + message.getPath());
    }/*  w  ww. ja  va  2 s. c  om*/

    try {
        final String uniqueKey = message.getUniqueKey();
        // find the Channel for this data stream:
        StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>> info = activeStreams.getStreams()
                .get(uniqueKey);

        if (message.getType() == MessageType.OPEN && info != null) {
            log.warn("illegal state on Open stream: " + message);
            IoUtils.safeClose(info.getStream().getRightSide());
            messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
        }

        switch (message.getType()) {
        case ERROR:
            log.info("error from Client: " + json);
        case CLOSE: {
            if (info != null) {
                IoUtils.safeClose(info.getStream().getRightSide());
            }
        }
            break;

        case OPEN: {
            switch (message.getSubType()) {
            case READ: {
                final InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
                final InputStream cis = new CipherInputStream(is, getCipher(message, Cipher.DECRYPT_MODE));

                final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker
                        .createHalfDuplexPipe();
                pipe.getLeftSide().getReadSetter().set(new SecureChannelWriterBase(message) {
                    @Override
                    protected void write(Message message) {
                        try {
                            messageSender.send(message);
                        } catch (Exception e) {
                            log.warn("cannot write message=" + message + " : " + e, e);
                        }
                    }
                });
                pipe.getLeftSide().getCloseSetter().set(new ChannelListener<StreamSourceChannel>() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        activeStreams.getStreams().remove(uniqueKey);
                        messageSender.send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                    }
                });
                pipe.getRightSide().getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {
                    private byte[] bytes = new byte[Constants.BUFFER_SIZE];

                    @Override
                    public void handleEvent(StreamSinkChannel channel) {
                        try {
                            int count = 0;
                            while ((count = cis.read(bytes, 0, bytes.length)) > 0) {
                                if (count > 0) {
                                    Channels.writeBlocking(pipe.getRightSide(),
                                            ByteBuffer.wrap(bytes, 0, count));
                                }
                                if (count < 0) {
                                    pipe.getRightSide().close();
                                } else {
                                    channel.resumeWrites();
                                }
                            }
                        } catch (Exception e) {
                            log.warn("cannot read from cypher: " + e, e);
                            IoUtils.safeClose(channel);
                        }
                    }
                });

                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start sending data:
                pipe.getLeftSide().resumeReads();
                pipe.getRightSide().resumeWrites();
            }
                break;

            case WRITE: {
                Files.createDirectories(path.getParent());
                OutputStream os = Files.newOutputStream(path, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                OutputStream cos = new CipherOutputStream(os, getCipher(message, Cipher.ENCRYPT_MODE));

                ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker.createHalfDuplexPipe();

                pipe.getLeftSide().getReadSetter().set(new SecureChannelReaderBase() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        readChannel(message, cos, pipe, channel);
                    }
                });

                pipe.getLeftSide().getCloseSetter().set(new SecureChannelReaderBase() {
                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        try {
                            cos.close();
                            activeStreams.getStreams().remove(pipe.toString());
                            messageSender
                                    .send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                            log.info("closed channel: " + pipe.toString());
                        } catch (IOException e) {
                            log.warn("cannot close stream: message=" + message + " : " + e, e);
                        }
                    }
                });
                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start receiving data:
                pipe.getLeftSide().resumeReads();
            }
                break;

            default:
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
                break;

            }
        }
            break;

        case DATA: {
            if (info != null) {
                Channels.writeBlocking(info.getStream().getRightSide(), ByteBuffer.wrap(message.getBytes()));
            } else {
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
            }
        }
            break;
        }

    } catch (IOException e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw e;
    } catch (Exception e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw new IOException("cannot handle message: " + message + " : " + e, e);
    }
}

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

/**
 * the decrypted output stream/*w w  w.  j ava 2s .co m*/
 * @param out
 * @return the decrypted output stream
 */
public OutputStream decrypt(OutputStream out) {
    this.initCipher(false);
    return new CipherOutputStream(out, this.cipher);
}

From source file:org.codice.ddf.configuration.migration.MigrationZipFileTest.java

private void createZipWithEncryptedContents(Path zipPath, Path keyPath, Path checksumPath) throws Exception {
    Cipher cipher = createEncryptionCipher(keyPath);
    ZipEntry zipEntry = new ZipEntry("foo");
    ZipEntry zipEntry1 = new ZipEntry("baz");
    ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipPath.toFile()));
    zipOutputStream.putNextEntry(zipEntry);
    IOUtils.write("bar", new CipherOutputStream(zipOutputStream, cipher), StandardCharsets.UTF_8);
    zipOutputStream.closeEntry();//from   ww  w .  ja v  a  2s. co  m
    zipOutputStream.putNextEntry(zipEntry1);
    IOUtils.write("qux", new CipherOutputStream(zipOutputStream, cipher), StandardCharsets.UTF_8);
    zipOutputStream.closeEntry();
    zipOutputStream.close();
    createChecksum(zipPath, checksumPath);
}

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);// w  w w. j  a  v a 2s.co 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: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 ww.ja v a  2s  .com*/
        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.yes.cart.web.support.util.cookie.impl.CookieTuplizerImpl.java

/**
 * {@inheritDoc}/*from www.ja  v  a2  s . c  o  m*/
 */
public Cookie[] toCookies(final Cookie[] oldCookies, final Serializable serializable)
        throws UnableToCookielizeObjectException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    synchronized (desCipher) {
        BASE64EncoderStream base64EncoderStream = new BASE64EncoderStream(byteArrayOutputStream,
                Integer.MAX_VALUE); //will be splited manually
        CipherOutputStream cipherOutputStream = new CipherOutputStream(base64EncoderStream, desCipher);
        ObjectOutputStream objectOutputStream = null;
        try {
            objectOutputStream = new ObjectOutputStream(cipherOutputStream);
            objectOutputStream.writeObject(serializable);
            objectOutputStream.flush();
            objectOutputStream.close();
        } catch (Throwable ioe) {
            ShopCodeContext.getLog(this)
                    .error(MessageFormat.format("Unable to serialize object {0}", serializable), ioe);
            throw new UnableToCookielizeObjectException(ioe);
        } finally {
            try {
                if (objectOutputStream != null) {
                    objectOutputStream.close();
                }
                cipherOutputStream.close();
                base64EncoderStream.close();
                byteArrayOutputStream.close();
            } catch (IOException e) {
                ShopCodeContext.getLog(this).error("Can not close stream", e);
            }
        }
    }
    return assembleCookiesForObject(oldCookies, split(byteArrayOutputStream.toString()), serializable);
}

From source file:org.slc.sli.bulk.extract.files.ExtractFile.java

private OutputStream getAppStream(String app) throws Exception {
    File archive = new File(parentDir, getFileName(app));
    OutputStream f = null;/* www. ja  va  2s  .c  o  m*/

    try {
        f = new BufferedOutputStream(new FileOutputStream(archive));
        createTarFile(archive);

        archiveFiles.put(app, archive);

        final Pair<Cipher, SecretKey> cipherSecretKeyPair = getCiphers();

        byte[] ivBytes = cipherSecretKeyPair.getLeft().getIV();
        byte[] secretBytes = cipherSecretKeyPair.getRight().getEncoded();

        PublicKey publicKey = getApplicationPublicKey(app);
        byte[] encryptedIV = encryptDataWithRSAPublicKey(ivBytes, publicKey);
        byte[] encryptedSecret = encryptDataWithRSAPublicKey(secretBytes, publicKey);

        f.write(encryptedIV);
        f.write(encryptedSecret);

        return new CipherOutputStream(f, cipherSecretKeyPair.getLeft());
    } catch (Exception e) {
        IOUtils.closeQuietly(f);
        throw e;
    }
}

From source file:com.microsoft.azure.storage.blob.BlobEncryptionPolicy.java

/**
 * Return a reference to a {@link OutputStream} given a user stream. This method is used for decrypting blobs.
 * @param userProvidedStream/*from w  w w .  j  ava2  s  . c  o  m*/
 *          The output stream provided by the user.
 * @param metadata
 *          Reference to blob metadata object that is used to get the encryption materials.
 * @param requireEncryption
 *          A value to indicate that the data read from the server should be encrypted.
 * @param iv
 *          The iv to use if pre-buffered. Used only for range reads.
 * @param noPadding
 *          Value indicating if the padding mode should be set or not.
 * @return A reference to a {@link OutputStream} that will be written to.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
OutputStream decryptBlob(OutputStream userProvidedStream, Map<String, String> metadata,
        Boolean requireEncryption, byte[] iv, boolean noPadding) throws StorageException {
    Utility.assertNotNull("metadata", metadata);

    // If encryption policy is set but the encryption metadata is absent, throw
    // an exception.
    String encryptionDataString = metadata.get("encryptiondata");
    if (requireEncryption != null && requireEncryption && encryptionDataString == null) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                SR.ENCRYPTION_DATA_NOT_PRESENT_ERROR, null);
    }

    try {
        if (encryptionDataString != null) {
            BlobEncryptionData encryptionData = BlobEncryptionData.deserialize(encryptionDataString);

            Utility.assertNotNull("encryptionData", encryptionData);
            Utility.assertNotNull("contentEncryptionIV", encryptionData.getContentEncryptionIV());
            Utility.assertNotNull("encryptedKey", encryptionData.getWrappedContentKey().getEncryptedKey());

            // Throw if the encryption protocol on the message doesn't match the version that this client library understands
            // and is able to decrypt.
            if (!Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1
                    .equals(encryptionData.getEncryptionAgent().getProtocol())) {
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.ENCRYPTION_PROTOCOL_VERSION_INVALID, null);
            }

            // Throw if neither the key nor the key resolver are set.
            if (this.keyWrapper == null && this.keyResolver == null) {
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.KEY_AND_RESOLVER_MISSING, null);
            }

            byte[] contentEncryptionKey = null;

            // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
            // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
            // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
            // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
            // locally. No service call is made.
            if (this.keyResolver != null) {
                IKey keyEncryptionKey = this.keyResolver
                        .resolveKeyAsync(encryptionData.getWrappedContentKey().getKeyId()).get();

                Utility.assertNotNull("keyEncryptionKey", keyEncryptionKey);
                contentEncryptionKey = keyEncryptionKey
                        .unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
                                encryptionData.getWrappedContentKey().getAlgorithm())
                        .get();
            } else {
                if (encryptionData.getWrappedContentKey().getKeyId().equals(this.keyWrapper.getKid())) {
                    contentEncryptionKey = this.keyWrapper
                            .unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
                                    encryptionData.getWrappedContentKey().getAlgorithm())
                            .get();
                } else {
                    throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.KEY_MISMATCH, null);
                }
            }

            switch (encryptionData.getEncryptionAgent().getEncryptionAlgorithm()) {
            case AES_CBC_256:

                Cipher myAes;
                if (noPadding) {
                    myAes = Cipher.getInstance("AES/CBC/NoPadding");
                } else {
                    myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
                }

                IvParameterSpec ivParameterSpec = new IvParameterSpec(
                        iv != null ? iv : encryptionData.getContentEncryptionIV());
                SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length,
                        "AES");
                myAes.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);

                return new CipherOutputStream(userProvidedStream, myAes);

            default:
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.INVALID_ENCRYPTION_ALGORITHM, null);
            }
        } else {
            return userProvidedStream;
        }
    } catch (StorageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.DECRYPTION_LOGIC_ERROR, ex);
    }
}

From source file:org.nuclos.client.LocalUserCaches.java

public void store() {
    try {//w  w w  .  ja v  a 2  s .c o m
        final BufferedOutputStream out;

        if (bUseEncryption) {
            out = new BufferedOutputStream(new CipherOutputStream(new FileOutputStream(this.getCachesFile()),
                    createCipher(Cipher.ENCRYPT_MODE,
                            SecurityDelegate.getInstance().getCurrentApplicationInfoOnServer())));
        } else {
            out = new BufferedOutputStream(new FileOutputStream(this.getCachesFile()));
        }

        try {
            storeObject(MetaDataClientProvider.getInstance());
            storeObject(AttributeCache.getInstance());
            storeObject(ResourceCache.getInstance());
            storeObject(GenericObjectMetaDataCache.getInstance());
            storeObject(MasterDataCache.getInstance());
            storeObject(MetaDataCache.getInstance());
            storeObject(GenericObjectLayoutCache.getInstance());
            //storeObject(SearchFilterCache.getInstance());
            storeObject(CustomComponentCache.getInstance());
            storeObject(ClientParameterProvider.getInstance());
            storeObject(LocaleDelegate.getInstance());
            storeObject(TasklistCache.getInstance());
            storeObject(StateDelegate.getInstance());
            storeObject(RuleCache.getInstance());

            put(LOCALUSERCACHES_APP_VERSION,
                    ApplicationProperties.getInstance().getCurrentVersion().getSchemaVersion());
            store(out, ApplicationProperties.getInstance().getAppId() + " Local User Caches");
        } finally {
            out.close();
        }

        if (bUseHashing) {
            // get sha hash.
            LocalUserProperties.getInstance().put(LOCALUSERCACHES_HASH, getHash());
            LocalUserProperties.getInstance().store();
        }
    } catch (GeneralSecurityException e) {
        final String sMessage = "Lokale Caches konnten nicht gespeichert werden: " + e;
        LOG.error(sMessage, e);
    } catch (IOException e) {
        final String sMessage = "Lokale Caches konnten nicht gespeichert werden: " + e;
        LOG.error(sMessage, e);
    } catch (Exception ex) {
        final String sMessage = "Lokale Caches konnten nicht gespeichert werden: " + ex;
        LOG.error(sMessage, ex);
    }
}