Example usage for javax.crypto.spec IvParameterSpec IvParameterSpec

List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec

Introduction

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

Prototype

public IvParameterSpec(byte[] iv) 

Source Link

Document

Creates an IvParameterSpec object using the bytes in iv as the IV.

Usage

From source file:com.gfw.press.encrypt.Encrypt.java

/**
 * ?//w  w  w.j  av  a 2 s  .c o  m
 * 
 * @param key
 *            SecretKey
 * 
 * @param bytes
 *            ?
 * 
 * @return [?+?]? + [? + ?]
 * 
 */
public byte[] encryptNet(String nodePwd, byte[] bytes) {
    if (bytes == null || bytes.length == 0) {
        return null;
    }
    SecretKey key = null;
    try {
        key = getSecretKey(DigestUtils.md5Hex(nodePwd.getBytes(CHARSET)));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    if (null == key) {
        System.out.println("key!");
        return null;
    }
    byte[] IV = getSecureRandom(IV_SIZE);
    IvParameterSpec IVSpec = new IvParameterSpec(IV);
    try {
        cipher.init(Cipher.ENCRYPT_MODE, key, IVSpec);
    } catch (InvalidKeyException | InvalidAlgorithmParameterException ex) {
        log("?Cipher");
        ex.printStackTrace();
        return null;
    }
    // ?
    byte[] cipher_bytes = null;
    try {
        cipher_bytes = cipher.doFinal(bytes);
    } catch (IllegalBlockSizeException | BadPaddingException ex) {
        log("?");
        ex.printStackTrace();
        return null;
    }
    // ?
    byte[] noise_bytes = (cipher_bytes.length < NOISE_MAX / 2)
            ? getSecureRandom(secureRandom.nextInt(NOISE_MAX))
            : new byte[0];
    byte[] size_bytes = encrypt(key, getBlockSizeBytes((IV_SIZE + cipher_bytes.length), noise_bytes.length));
    if (size_bytes == null || size_bytes.length != ENCRYPT_SIZE) {
        return null;
    }
    byte[] all_cipher = new byte[size_bytes.length + IV_SIZE + cipher_bytes.length + noise_bytes.length];
    System.arraycopy(size_bytes, 0, all_cipher, 0, size_bytes.length);
    System.arraycopy(IV, 0, all_cipher, size_bytes.length, IV.length);
    System.arraycopy(cipher_bytes, 0, all_cipher, size_bytes.length + IV.length, cipher_bytes.length);
    if (noise_bytes.length > 0) { // ??
        System.arraycopy(noise_bytes, 0, all_cipher, size_bytes.length + IV.length + cipher_bytes.length,
                noise_bytes.length);
    }
    size_bytes = null;
    IV = null;
    cipher_bytes = null;
    noise_bytes = null;
    return all_cipher;
}

From source file:com.ccstats.crypto.AESWorker.java

/**
 * Decrypting text that is encrypted by the advanced encryption standard.
 *
 * @param password The char array containing of the plaintext password
 * @param encryptedBlock The Encrypted text to be targeted and decrypted.
 *
 * @return The decrypted byte array of the encrypted text.
 *//*w  w w.  ja  v a 2s. com*/
public byte[] decrypt(char[] password, char[] encryptedBlock)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, DecoderException {

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    if (Cipher.getMaxAllowedKeyLength("AES") < this.keyLength) {
        this.keyLength = Cipher.getMaxAllowedKeyLength("AES");
        System.err.printf(
                "WARNING: YOUR MAXIMUM AES KEY LENGTH POLICY IS %d BITS. KEY LENGTH LIMITED TO %d BITS.\n",
                this.keyLength, this.keyLength);
    }

    // hash the password with the MD5 function and decode the encryptedBlock
    password = hash(new String(password).getBytes(StandardCharsets.UTF_8));
    byte[] decoded = Hex.decodeHex(encryptedBlock);

    // The decoded byte array has the IV, encryptedText, and salt bytes stored in that order.
    // The IV bytes are of length 16 and salt is of length 20.
    byte[] encryptedText = new byte[decoded.length - 36], ivBytes = new byte[16], salt = new byte[20];

    // The decoded bytes are ordered in the following form: ivBytes + encryptedText + saltBytes.
    // Extract the bytes into their corresponding array.
    System.arraycopy(decoded, 0, ivBytes, 0, ivBytes.length);
    System.arraycopy(decoded, ivBytes.length, encryptedText, 0, encryptedText.length);
    System.arraycopy(decoded, decoded.length - salt.length, salt, 0, salt.length);

    // generate the key from the acquired data
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password, salt, 16384, this.keyLength);
    SecretKey key = factory.generateSecret(spec);
    SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");

    // finally, attempt to decrypt the encryptedText
    cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ivBytes));
    return cipher.doFinal(encryptedText);
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

