Example usage for javax.crypto Cipher getIV

List of usage examples for javax.crypto Cipher getIV

Introduction

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

Prototype

public final byte[] getIV() 

Source Link

Document

Returns the initialization vector (IV) in a new buffer.

Usage

From source file:com.adaptris.security.password.AesCrypto.java

public String encode(String plainText, String charset) throws PasswordException {
    String result = null;/*from  w  w w  .j a  v  a 2s .com*/
    try {
        KeyGenerator kg = KeyGenerator.getInstance(ALG);
        kg.init(KEY_LEN, SecurityUtil.getSecureRandom());
        SecretKey sessionKey = kg.generateKey();
        Cipher dataCipher = Cipher.getInstance(CIPHER);
        dataCipher.init(Cipher.ENCRYPT_MODE, sessionKey);
        byte[] encryptedBody = dataCipher.doFinal(seed(plainText, charset));
        Output output = new Output();
        output.setSessionKey(sessionKey.getEncoded());
        output.setSessionVector(dataCipher.getIV());
        output.setEncryptedData(encryptedBody);
        result = Password.PORTABLE_PASSWORD + output.write();
    } catch (Exception e) {
        throw new PasswordException(e);
    }
    return result;
}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Add a saved password for a file/*www .j  a  v  a2s. c o m*/
 */
public void addSavedPassword(Uri fileUri, String password, Cipher cipher)
        throws UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
    byte[] enc = cipher.doFinal(password.getBytes("UTF-8"));
    String encStr = Base64.encodeToString(enc, Base64.NO_WRAP);
    String ivStr = Base64.encodeToString(cipher.getIV(), Base64.NO_WRAP);

    String keyName = getPrefsKey(fileUri);
    SharedPreferences prefs = getPrefs();
    prefs.edit().putString(keyName, encStr).putString(getIvPrefsKey(keyName), ivStr).apply();
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * ??//  w  w w. j a  v  a 2s.c  om
 * <dl>
 * <dt>?
 * <dd>AES??????
 * </dl>
 * @param key ?
 * @param plain 
 * @return {@link SecuredData ?}
 */
public SecuredData encrypt(final byte[] key, final byte[] plain) {
    try {
        final Cipher cipher = Cipher.getInstance(AES_TRANSFORM_NAME);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, AES_ALGO_NAME));
        try (final ByteArrayOutputStream bos = new ByteArrayOutputStream();) {
            bos.write(cipher.doFinal(plain));
            return new SecuredData(bos.toByteArray(), cipher.getIV());
        }
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException | IOException e) {
        throw new RuntimeException(e);
    }
}

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

public final byte[] encrypt(final byte[] bytes)
        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidAlgorithmParameterException {
    ready();/*  www  .  j a v a  2s.  c  om*/
    activecrypts++;
    try {
        final Cipher ecipher = this.crypter.getEcipher();
        byte[] salt = ecipher.getIV();
        final ByteBuffer outbuf = ByteBuffer
                .allocate(ecipher.getOutputSize(bytes.length) + (salt != null ? salt.length : 0) + 1);
        if (salt != null) {
            outbuf.put((byte) salt.length);
            outbuf.put(salt);
        } else
            outbuf.put((byte) 0);
        try {
            ecipher.doFinal(ByteBuffer.wrap(bytes), outbuf);
        } catch (ShortBufferException e) {
            // not going to happen since we specifically allocate based on the cipher output size
        }
        return outbuf.array();
    } finally {
        activecrypts--;
    }
}

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

