Example usage for javax.crypto Cipher update

List of usage examples for javax.crypto Cipher update

Introduction

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

Prototype

public final byte[] update(byte[] input, int inputOffset, int inputLen) 

Source Link

Document

Continues a multiple-part encryption or decryption operation (depending on how this cipher was initialized), processing another data part.

Usage

From source file:TripleDES.java

/**
 * Use the specified TripleDES key to decrypt bytes ready from the input
 * stream and write them to the output stream. This method uses uses Cipher
 * directly to show how it can be done without CipherInputStream and
 * CipherOutputStream./*from   ww  w .j  a  v a  2 s.c  o m*/
 */
public static void decrypt(SecretKey key, InputStream in, OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException,
        NoSuchPaddingException, BadPaddingException {
    // Create and initialize the decryption engine
    Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.DECRYPT_MODE, key);

    // Read bytes, decrypt, and write them out.
    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(cipher.update(buffer, 0, bytesRead));
    }

    // Write out the final bunch of decrypted bytes
    out.write(cipher.doFinal());
    out.flush();
}

From source file:com.hernandez.rey.crypto.TripleDES.java

/**
 * Use the specified TripleDES key to decrypt bytes ready from the input stream and write them to the output stream.
 * This method uses uses Cipher directly to show how it can be done without CipherInputStream and CipherOutputStream.
 * // w  w w  . j a v a2s .c  o m
 * @param key the key for decryption
 * @param in
 * @param out
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws IOException
 * @throws IllegalBlockSizeException
 * @throws NoSuchPaddingException
 * @throws BadPaddingException
 */
public static void decrypt(final SecretKey key, final InputStream in, final OutputStream out)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, IllegalBlockSizeException,
        NoSuchPaddingException, BadPaddingException {
    // Create and initialize the decryption engine
    final Cipher cipher = Cipher.getInstance("DESede");
    cipher.init(Cipher.DECRYPT_MODE, key);

    // Read bytes, decrypt, and write them out.
    final byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(cipher.update(buffer, 0, bytesRead));
    }

    // Write out the final bunch of decrypted bytes
    out.write(cipher.doFinal());
    out.flush();
}

From source file:org.apache.nifi.processors.standard.util.crypto.CipherUtility.java

public static void processStreams(Cipher cipher, InputStream in, OutputStream out) {
    try {/* w  w w  .  j av  a  2s .c  om*/
        final byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buffer)) > 0) {
            final byte[] decryptedBytes = cipher.update(buffer, 0, len);
            if (decryptedBytes != null) {
                out.write(decryptedBytes);
            }
        }

        out.write(cipher.doFinal());
    } catch (Exception e) {
        throw new ProcessException(e);
    }
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * KEY?/*from w  w  w  . ja va2s . c  om*/
 * 
 * @param schemaIndex
 * @param key
 *            ?,??????? ???DES DESede(TripleDES)
 *            DESedeWrap PBEWithMD5AndDES(OID.1.2.840.113549.1.5.3 
 *            1.2.840.113549.1.5.3) PBEWithMD5AndTripleDES
 *            PBEWithSHA1AndRC2_40(OID.1.2.840.113549.1.12.1.6 
 *            1.2.840.113549.1.12.1.6)
 *            PBEWithSHA1AndDESede(OID.1.2.840.113549
 *            .1.12.1.3,1.2.840.113549.1.12.1.3) Blowfish AES(Rijndael)
 *            AESWrap RC2 ARCFOUR(RC4) RSA RSA/ECB/PKCS1Padding RSA 15?
 * @return
 */