private void writeVaultHeader(File headerFile, byte[] vaultNonce, byte[] salt, int pbkdf2Iterations, Key aesKey,
        SecretKey keyFromPassphrase) throws Exception {
    Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
    FileOutputStream headerOutputStream = new FileOutputStream(headerFile);

    c.init(Cipher.WRAP_MODE, keyFromPassphrase, new IvParameterSpec(vaultNonce));
    byte[] encryptedAesKey = c.wrap(aesKey);

    VaultHeader.Builder vaultHeaderBuilder = VaultHeader.newBuilder();
    vaultHeaderBuilder.setVersion(VAULT_HEADER_VERSION);
    vaultHeaderBuilder.setSalt(ByteString.copyFrom(salt));
    vaultHeaderBuilder.setVaultIV(ByteString.copyFrom(vaultNonce));
    vaultHeaderBuilder.setPbkdf2Iterations(pbkdf2Iterations);
    vaultHeaderBuilder.setEncryptedAesKey(ByteString.copyFrom(encryptedAesKey));
    vaultHeaderBuilder.build().writeTo(headerOutputStream);
    headerOutputStream.close();//from   ww  w  . ja  v a 2 s .  com
}

From source file:org.apache.nifi.properties.AESSensitivePropertyProvider.java

/**
 * Returns the encrypted cipher text.//from w  ww.  ja v a2s.c om
 *
 * @param unprotectedValue the sensitive value
 * @return the value to persist in the {@code nifi.properties} file
 * @throws SensitivePropertyProtectionException if there is an exception encrypting the value
 */
@Override
public String protect(String unprotectedValue) throws SensitivePropertyProtectionException {
    if (unprotectedValue == null || unprotectedValue.trim().length() == 0) {
        throw new IllegalArgumentException("Cannot encrypt an empty value");
    }

    // Generate IV
    byte[] iv = generateIV();
    if (iv.length < IV_LENGTH) {
        throw new IllegalArgumentException(
                "The IV (" + iv.length + " bytes) must be at least " + IV_LENGTH + " bytes");
    }

    try {
        // Initialize cipher for encryption
        cipher.init(Cipher.ENCRYPT_MODE, this.key, new IvParameterSpec(iv));

        byte[] plainBytes = unprotectedValue.getBytes(StandardCharsets.UTF_8);
        byte[] cipherBytes = cipher.doFinal(plainBytes);
        logger.info(getName() + " encrypted a sensitive value successfully");
        return base64Encode(iv) + DELIMITER + base64Encode(cipherBytes);
        // return Base64.toBase64String(iv) + DELIMITER + Base64.toBase64String(cipherBytes);
    } catch (BadPaddingException | IllegalBlockSizeException | EncoderException
            | InvalidAlgorithmParameterException | InvalidKeyException e) {
        final String msg = "Error encrypting a protected value";
        logger.error(msg, e);
        throw new SensitivePropertyProtectionException(msg, e);
    }
}

From source file:com.otisbean.keyring.Ring.java

/**
 * Initialize the cipher object and create the key object.
 * /* ww  w .  j a va 2  s  .  co m*/
 * @param password
 * @return A checkData string, which can be compared against the existing
 * one to determine if the password is valid.
 * @throws GeneralSecurityException
 */
