Example usage for javax.crypto CipherInputStream CipherInputStream

List of usage examples for javax.crypto CipherInputStream CipherInputStream

Introduction

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

Prototype

public CipherInputStream(InputStream is, Cipher c) 

Source Link

Document

Constructs a CipherInputStream from an InputStream and a Cipher.

Usage

From source file:models.logic.CipherDecipher.java

public static void encryptOrDecrypt(SecretKey key, int mode, InputStream is, OutputStream os) throws Throwable {
    Cipher cipher = Cipher.getInstance("AES");
    if (mode == Cipher.ENCRYPT_MODE) {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        CipherInputStream cis = new CipherInputStream(is, cipher);
        doCopy(cis, os);/* w  w w.  j a v a 2s  .c  o  m*/
    } else if (mode == Cipher.DECRYPT_MODE) {
        cipher.init(Cipher.DECRYPT_MODE, key);
        CipherOutputStream cos = new CipherOutputStream(os, cipher);
        doCopy(is, cos);
    }
}

From source file:bobs.is.compress.sevenzip.AES256SHA256Decoder.java

@Override
InputStream decode(final String archiveName, final InputStream in, final long uncompressedLength,
        final Coder coder, final byte[] passwordBytes) throws IOException {
    return new InputStream() {
        private boolean isInitialized = false;
        private CipherInputStream cipherInputStream = null;

        private CipherInputStream init() throws IOException {
            if (isInitialized) {
                return cipherInputStream;
            }//from   ww w .  j a v  a  2  s  .  co  m
            final int byte0 = 0xff & coder.properties[0];
            final int numCyclesPower = byte0 & 0x3f;
            final int byte1 = 0xff & coder.properties[1];
            final int ivSize = ((byte0 >> 6) & 1) + (byte1 & 0x0f);
            final int saltSize = ((byte0 >> 7) & 1) + (byte1 >> 4);
            if (2 + saltSize + ivSize > coder.properties.length) {
                throw new IOException("Salt size + IV size too long in " + archiveName);
            }
            final byte[] salt = new byte[saltSize];
            System.arraycopy(coder.properties, 2, salt, 0, saltSize);
            final byte[] iv = new byte[16];
            System.arraycopy(coder.properties, 2 + saltSize, iv, 0, ivSize);

            if (passwordBytes == null) {
                throw new PasswordRequiredException(archiveName);
            }
            final byte[] aesKeyBytes;
            if (numCyclesPower == 0x3f) {
                aesKeyBytes = new byte[32];
                System.arraycopy(salt, 0, aesKeyBytes, 0, saltSize);
                System.arraycopy(passwordBytes, 0, aesKeyBytes, saltSize,
                        Math.min(passwordBytes.length, aesKeyBytes.length - saltSize));
            } else {
                final MessageDigest digest;
                try {
                    digest = MessageDigest.getInstance("SHA-256");
                } catch (final NoSuchAlgorithmException noSuchAlgorithmException) {
                    throw new IOException("SHA-256 is unsupported by your Java implementation",
                            noSuchAlgorithmException);
                }
                final byte[] extra = new byte[8];
                for (long j = 0; j < (1L << numCyclesPower); j++) {
                    digest.update(salt);
                    digest.update(passwordBytes);
                    digest.update(extra);
                    for (int k = 0; k < extra.length; k++) {
                        ++extra[k];
                        if (extra[k] != 0) {
                            break;
                        }
                    }
                }
                aesKeyBytes = digest.digest();
            }

            final SecretKey aesKey = new SecretKeySpec(aesKeyBytes, "AES");
            try {
                final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
                cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
                cipherInputStream = new CipherInputStream(in, cipher);
                isInitialized = true;
                return cipherInputStream;
            } catch (final GeneralSecurityException generalSecurityException) {
                throw new IOException("Decryption error "
                        + "(do you have the JCE Unlimited Strength Jurisdiction Policy Files installed?)",
                        generalSecurityException);
            }
        }

        @Override
        public int read() throws IOException {
            return init().read();
        }

        @Override
        public int read(final byte[] b, final int off, final int len) throws IOException {
            return init().read(b, off, len);
        }

        @Override
        public void close() {
        }
    };
}

From source file:corner.util.crypto.Cryptor.java

/**
 * ?IO?.IO?,.// w  w  w.j  a va  2  s .co  m
 * @param inputFileName ????.
 * @param keyFile ??.
 * @return ?IO?.
 */