public final void encryptObjToOutputStream(final Serializable obj, final OutputStream outputStream)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, IOException {
    if (outputStream instanceof ObjectOutputStream)
        throw new IOException(
                "encryptObjToOutputStream already wraps the outputStream in an ObjectOutputStream, so only pass-in a non-ObjectOutputStream wrapped stream");

    ready();//from ww  w  .  ja v a2  s  .co m
    activecrypts++;
    try {
        final Cipher ecipher = crypter.getEcipher();
        final byte[] salt = ecipher.getIV();
        if (salt == null) {
            outputStream.write(0);
        } else {
            outputStream.write(salt.length);
            for (byte s : salt)
                outputStream.write(s);
        }
        final CipherOutputStream cos = new CipherOutputStream(outputStream, ecipher) {
            /*
             * WebSphere 7 has a known bug with it's implementation of ibmjceprovider.jar
             * concerning writing byte-arrays in a serialized object when the byte-array length
             * is zero.
             * see: http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14597510
             * 
             * Added an override of the CipherOutputStream write method so that it is only called when
             * the byte array has length > 0
             */
            @Override
            public void write(final byte[] b, final int off, final int len) throws IOException {
                if (len > 0) {
                    super.write(b, off, len);
                    //super.flush();
                }
            }
        };
        final ObjectOutputStream oos = new ObjectOutputStream(cos);
        oos.writeObject(obj);
        oos.flush();
        oos.close();
    } finally {
        activecrypts--;
    }
}

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

public final void encryptToOutputStream(final byte[] bytes, final OutputStream outputStream)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, IOException {
    ready();//from   w ww  .j a v a2s  . c o  m
    activecrypts++;
    try {
        final Cipher ecipher = crypter.getEcipher();
        final byte[] salt = ecipher.getIV();
        if (salt == null) {
            outputStream.write(0);
        } else {
            outputStream.write(salt.length);
            outputStream.write(salt);
        }
        outputStream.flush();
        CipherOutputStream cop = null;
        try {
            cop = new CipherOutputStream(outputStream, ecipher) {
                /*
                 * WebSphere 7 has a known bug with it's implementation of ibmjceprovider.jar
                 * concerning writing byte-arrays in a serialized object when the byte-array length
                 * is zero.
                 * see: http://www.ibm.com/developerworks/forums/thread.jspa?messageID=14597510
                 * 
                 * Added an override of the CipherOutputStream write method so that it is only called when
                 * the byte array has length > 0
                 */
                @Override
                public void write(final byte[] b, final int off, final int len) throws IOException {
                    if (len > 0) {
                        super.write(b, off, len);
                        //super.flush(); Do NOT flush here, as it slows the process down exponentially
                    }
                }
            };
            cop.write(bytes);
            cop.flush();
        } finally {
            if (cop != null) {
                cop.flush();
                cop.close();
            }
            outputStream.flush();
            outputStream.close();
        }
    } finally {
        activecrypts--;
    }
}

From source file:com.evolveum.midpoint.prism.crypto.AESProtector.java

private byte[] encryptBytes(byte[] clearData, String algorithmUri, Key key)
        throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
    Cipher cipher = getCipher(Cipher.ENCRYPT_MODE, algorithmUri);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    byte[] encryptedData = cipher.doFinal(clearData);

    // Place IV at the beginning of the encrypted bytes so it can be reused on decryption
    byte[] iv = cipher.getIV();
    byte[] encryptedBytes = new byte[iv.length + encryptedData.length];
    System.arraycopy(iv, 0, encryptedBytes, 0, iv.length);
    System.arraycopy(encryptedData, 0, encryptedBytes, iv.length, encryptedData.length);

    return encryptedBytes;
}

From source file:org.nuxeo.ecm.core.blob.binary.AESBinaryManager.java

/**
 * Encrypts the given input stream into the given output stream, while also computing the digest of the input
 * stream.//from  w w  w . ja  va 2 s .  c  o m
 * <p>
 * File format version 1 (values are in network order):
 * <ul>
 * <li>10 bytes: magic number "NUXEOCRYPT"
 * <li>1 byte: file format version = 1
 * <li>1 byte: use keystore = 1, use PBKDF2 = 2
 * <li>if use PBKDF2:
 * <ul>
 * <li>4 bytes: salt length = n
 * <li>n bytes: salt data
 * </ul>
 * <li>4 bytes: IV length = p
 * <li>p bytes: IV data
 * <li>x bytes: encrypted stream
 * </ul>
 *
 * @param in the input stream containing the data
 * @param file the file containing the encrypted data
 * @return the digest of the input stream
 */