public static byte[] encrypt(InputStream in, Key key, AlgorithmParameterSpec spec, boolean padding) {
    Assert.notNull(key, "SecretKey Key must not null");
    String alg = (key instanceof RawSecretKeySpec) ? ((RawSecretKeySpec) key).chiperAlgomrithm
            : key.getAlgorithm();
    if (padding && alg.indexOf('/') == -1) {
        alg = alg + "/ECB/PKCS1Padding";
    }
    try {
        Cipher c1 = Cipher.getInstance(alg);
        c1.init(Cipher.ENCRYPT_MODE, key, spec);
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(c1.update(b, 0, len));
        }
        out.write(c1.doFinal());
        return out.toByteArray();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * KEY?//  w ww.  j  a v  a  2 s.c  om
 * 
 * @param schemaIndex
 * @param key
 *            ?.???????
 * @return AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
 *         iterationCount);
 */
public static byte[] decrypt(InputStream in, Key key, AlgorithmParameterSpec spec) {
    Assert.notNull(key, "SecretKey Key must not null");
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        Cipher c1 = Cipher
                .getInstance((key instanceof RawSecretKeySpec) ? ((RawSecretKeySpec) key).chiperAlgomrithm
                        : key.getAlgorithm());
        c1.init(Cipher.DECRYPT_MODE, key, spec);
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            out.write(c1.update(b, 0, len));
        }
        out.write(c1.doFinal());
        return out.toByteArray();
    } catch (GeneralSecurityException e) {
        LogUtil.exception(e);
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.kawanfw.commons.util.convert.Pbe.java

/**
 * Encrypt or decrypt a file using a password
 * //from w  w  w .j  av  a  2 s  .c  om
 * @param mode
 *            Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE
 * @param fileIn
 *            the file to encrypt or Decrypt.
 * @param fileOut
 *            the resulting encrypted/decrypted file
 * @param password
 *            the password to use
 * 
 * @throws Exception
 */
private void cipher(int mode, File fileIn, File fileOut, char[] password) throws Exception {
    if (mode != Cipher.ENCRYPT_MODE && mode != Cipher.DECRYPT_MODE) {
        throw new IllegalArgumentException("mode is not Cipher.ENCRYPT_MODE or Cipher.DECRYPT_MODE!");
    }

    if (fileIn == null) {
        throw new IllegalArgumentException("in File can not be null!");
    }

    if (fileOut == null) {
        throw new IllegalArgumentException("out File can not be null!");
    }

    if (password == null) {
        throw new IllegalArgumentException("password can not be null!");
    }

    PBEKeySpec pbeKeySpec;
    PBEParameterSpec pbeParamSpec;
    SecretKeyFactory keyFac;

    // Salt
    byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee,
            (byte) 0x99 };

    // Iteration count
    int count = 1;

    // Create PBE parameter set
    pbeParamSpec = new PBEParameterSpec(salt, count);

    pbeKeySpec = new PBEKeySpec(password);
    keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

    // Create PBE Cipher
    Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

    // Initialize PBE Cipher with key and parameters
    pbeCipher.init(mode, pbeKey, pbeParamSpec);

    InputStream in = null;
    OutputStream out = null;

    try {
        in = new BufferedInputStream(new FileInputStream(fileIn));
        out = new BufferedOutputStream(new FileOutputStream(fileOut));

        byte[] input = new byte[2048 * 10];
        int bytesRead;
        while ((bytesRead = in.read(input)) != -1) {
            byte[] output = pbeCipher.update(input, 0, bytesRead);
            if (output != null)
                out.write(output);
        }

        byte[] output = pbeCipher.doFinal();
        if (output != null)
            out.write(output);

        out.flush();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }

}

From source file:org.sejda.sambox.pdmodel.encryption.SecurityHandler.java

/**
 * Encrypt or decrypt data with AES with key length other than 256 bits.
 *
 * @param finalKey The final key obtained with via {@link #calcFinalKey()}.
 * @param data The data to encrypt./*from w  ww .ja  va2s . c  om*/
 * @param output The output to write the encrypted data to.
 *
 * @throws IOException If there is an error reading the data.
 */