private String initCipher(char[] password) throws GeneralSecurityException {
    log("initCipher()");
    String base64Key = null;
    try {
        // Convert a char array into a UTF-8 byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter out = new OutputStreamWriter(baos, "UTF-8");
        try {
            out.write(password);
            out.close();
        } catch (IOException e) {
            // the only reason this would throw is an encoding problem.
            throw new RuntimeException(e.getLocalizedMessage());
        }
        byte[] passwordBytes = baos.toByteArray();

        /* The following code looks like a lot of monkey-motion, but it yields
         * results compatible with the on-phone Keyring Javascript and Mojo code.
         * 
         * In newPassword() in ring.js, we have this (around line 165):
         * this._key = b64_sha256(this._salt + newPassword); */
        byte[] saltBytes = salt.getBytes("UTF-8");
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(saltBytes, 0, saltBytes.length);
        md.update(passwordBytes, 0, passwordBytes.length);
        byte[] keyHash = md.digest();
        String paddedBase64Key = Base64.encodeBytes(keyHash);
        /* The Javascript SHA-256 library used in Keyring doesn't pad base64 output,
         * so we need to trim off any trailing "=" signs. */
        base64Key = paddedBase64Key.replace("=", "");
        byte[] keyBytes = base64Key.getBytes("UTF-8");

        /* Keyring passes data to Mojo.Model.encrypt(key, data), which eventually
         * make a JNI call to OpenSSL's blowfish api.  The following is the
         * equivalent in straight up JCE. */
        key = new SecretKeySpec(keyBytes, "Blowfish");
        iv = new IvParameterSpec(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 });
    } catch (UnsupportedEncodingException e) {
        // This is a bit dodgy, but handling a UEE elsewhere is foolish
        throw new GeneralSecurityException(e.getLocalizedMessage());
    }
    return "{" + base64Key + "}";
}

From source file:org.openmrs.util.Security.java

/**
 * encrypt text to a string with specific initVector and secretKey; rarely used except in
 * testing and where specifically necessary
 *
 * @see #encrypt(String)//from w w  w .  j a va  2s .c  o m
 *
 * @param text string to be encrypted
 * @param initVector custom init vector byte array
 * @param secretKey custom secret key byte array
 * @return encrypted text
 * @since 1.9
 */
public static String encrypt(String text, byte[] initVector, byte[] secretKey) {
    IvParameterSpec initVectorSpec = new IvParameterSpec(initVector);
    SecretKeySpec secret = new SecretKeySpec(secretKey, OpenmrsConstants.ENCRYPTION_KEY_SPEC);
    byte[] encrypted;

    try {
        Cipher cipher = Cipher.getInstance(OpenmrsConstants.ENCRYPTION_CIPHER_CONFIGURATION);
        cipher.init(Cipher.ENCRYPT_MODE, secret, initVectorSpec);
        encrypted = cipher.doFinal(text.getBytes(encoding));
    } catch (GeneralSecurityException e) {
        throw new APIException("could.not.encrypt.text", null, e);
    } catch (UnsupportedEncodingException e) {
        throw new APIException("system.cannot.find.encoding", new Object[] { encoding }, e);
    }

    return Base64.encode(encrypted);
}

From source file:org.cryptonode.jncryptor.AES256v2Cryptor.java

/**
 * Encrypts plaintext data, 256-bit AES CBC-mode with PKCS#5 padding.
 * /*  w  w w  .jav a2 s .co  m*/
 * @param plaintext
 *          the plaintext
 * @param password
 *          the password (can be <code>null</code> or empty)
 * @param encryptionSalt
 *          eight bytes of random salt value
 * @param hmacSalt
 *          eight bytes of random salt value
 * @param iv
 *          sixteen bytes of AES IV
 * @return a formatted ciphertext
 * @throws CryptorException
 *           if an error occurred
 */