@Override
public String storeAndDigest(InputStream in, OutputStream out) throws IOException {
    out.write(FILE_MAGIC);
    DataOutputStream data = new DataOutputStream(out);
    data.writeByte(FILE_VERSION_1);

    try {
        // get digest to use
        MessageDigest messageDigest = MessageDigest.getInstance(digestAlgorithm);

        // secret key
        Key secret;
        if (usePBKDF2) {
            data.writeByte(USE_PBKDF2);
            // generate a salt
            byte[] salt = new byte[16];
            RANDOM.nextBytes(salt);
            // generate secret key
            secret = generateSecretKey(salt);
            // write salt
            data.writeInt(salt.length);
            data.write(salt);
        } else {
            data.writeByte(USE_KEYSTORE);
            // find secret key from keystore
            secret = getSecretKey();
        }

        // cipher
        Cipher cipher = Cipher.getInstance(AES_CBC_PKCS5_PADDING);
        cipher.init(Cipher.ENCRYPT_MODE, secret);

        // write IV
        byte[] iv = cipher.getIV();
        data.writeInt(iv.length);
        data.write(iv);

        // digest and write the encrypted data
        CipherAndDigestOutputStream cipherOut = new CipherAndDigestOutputStream(out, cipher, messageDigest);
        IOUtils.copy(in, cipherOut);
        cipherOut.close();
        byte[] digest = cipherOut.getDigest();
        return toHexString(digest);
    } catch (GeneralSecurityException e) {
        throw new NuxeoException(e);
    }

}

From source file:test.PBEncryptLink.java

/**
 * Initialize the Cipher object using the given key. If the Initialization
 * vaector has not already been stored (as an IvParameterSpec), then, for
 * encryption, one is created and stored. If the CipherMode is DECRYPT and
 * no initialization vector has been set, then an
 * InvalidAlgorithmParameterException is thrown.
 * /* ww w  . ja v a2 s  .c  om*/
 * @param key
 * @throws InvalidKeyException
 * @throws InvalidAlgorithmParameterException
 *             Hmm.
 */
public void initCipher(byte[] key) throws InvalidKeyException, InvalidAlgorithmParameterException {
    SecretKeySpec skeySpec = new SecretKeySpec(key, "Blowfish");
    Cipher cipher = getBlowfishCipher();
    IvParameterSpec ivs = getIvParmSpec();

    int intCipherMode = -1;
    switch (getCipherMode()) {
    case ENCRYPT:
        intCipherMode = Cipher.ENCRYPT_MODE;
        if (ivs == null) {

            cipher.init(intCipherMode, skeySpec);
            setIV(cipher.getIV());
        } else {
            cipher.init(intCipherMode, skeySpec, ivs);
        }
        break;
    case DECRYPT:
        intCipherMode = Cipher.DECRYPT_MODE;
        cipher.init(intCipherMode, skeySpec, ivs);
    default:
        break;
    }
    if (intCipherMode == -1) {
        return;
    }

}

From source file:de.schildbach.wallet.util.FingerprintHelper.java

@Nullable
@RequiresApi(api = Build.VERSION_CODES.M)
private Cipher createCipher(int mode) throws NoSuchPaddingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, InvalidKeyException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC
            + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);

    Key key = keyStore.getKey(KEYSTORE_ALIAS, null);
    if (key == null) {
        return null;
    }/*ww w .j a  v  a  2 s .  c  o m*/
    if (mode == Cipher.ENCRYPT_MODE) {
        cipher.init(mode, key);
        byte[] iv = cipher.getIV();
        saveIv(iv);
    } else {
        byte[] lastIv = getLastIv();
        cipher.init(mode, key, new IvParameterSpec(lastIv));
    }
    return cipher;
}