private void decryptDataAESother(byte[] finalKey, InputStream data, OutputStream output) throws IOException {
    byte[] iv = new byte[16];

    int ivSize = data.read(iv);
    if (ivSize == -1) {
        return;
    }
    if (ivSize != iv.length) {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }

    try {
        Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

        SecretKey aesKey = new SecretKeySpec(finalKey, "AES");
        IvParameterSpec ips = new IvParameterSpec(iv);
        decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ips);
        byte[] buffer = new byte[256];
        int n;
        while ((n = data.read(buffer)) != -1) {
            byte[] update = decryptCipher.update(buffer, 0, n);
            if (update != null) {
                output.write(update);
            }
        }
        output.write(decryptCipher.doFinal());
    } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new IOException(e);
    }
}

From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java

/**
 *  ? ? close      . //w  ww .ja v  a 2  s . co m
 * @param in  
 * @param out  
 * @param isStreamClose close 
 * @throws NoSuchAlgorithmException  ? ?  ?  
 * @throws InvalidKeyException ?  ? key ?  
 * @throws IOException /  
 * @throws IllegalBlockSizeException ?  ? ? ?  
 * @throws NoSuchPaddingException   ?  ?  
 * @throws BadPaddingException ?  ? 
 * @throws InvalidKeySpecException ?  ? keySpec ?  
 * @throws InvalidAlgorithmParameterException  ?  ? ? 
 */
private void decrypt(InputStream in, OutputStream out, boolean isStreamClose) throws NoSuchAlgorithmException,
        InvalidKeyException, IOException, IllegalBlockSizeException, NoSuchPaddingException,
        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.DECRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec);
    } else {
        cipher.init(Cipher.DECRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()));
    }

    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(cipher.update(buffer, 0, bytesRead));
    }

    out.write(cipher.doFinal());
    out.flush();
    if (isStreamClose) {
        in.close();
        out.close();
    }
}

From source file:org.apache.pdfbox.pdmodel.encryption.SecurityHandler.java

/**
 * Encrypt or decrypt data with AES with key length other than 256 bits.
 *
 * @param finalKey The final key obtained with via {@link #calcFinalKey()}.
 * @param data The data to encrypt.//from  w w w .j a v  a 2s  . c  o m
 * @param output The output to write the encrypted data to.
 * @param decrypt true to decrypt the data, false to encrypt it.
 *
 * @throws IOException If there is an error reading the data.
 */
private void encryptDataAESother(byte[] finalKey, InputStream data, OutputStream output, boolean decrypt)
        throws IOException {
    byte[] iv = new byte[16];

    int ivSize = data.read(iv);
    if (ivSize != iv.length) {
        throw new IOException("AES initialization vector not fully read: only " + ivSize
                + " bytes read instead of " + iv.length);
    }

    try {
        Cipher decryptCipher;
        try {
            decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        } catch (NoSuchAlgorithmException e) {
            // should never happen
            throw new RuntimeException(e);
        }

        SecretKey aesKey = new SecretKeySpec(finalKey, "AES");
        IvParameterSpec ips = new IvParameterSpec(iv);
        decryptCipher.init(decrypt ? Cipher.DECRYPT_MODE : Cipher.ENCRYPT_MODE, aesKey, ips);
        byte[] buffer = new byte[256];
        int n;
        while ((n = data.read(buffer)) != -1) {
            output.write(decryptCipher.update(buffer, 0, n));
        }
        output.write(decryptCipher.doFinal());
    } catch (InvalidKeyException e) {
        throw new IOException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new IOException(e);
    } catch (NoSuchPaddingException e) {
        throw new IOException(e);
    } catch (IllegalBlockSizeException e) {
        throw new IOException(e);
    } catch (BadPaddingException e) {
        throw new IOException(e);
    }
}

From source file:org.apache.xml.security.encryption.XMLCipher.java