byte[] encryptData(byte[] plaintext, char[] password, byte[] encryptionSalt, byte[] hmacSalt, byte[] iv)
        throws CryptorException {

    SecretKey encryptionKey = keyForPassword(password, encryptionSalt);
    SecretKey hmacKey = keyForPassword(password, hmacSalt);

    try {
        Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv));
        byte[] ciphertext = cipher.doFinal(plaintext);

        AES256v2Ciphertext output = new AES256v2Ciphertext(encryptionSalt, hmacSalt, iv, ciphertext);

        Mac mac = Mac.getInstance(HMAC_ALGORITHM);
        mac.init(hmacKey);
        byte[] hmac = mac.doFinal(output.getDataToHMAC());
        output.setHmac(hmac);
        return output.getRawData();

    } catch (GeneralSecurityException e) {
        throw new CryptorException("Failed to generate ciphertext.", e);
    }
}

From source file:org.opensafety.hishare.util.implementation.EncryptionImpl.java

private IvParameterSpec generateIv(byte[] salt) {
    byte[] iv = Arrays.copyOfRange(salt, 0, 16);
    return new IvParameterSpec(iv);
}

From source file:test.frames.CryptoServiceSingleton.java

/**
 * Utility method encrypting/decrypting the given message.
 * The sense of the operation is specified using the `encryptMode` parameter.
 *
 * @param encryptMode  encrypt or decrypt mode ({@link javax.crypto.Cipher#DECRYPT_MODE} or
 *                     {@link javax.crypto.Cipher#ENCRYPT_MODE}).
 * @param generatedKey the generated key
 * @param vector       the initialization vector
 * @param message      the plain/cipher text to encrypt/decrypt
 * @return the encrypted or decrypted message
 *//*from  w  w  w . j a v a2 s .  c o  m*/
private byte[] doFinal(int encryptMode, SecretKey generatedKey, String vector, byte[] message) {
    try {
        byte[] raw = Hex.decodeHex(vector.toCharArray());
        Cipher cipher = Cipher.getInstance(AES_CBC_ALGORITHM);
        cipher.init(encryptMode, generatedKey, new IvParameterSpec(raw));
        return cipher.doFinal(message);
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:ropes.Crypto.java

/**
* If a file is being decrypted, we need to know the pasword, the salt and the initialization vector (iv). 
* We have the password from initializing the class. pass the iv and salt here which is
* obtained when encrypting the file initially.
*   //from www .ja va2 s  .c  o  m
* @param initvec
* @param salt
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws NoSuchPaddingException
* @throws InvalidKeyException
* @throws InvalidAlgorithmParameterException
* @throws DecoderException
*/
public void setupDecrypt(String initvec, String salt) {
    try {
        SecretKeyFactory factory = null;
        SecretKey tmp = null;
        SecretKey secret = null;

        // since we pass it as a string of input, convert to a actual byte buffer here
        mSalt = Hex.decodeHex(salt.toCharArray());
        Db("got salt " + Hex.encodeHexString(mSalt));

        // get initialization vector from passed string
        mInitVec = Hex.decodeHex(initvec.toCharArray());
        Db("got initvector :" + Hex.encodeHexString(mInitVec));

        /* Derive the key, given password and salt. */
        // in order to do 256 bit crypto, you have to muck with the files for Java's "unlimted security"
        // The end user must also install them (not compiled in) so beware.
        // see here:
        // http://www.javamex.com/tutorials/cryptography/unrestricted_policy_files.shtml
        factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        KeySpec spec = new PBEKeySpec(mPassword.toCharArray(), mSalt, ITERATIONS, KEYLEN_BITS);

        tmp = factory.generateSecret(spec);
        secret = new SecretKeySpec(tmp.getEncoded(), "AES");

        /* Decrypt the message, given derived key and initialization vector. */
        mDecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        mDecipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(mInitVec));

    } catch (DecoderException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidAlgorithmParameterException ex) {
        Logger.getLogger(Crypto.class.getName()).log(Level.SEVERE, null, ex);
    }
}