public static InputStream dencryptFileIO(String inputFileName, String keyFile) {
    if (keyFile == null) {
        try {
            return new FileInputStream(new File(inputFileName));
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    SecretKey key = null;

    ObjectInputStream keyis;
    try {
        keyis = new ObjectInputStream(new FileInputStream(keyFile));
        key = (SecretKey) keyis.readObject();

        keyis.close();
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

    //keyCipher
    Cipher cipher = null;

    try {
        //,
        cipher = Cipher.getInstance("DES");
        // ?
        cipher.init(Cipher.DECRYPT_MODE, key);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }

    File file = new File(inputFileName);

    try {

        //?
        CipherInputStream in = new CipherInputStream(new BufferedInputStream(new FileInputStream(file)),
                cipher);
        return in;

    } catch (Exception e) {
        throw new RuntimeException(e);

    }

}

From source file:hudson.console.AnnotatedLargeText.java

private ConsoleAnnotator createAnnotator(StaplerRequest req) throws IOException {
    try {//from w  ww  . j av  a2s  . com
        String base64 = req != null ? req.getHeader("X-ConsoleAnnotator") : null;
        if (base64 != null) {
            Cipher sym = PASSING_ANNOTATOR.decrypt();

            ObjectInputStream ois = new ObjectInputStreamEx(
                    new GZIPInputStream(new CipherInputStream(
                            new ByteArrayInputStream(Base64.decode(base64.toCharArray())), sym)),
                    Jenkins.getInstance().pluginManager.uberClassLoader);
            try {
                long timestamp = ois.readLong();
                if (TimeUnit2.HOURS.toMillis(1) > abs(System.currentTimeMillis() - timestamp))
                    // don't deserialize something too old to prevent a replay attack
                    return (ConsoleAnnotator) ois.readObject();
            } finally {
                ois.close();
            }
        }
    } catch (ClassNotFoundException e) {
        throw new IOException(e);
    }
    // start from scratch
    return ConsoleAnnotator.initial(context == null ? null : context.getClass());
}

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());
    }/*from w w  w.j a v  a2 s  .  c o  m*/

    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:com.dc.util.file.FileSupport.java

private static void copyEncryptedStream(InputStream input, OutputStream output, String key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
    Cipher dcipher = Cipher.getInstance("AES");
    CipherInputStream cis = null;
    try {//from   w  w  w  .j  av a2s .co  m
        dcipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key.getBytes(), "AES"));
        cis = new CipherInputStream(input, dcipher);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = cis.read(buffer)) != -1) {
            output.write(buffer, 0, bytesRead);
        }
        output.flush();
    } finally {
        if (cis != null) {
            cis.close();
        }
    }
}

From source file:com.doplgangr.secrecy.FileSystem.File.java