private EncryptedData encryptData(Document context, Element element, String type, InputStream serializedData)
        throws /* XMLEncryption */ Exception {
    contextDocument = context;/*from www  .java 2 s.c o m*/

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }

    String serializedOctets = null;
    if (serializedData == null) {
        if (type.equals(EncryptionConstants.TYPE_CONTENT)) {
            NodeList children = element.getChildNodes();
            if (null != children) {
                serializedOctets = serializer.serialize(children);
            } else {
                Object exArgs[] = { "Element has no content." };
                throw new XMLEncryptionException("empty", exArgs);
            }
        } else {
            serializedOctets = serializer.serialize(element);
        }
        if (log.isDebugEnabled()) {
            log.debug("Serialized octets:\n" + serializedOctets);
        }
    }

    byte[] encryptedBytes = null;

    // Now create the working cipher if none was created already
    Cipher c;
    if (contextCipher == null) {
        String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
        if (log.isDebugEnabled()) {
            log.debug("alg = " + jceAlgorithm);
        }

        try {
            if (requestedJCEProvider == null) {
                c = Cipher.getInstance(jceAlgorithm);
            } else {
                c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
            }
        } catch (NoSuchAlgorithmException nsae) {
            throw new XMLEncryptionException("empty", nsae);
        } catch (NoSuchProviderException nspre) {
            throw new XMLEncryptionException("empty", nspre);
        } catch (NoSuchPaddingException nspae) {
            throw new XMLEncryptionException("empty", nspae);
        }
    } else {
        c = contextCipher;
    }
    // Now perform the encryption

    try {
        // Should internally generate an IV
        // todo - allow user to set an IV
        c.init(cipherMode, key);
    } catch (InvalidKeyException ike) {
        throw new XMLEncryptionException("empty", ike);
    }

    try {
        if (serializedData != null) {
            int numBytes;
            byte[] buf = new byte[8192];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((numBytes = serializedData.read(buf)) != -1) {
                byte[] data = c.update(buf, 0, numBytes);
                baos.write(data);
            }
            baos.write(c.doFinal());
            encryptedBytes = baos.toByteArray();
        } else {
            encryptedBytes = c.doFinal(serializedOctets.getBytes("UTF-8"));
            if (log.isDebugEnabled()) {
                log.debug("Expected cipher.outputSize = "
                        + Integer.toString(c.getOutputSize(serializedOctets.getBytes("UTF-8").length)));
            }
        }
        if (log.isDebugEnabled()) {
            log.debug("Actual cipher.outputSize = " + Integer.toString(encryptedBytes.length));
        }
    } catch (IllegalStateException ise) {
        throw new XMLEncryptionException("empty", ise);
    } catch (IllegalBlockSizeException ibse) {
        throw new XMLEncryptionException("empty", ibse);
    } catch (BadPaddingException bpe) {
        throw new XMLEncryptionException("empty", bpe);
    } catch (UnsupportedEncodingException uee) {
        throw new XMLEncryptionException("empty", uee);
    }

    // Now build up to a properly XML Encryption encoded octet stream
    // IvParameterSpec iv;
    byte[] iv = c.getIV();
    byte[] finalEncryptedBytes = new byte[iv.length + encryptedBytes.length];
    System.arraycopy(iv, 0, finalEncryptedBytes, 0, iv.length);
    System.arraycopy(encryptedBytes, 0, finalEncryptedBytes, iv.length, encryptedBytes.length);
    String base64EncodedEncryptedOctets = Base64.encode(finalEncryptedBytes);

    if (log.isDebugEnabled()) {
        log.debug("Encrypted octets:\n" + base64EncodedEncryptedOctets);
        log.debug("Encrypted octets length = " + base64EncodedEncryptedOctets.length());
    }

    try {
        CipherData cd = ed.getCipherData();
        CipherValue cv = cd.getCipherValue();
        // cv.setValue(base64EncodedEncryptedOctets.getBytes());
        cv.setValue(base64EncodedEncryptedOctets);

        if (type != null) {
            ed.setType(new URI(type).toString());
        }
        EncryptionMethod method = factory.newEncryptionMethod(new URI(algorithm).toString());
        ed.setEncryptionMethod(method);
    } catch (URISyntaxException ex) {
        throw new XMLEncryptionException("empty", ex);
    }
    return ed;
}