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:de.schildbach.wallet.util.FingerprintHelper.java

private String decipher(Cipher cipher) throws IOException {
    String retVal = null;//w  w w .  j  a v  a2s. c  om
    String savedEncryptedPassword = getSavedEncryptedPassword();
    if (savedEncryptedPassword != null) {
        byte[] decodedPassword = decodeBytes(savedEncryptedPassword);
        CipherInputStream cipherInputStream = new CipherInputStream(new ByteArrayInputStream(decodedPassword),
                cipher);

        ArrayList<Byte> values = new ArrayList<>();
        int nextByte;
        while ((nextByte = cipherInputStream.read()) != -1) {
            values.add((byte) nextByte);
        }
        cipherInputStream.close();

        byte[] bytes = new byte[values.size()];
        for (int i = 0; i < values.size(); i++) {
            bytes[i] = values.get(i).byteValue();
        }

        retVal = new String(bytes, Charset.defaultCharset());
    }
    return retVal;
}

From source file:jfs.sync.encryption.JFSEncryptedStream.java

/**
 * //from w  ww . ja v a  2  s .c o  m
 * @param fis
 * @param expectedLength
 *            length to be expected or -2 if you don't want the check
 * @param cipher
 * @return
 */
public static InputStream createInputStream(InputStream fis, long expectedLength, Cipher cipher) {
    try {
        InputStream in = fis;
        ObjectInputStream ois = new ObjectInputStream(in);
        byte marker = readMarker(ois);
        long l = readLength(ois);
        if (log.isDebugEnabled()) {
            log.debug(
                    "JFSEncryptedStream.createInputStream() length check " + expectedLength + " == " + l + "?");
        } // if
        if (expectedLength != DONT_CHECK_LENGTH) {
            if (l != expectedLength) {
                log.error("JFSEncryptedStream.createInputStream() length check failed");
                return null;
            } // if
        } // if
        if (cipher == null) {
            log.error("JFSEncryptedStream.createInputStream() no cipher for length " + expectedLength);
        } else {
            in = new CipherInputStream(in, cipher);
        } // if
        if (marker == COMPRESSION_DEFLATE) {
            Inflater inflater = new Inflater(true);
            in = new InflaterInputStream(in, inflater, COMPRESSION_BUFFER_SIZE);
        } // if
        if (marker == COMPRESSION_BZIP2) {
            in = new BZip2CompressorInputStream(in);
        } // if
        if (marker == COMPRESSION_LZMA) {
            Decoder decoder = new Decoder();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] properties = new byte[5];
            int readBytes = in.read(properties, 0, properties.length);
            boolean result = decoder.SetDecoderProperties(properties);
            if (log.isDebugEnabled()) {
                log.debug("JFSEncryptedStream.createInputStream() readBytes=" + readBytes);
                log.debug("JFSEncryptedStream.createInputStream() result=" + result);
            } // if

            decoder.Code(in, outputStream, l);
            in.close();
            outputStream.close();
            if (log.isDebugEnabled()) {
                log.debug("JFSEncryptedStream.createInputStream() " + outputStream.size());
            } // if
            in = new ByteArrayInputStream(outputStream.toByteArray());
        } // if
        return in;
    } catch (IOException ioe) {
        log.error("JFSEncryptedStream.createInputStream() I/O Exception " + ioe.getLocalizedMessage());
        return null;
    } // try/catch
}

From source file:org.yes.cart.web.support.util.cookie.impl.CookieTuplizerImpl.java

/**
 * {@inheritDoc}//from ww  w  . j  a v  a2 s .co m
 */
@SuppressWarnings("unchecked")
public <T extends Serializable> T toObject(Cookie[] cookies, final T object)
        throws UnableToObjectizeCookieException {
    final String input = assembleStringRespresentationOfObjectFromCookies(cookies, object);
    if (input.length() == 0) {
        return object;
    }
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(input.getBytes());
    final BASE64DecoderStream base64DecoderStream = new BASE64DecoderStream(byteArrayInputStream);
    final CipherInputStream cipherInputStream = new CipherInputStream(base64DecoderStream, desUnCipher);
    ObjectInputStream objectInputStream = null;
    try {
        objectInputStream = new ObjectInputStream(cipherInputStream);
        return (T) objectInputStream.readObject();

    } catch (Exception exception) {
        try {
            desUnCipher.init(Cipher.DECRYPT_MODE, secretKey); //reinit
        } catch (InvalidKeyException e) {
            ShopCodeContext.getLog(this).error("Cant reinit desUnCipher", exception);
        }
        final String errMsg = "Unable to convert bytes assembled from cookies into object";
        ShopCodeContext.getLog(this).error(errMsg, exception);
        throw new UnableToObjectizeCookieException(errMsg, exception);
    } finally {
        try {
            if (objectInputStream != null) {
                objectInputStream.close();
            }
            cipherInputStream.close();
            base64DecoderStream.close();
            byteArrayInputStream.close();
        } catch (IOException ioe) { // leave this one silent as we have the object on hands.
            ShopCodeContext.getLog(this).error("Unable to close object stream", ioe);
        }

    }
}