public java.io.File readFile(CryptStateListener listener) {
    decrypting = true;//from   w  ww .ja  va2s .  c om
    InputStream is = null;
    OutputStream out = null;
    java.io.File outputFile = null;
    try {
        outputFile = java.io.File.createTempFile("tmp" + name, "." + FileType, storage.getTempFolder());
        outputFile.mkdirs();
        outputFile.createNewFile();
        AES_Encryptor enc = new AES_Encryptor(key);
        is = new CipherInputStream(new FileInputStream(file), enc.decryptstream());
        listener.setMax((int) file.length());
        ReadableByteChannel inChannel = Channels.newChannel(is);
        FileChannel outChannel = new FileOutputStream(outputFile).getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(Config.bufferSize);
        while (inChannel.read(byteBuffer) >= 0 || byteBuffer.position() > 0) {
            byteBuffer.flip();
            outChannel.write(byteBuffer);
            byteBuffer.compact();
            listener.updateProgress((int) outChannel.size());
        }
        inChannel.close();
        outChannel.close();
        Util.log(outputFile.getName(), outputFile.length());
        return outputFile;
    } catch (FileNotFoundException e) {
        listener.onFailed(2);
        Util.log("Encrypted File is missing", e.getMessage());
    } catch (IOException e) {
        Util.log("IO Exception while decrypting", e.getMessage());
        if (e.getMessage().contains("pad block corrupted"))
            listener.onFailed(1);
        else
            e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        listener.Finished();
        decrypting = false;
        try {
            if (is != null) {
                is.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // An error occured. Too Bad
    if (outputFile != null)
        storage.purgeFile(outputFile);
    return null;
}

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

LocalUserCaches() {
    try {//w ww .j a  va 2 s .  com
        InputStream in = null;
        try {
            if (bUseHashing && !LangUtils.equals(LocalUserProperties.getInstance().get(LOCALUSERCACHES_HASH),
                    getHash())) {
                LOG.info("hash missmatch. skipping.");
            } else {
                if (bUseEncryption)
                    in = new BufferedInputStream(new CipherInputStream(
                            new FileInputStream(this.getCachesFile()), createCipher(Cipher.DECRYPT_MODE,
                                    SecurityDelegate.getInstance().getCurrentApplicationInfoOnServer())));
                else
                    in = new BufferedInputStream(new FileInputStream(this.getCachesFile()));
                load(in);

                // compare current version
                if (!LangUtils.equals(
                        ApplicationProperties.getInstance().getCurrentVersion().getSchemaVersion(),
                        get(LOCALUSERCACHES_APP_VERSION))) {
                    LOG.info("version missmatch. skipping.");
                    clear();
                }
            }
        } catch (FileNotFoundException ex) {
            // The properties file doesn't exist. or other exception...
            // So we start with empty or default values.
        } catch (GeneralSecurityException ex) {
            // other exception... just log and start with empty or default values.
            LOG.warn("Lokale Caches konnten nicht geladen werden: " + ex.getMessage());
        } catch (IllegalArgumentException ex) {
            // other exception... just log and start with empty or default values.
            LOG.warn("Lokale Caches konnten nicht geladen werden: " + ex.getMessage());
        } catch (Exception ex) {
            // other exception... just log and start with empty or default values.
            LOG.error("Lokale Caches konnten nicht geladen werden: " + ex.getMessage(), ex);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    } catch (IOException e) {
        final String sMessage = "Lokale Caches konnten nicht geladen werden: " + e.getMessage();
        throw new NuclosFatalException(sMessage, e);
    }
    INSTANCE = this;
}

From source file:de.marius_oe.cfs.cryption.Crypter.java

/**
 * Encrypts the given input stream and stores the encrypted data in the
 * destinationFile.//from w w w.ja va 2  s . com
 *
 * @param inStream
 *            plain text stream
 * @param destinationStream
 *            stream for the encrypted data
 * @param compressStream
 *            whether the data should be compressed before encryption
 */
public static void encrypt(InputStream inStream, OutputStream destinationStream, boolean compressStream) {
    logger.debug("encrypting inputstream - compressed: {}", compressStream);

    InputStream tempInputStream;

    if (compressStream) {
        logger.debug("Compress InputStream.");
        tempInputStream = StreamUtils.zipStream(inStream);
    } else {
        tempInputStream = inStream;
    }

    Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, null);

    logger.debug("Encrypt InputStream.");
    tempInputStream = new CipherInputStream(tempInputStream, cipher);

    try {
        // write iv to the beginning of the stream
        destinationStream.write((byte) cipher.getIV().length);
        destinationStream.write(cipher.getIV());

        int bytesCopied = IOUtils.copy(tempInputStream, destinationStream);

        logger.debug("encryption done. copied {} encrypted bytes to the outputstream", bytesCopied);

        tempInputStream.close();
        destinationStream.close();
    } catch (IOException e) {
        logger.error("Encryption failed - Reason: {}", e.getLocalizedMessage());
        throw new RuntimeException(e);
    }
}

From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java

/**
 * Method that will be called to process the summary collection file. The upload process will unpack the zipped collection of summary files and then
 * decrypt them./*  www .j a v a2s  .c  o m*/
 *
 * @throws Exception
 */
protected void processSummaries() throws Exception {
    String zipFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ZIP), ".");
    String encryptedFilename = StringUtils.join(Arrays.asList(filename, TaskConstants.FILE_TYPE_ENCRYPTED),
            ".");

    File file = new File(TaskUtils.getZippedOutputPath(), zipFilename);
    OutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
    ZipFile encryptedFile = new ZipFile(new File(TaskUtils.getEncryptedOutputPath(), encryptedFilename));

    Enumeration<? extends ZipEntry> entries = encryptedFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry zipEntry = entries.nextElement();
        String zipEntryName = zipEntry.getName();
        if (!zipEntryName.endsWith(TaskConstants.FILE_TYPE_SAMPLE)
                && !zipEntryName.endsWith(TaskConstants.FILE_TYPE_SECRET)) {
            int count;
            byte[] data = new byte[TaskConstants.BUFFER_SIZE];
            CipherInputStream zipCipherInputStream = new CipherInputStream(
                    encryptedFile.getInputStream(zipEntry), cipher);
            while ((count = zipCipherInputStream.read(data, 0, TaskConstants.BUFFER_SIZE)) != -1) {
                outStream.write(data, 0, count);
            }
            zipCipherInputStream.close();
        }
    }
    outStream.close();

    File outputPath = TaskUtils.getSummaryOutputPath();
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
    while (zipEntries.hasMoreElements()) {
        ZipEntry zipEntry = zipEntries.nextElement();
        processedFilename = zipEntry.getName();
        File f = new File(outputPath, zipEntry.getName());
        // ensure that the parent path exists
        File parent = f.getParentFile();
        if (parent.exists() || parent.mkdirs()) {
            FileCopyUtils.copy(zipFile.getInputStream(zipEntry),
                    new BufferedOutputStream(new FileOutputStream(f)));
        }
    }
}