From source file:org.jets3t.service.security.EncryptionUtil.java

/**
 * Wraps an input stream in an encrypting cipher stream.
 *
 * @param is//from w  w  w  . j ava  2 s  .  c  o  m
 * @return
 * encrypting cipher input stream.
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 */
public CipherInputStream encrypt(InputStream is) throws InvalidKeyException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, NoSuchPaddingException {
    Cipher cipher = initEncryptModeCipher();
    return new CipherInputStream(is, cipher);
}

From source file:net.jmhertlein.core.crypto.Keys.java

/**
 * Given a secret key and an input stream, wraps the input stream first in a CipherInputStream using the given secret key, then in an ObjectInputStream
 *
 * @param key the secret key to use to encrypt data with
 * @param is  the input stream to encrypt and wrap
 *
 * @return an ObjectInputStream whose data will be encrypted with the secret key
 * @throws NoSuchAlgorithmException/*  w  w w  .j av a2 s  . c o m*/
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws IOException
 */
public static ObjectInputStream getEncryptedObjectInputStream(SecretKey key, InputStream is)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IOException {
    Cipher inCipher = Cipher.getInstance("AES/CFB8/NoPadding");
    inCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(getKeyBytes(key)));

    return new ObjectInputStream(new CipherInputStream(is, inCipher));
}

From source file:org.jets3t.service.security.EncryptionUtil.java

/**
 * Wraps an input stream in an decrypting cipher stream.
 *
 * @param is/*  ww  w.  ja v  a 2s . c o  m*/
 * @return
 * decrypting cipher input stream.
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 */
public CipherInputStream decrypt(InputStream is) throws InvalidKeyException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, NoSuchPaddingException {
    Cipher cipher = initDecryptModeCipher();
    return new CipherInputStream(is, cipher);
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private SecretKey getSecretKey(KeyStore keyStore) throws NoSuchAlgorithmException, UnrecoverableEntryException,
        KeyStoreException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IOException,
        ClassNotFoundException {//  w w  w  .j a  v  a  2s.  c o m

    if (_key != null) {
        return _key;
    }

    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keyStore
            .getEntry(SECURELOCALSTORAGEALIAS, null);

    SecretKey key;

    FileInputStream fis = _cordova.getActivity().openFileInput(SECURELOCALSTORAGEKEY);
    try {

        Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());

        CipherInputStream cipherInputStream = new CipherInputStream(fis, output);
        try {

            ObjectInputStream ois = new ObjectInputStream(cipherInputStream);

            key = (SecretKey) ois.readObject();

        } finally {
            cipherInputStream.close();
        }
    } finally {
        fis.close();
    }

    // store key for the lifetime for the app
    _key = key;
    return key;
}

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

public final byte[] decryptFromInputStream(final InputStream is) throws IOException, InvalidKeyException,
        InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
    ready();//ww  w. j  av a2s .  c  o m
    activecrypts++;
    try {
        final int saltsize = is.read();
        final byte[] salt;
        if (saltsize > 0) {
            salt = new byte[saltsize];
            is.read(salt);
        } else
            salt = null;
        final CipherInputStream cip = new CipherInputStream(is, crypter.getDcipher(salt));
        try {
            return IOUtils.toByteArray(cip);
        } finally {
            try {
                is.close();
            } catch (final Exception e) {
            }

        }
    } finally {
        activecrypts--;
    }
}

From source file:com.aperigeek.dropvault.web.dao.MongoFileService.java

protected InputStream readFile(File file, String username, char[] password) throws IOException {
    try {/*from   w  w w . jav a2 s  .com*/
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream fIn = new BufferedInputStream(new FileInputStream(file));

        Cipher cipher = Cipher.getInstance("Blowfish");
        cipher.init(Cipher.DECRYPT_MODE, getSecretKey(username, password));

        CipherInputStream in = new CipherInputStream(fIn, cipher);

        return in;
    } catch (Exception ex) {
        // TODO: better exception handling
        Logger.getAnonymousLogger().log(Level.SEVERE, "ERROR", ex);
        throw new RuntimeException(ex);
    }
}

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;/*w w w .ja va  2s. 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
    // }
    //
}