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:TDS.Shared.Web.Encryption.java

/**
 * decrypts a string/*w ww .  ja  v  a  2 s . c  om*/
 * 
 * @param stringToDecrypt
 * @return decrypted string
 * @throws TDSEncryptionException
 */
private synchronized String decrypt(String stringToDecrypt) {
    try {

        if (StringUtils.isEmpty(stringToDecrypt)) {
            return "";
        }

        byte[] encryptedBytes = DatatypeConverter.parseBase64Binary(stringToDecrypt);

        byte[] iv = new byte[IV_LENGTH];
        System.arraycopy(encryptedBytes, 0, iv, 0, iv.length);
        _decryptCipher.init(Cipher.DECRYPT_MODE, _secretKey, new IvParameterSpec(iv));
        byte[] cipherBytes = new byte[encryptedBytes.length - IV_LENGTH];
        System.arraycopy(encryptedBytes, IV_LENGTH, cipherBytes, 0, cipherBytes.length);
        byte[] decryptedBytes = _decryptCipher.doFinal(cipherBytes);
        return new String(decryptedBytes, CHARSET_NAME);
    } catch (InvalidAlgorithmParameterException e) {
        _logger.error("Encyption.decrypt: " + e.getMessage(), e);
        throw new TDSEncryptionException("Algorithm is not valid");
    } catch (InvalidKeyException e) {
        _logger.error("Encyption.decrypt: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key is not valid");
    } catch (IllegalBlockSizeException e) {
        _logger.error("Encyption.decrypt: " + e.getMessage(), e);
        throw new TDSEncryptionException("Block size is not valid");
    } catch (BadPaddingException e) {
        _logger.error("Encyption.decrypt: " + e.getMessage(), e);
        throw new TDSEncryptionException("Padding is not valid");
    } catch (UnsupportedEncodingException e) {
        _logger.error("Encyption.decrypt: " + e.getMessage(), e);
        throw new TDSEncryptionException("Encoding is not valid");
    }

}

From source file:im.whistle.crypt.Crypt.java

/**
 * Decrypts a message.// ww w  . j  a v a2  s.  c  o m
 * @param args Arguments: enc, privateKey, sig, publicKey
 * @param callback Callback
 */
public static void decrypt(JSONArray args, AsyncCallback<JSONArray> callback) {
    try {
        // Get the arguments
        String enc = args.getString(0);
        String key = args.getString(1);
        String sig = null;
        String pub = null;
        if (args.length() == 4) {
            sig = args.getString(2);
            pub = args.getString(3);
        }
        Boolean ver = null;

        // Convert everything into byte arrays
        byte[] encRaw = Base64.decode(enc, Base64.DEFAULT);
        byte[] keyRaw = Base64.decode(stripKey(key), Base64.DEFAULT);

        // Verify signature
        if (sig != null && pub != null) {
            try {
                byte[] sigRaw = Base64.decode(sig, Base64.DEFAULT);
                byte[] pubRaw = Base64.decode(stripKey(pub), Base64.DEFAULT);
                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubRaw);
                KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
                Signature s = Signature.getInstance("SHA1withRSA", "BC");
                s.initVerify(kf.generatePublic(publicKeySpec));
                s.update(encRaw);
                ver = s.verify(sigRaw);
            } catch (Exception ex) {
                Log.i("whistle", "Verification failed: " + ex.getMessage());
                ver = false;
            }
        }

        // Split enc into encrypted aes data and remaining enc
        byte[] encSplit = encRaw;
        byte[] aesRaw = new byte[RSA_BYTES];
        System.arraycopy(encSplit, 0, aesRaw, 0, aesRaw.length);
        encRaw = new byte[encSplit.length - RSA_BYTES];
        System.arraycopy(encSplit, RSA_BYTES, encRaw, 0, encRaw.length);

        // Decrypt encrypted aes data using RSAES-OAEP
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyRaw);
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
        Cipher c = Cipher.getInstance("RSA/None/OAEPWithSHA-1AndMGF1Padding");
        c.init(Cipher.DECRYPT_MODE, kf.generatePrivate(privateKeySpec));
        aesRaw = c.doFinal(aesRaw);

        // Decrypted enc using AES-CBC
        byte[] aesKey = new byte[AES_BYTES];
        byte[] aesIv = new byte[aesRaw.length - aesKey.length];
        System.arraycopy(aesRaw, 0, aesKey, 0, aesKey.length);
        System.arraycopy(aesRaw, aesKey.length, aesIv, 0, aesIv.length);
        c = Cipher.getInstance("AES/CBC/PKCS7Padding");
        c.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(aesIv));
        byte[] dec = c.doFinal(encRaw);

        JSONArray res = new JSONArray();
        res.put(new String(dec, "utf-8"));
        res.put(ver);
        callback.success(res);
    } catch (Exception ex) {
        Log.w("whistle", "Decrypt error:" + ex.getMessage(), ex);
        callback.error(ex);
    }
}

From source file:org.apache.spark.network.crypto.AuthEngine.java

private void initializeForAuth(String cipher, byte[] nonce, SecretKeySpec key) throws GeneralSecurityException {

    // commons-crypto currently only supports ciphers that require an initial vector; so
    // create a dummy vector so that we can initialize the ciphers. In the future, if
    // different ciphers are supported, this will have to be configurable somehow.
    byte[] iv = new byte[conf.ivLength()];
    System.arraycopy(nonce, 0, iv, 0, Math.min(nonce.length, iv.length));

    encryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf);
    encryptor.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));

    decryptor = CryptoCipherFactory.getCryptoCipher(cipher, cryptoConf);
    decryptor.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
}

From source file:de.hybris.platform.cuppytrail.impl.DefaultSecureTokenService.java

private String encrypt(final byte[] plainText, final byte[] encryptionKeyBytes, final SecureRandom random)
        throws GeneralSecurityException {
    // Generate 16 random IV bytes
    final byte[] ivBytes = new byte[AESIV_LENGTH];
    random.nextBytes(ivBytes);/*  w w  w.  j  a v a  2s  . co  m*/
    final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

    // Setup cypher
    final Cipher cipher = Cipher.getInstance(ENCRYPTION_CIPHER);
    cipher.init(Cipher.ENCRYPT_MODE, buildSecretKey(encryptionKeyBytes), ivSpec);

    // Generate encrypted data
    final byte[] encryptedBytes = cipher.doFinal(plainText);

    // Prepend the IV
    final byte[] encryptedBytesPlusIV = new byte[ivBytes.length + encryptedBytes.length];
    System.arraycopy(ivBytes, 0, encryptedBytesPlusIV, 0, ivBytes.length);
    System.arraycopy(encryptedBytes, 0, encryptedBytesPlusIV, ivBytes.length, encryptedBytes.length);

    return convert(encryptedBytesPlusIV);
}

From source file:com.ironchain.common.kits.DigestKit.java

/**
 * AES/DES?, ?./*from   w ww  .  j  av  a  2s .com*/
 * 
 * @param input
 *            
 * @param key
 *            ?AES?
 * @param iv
 *            ???
 * @param mode
 *            Cipher.ENCRYPT_MODE  Cipher.DECRYPT_MODE
 * @param keyMode
 *            key?
 * @param encryptMode
 *            ?
 */
private static byte[] cryptos(byte[] input, byte[] key, byte[] iv, int mode, String keyMode,
        String encryptMode) {
    try {
        SecretKey secretKey = new SecretKeySpec(key, keyMode);
        Cipher cipher = Cipher.getInstance(encryptMode);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(mode, secretKey, ivSpec);
        } else {
            cipher.init(mode, secretKey);
        }
        return cipher.doFinal(input);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.orange.oidc.secproxy_service.KryptoUtils.java

static String encryptJWE(byte[] bytes, Key pubRsaKey, byte[] cek) {
    // Log.d("","encryptJWE");
    try {//  w  ww  .  j  a  v a2 s.  c  o  m
        // A.2.1
        // jwe header already computed as static
        // jweProtectedHeader;

        // A.2.2 Content Encryption Key (CEK)
        if (cek == null) {
            cek = generateRandomKey(256);
        }

        // Log.d("","cek: "+bytesToHex(cek));

        // A.2.3 Key Encryption
        String jweEncrypted64 = encryptRsaB64(cek, pubRsaKey);
        // Log.d("","jweEncrypted "+jweEncrypted64 );

        // A.2.4 Initialization Vector
        byte[] iv_key = generateRandomKey(128);

        // Log.d("","jweInitVector: "+bytesToHex(iv_key));
        String jweInitVector64 = encodeB64(iv_key);
        // Log.d("","jweInitVector64 "+jweInitVector64 );

        // A.2.5 Additional Authenticated Data
        byte[] aad = jweProtectedHeader.getBytes();

        // A.2.6. Content Encryption
        Cipher encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;
        int keySize = cek.length / 2;
        Log.d("", "Encryption AES: " + keySize * 8);

        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // Log.d("","hmac_key: "+bytesToHex(hmac_key));
        // Log.d("","aes_key: "+bytesToHex(aes_key));

        encrypt.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] cryptedBytes = encrypt.doFinal(bytes);
        String cryptedBytes64 = encodeB64(cryptedBytes);

        // compute hmac
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
        int offset = 0;
        System.arraycopy(aad, offset, hmacData, 0, aad.length);
        offset += aad.length;
        System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
        offset += iv_key.length;
        System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
        offset += cryptedBytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(al);
        System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

        // hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // authentication tag
        byte[] auth_tag = Arrays.copyOf(hmacValue, 16);
        String auth_tag64 = encodeB64(auth_tag);

        // A.2.7. Complete Representation
        String finalString = jweProtectedHeader + "." + jweEncrypted64 + "." + jweInitVector64 + "."
                + cryptedBytes64 + "." + auth_tag64;

        return finalString;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:edu.stanford.junction.extra.Encryption.java

/**
 * Decrypts an inbound message before handing it to the activity developer.
 *//*from w  ww.  j a  v a2s  .  c o  m*/
@Override
public synchronized boolean beforeOnMessageReceived(MessageHeader h, JSONObject msg) {
    if (mKeySpec == null)
        return true;

    try {
        if (!msg.has(FIELD_ENC)) {
            return true;
        }

        String b64 = msg.getString(FIELD_ENC);
        byte[] dec = Base64Coder.decode(b64);

        if (msg.has(FIELD_IV)) {
            byte[] iv = Base64.decode(msg.getString(FIELD_IV));
            mCipher.init(Cipher.DECRYPT_MODE, mKeySpec, new IvParameterSpec(iv));
            msg.remove(FIELD_IV);
        } else {
            mCipher.init(Cipher.DECRYPT_MODE, mKeySpec);
        }

        byte[] res = mCipher.doFinal(dec);
        JSONObject obj = new JSONObject(new String(res));

        msg.remove("e");
        Iterator<String> keys = obj.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            msg.put(key, obj.get(key));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

From source file:com.eucalyptus.auth.crypto.StringCrypto.java

public byte[] encrypt(String string, String secret)
        throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    final byte[] keyBytes = makeKey(secret);
    final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
    final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
    final Cipher cipher = Cipher.getInstance(this.symmetricFormat);
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    final byte[] stringEncrypted = cipher.doFinal(string.getBytes());
    return UrlBase64.encode(stringEncrypted);
}

From source file:net.ymate.platform.module.wechat.support.MessageHelper.java

/**
 * .//from   w w  w  .  java  2  s. c o m
 *
 * @param encryptText ?
 * @return 
 * @throws AesException aes
 */
static String decrypt(String appId, byte[] aesKey, String encryptText) throws AesException {
    byte[] original;
    try {
        // ?AESCBC?
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        SecretKeySpec key_spec = new SecretKeySpec(aesKey, "AES");
        IvParameterSpec iv = new IvParameterSpec(Arrays.copyOfRange(aesKey, 0, 16));
        cipher.init(Cipher.DECRYPT_MODE, key_spec, iv);
        // BASE64?
        byte[] encrypted = Base64.decodeBase64(encryptText);
        // 
        original = cipher.doFinal(encrypted);
    } catch (Exception e) {
        throw new AesException(AesException.DecryptAESError, RuntimeUtils.unwrapThrow(e));
    }

    String xmlContent, from_appid;
    try {
        // ?
        byte[] bytes = PKCS7Encoder.decode(original);
        // 16??,?AppId
        byte[] networkOrder = Arrays.copyOfRange(bytes, 16, 20);
        int xmlLength = recoverNetworkBytesOrder(networkOrder);
        xmlContent = new String(Arrays.copyOfRange(bytes, 20, 20 + xmlLength), __CHARSET);
        from_appid = new String(Arrays.copyOfRange(bytes, 20 + xmlLength, bytes.length), __CHARSET);
    } catch (Exception e) {
        throw new AesException(AesException.IllegalBuffer, RuntimeUtils.unwrapThrow(e));
    }
    // appid??
    if (!from_appid.equals(appId)) {
        throw new AesException(AesException.ValidateAppidError);
    }
    return xmlContent;

}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Encrypt plain text using AES/*from  w  ww  .j  a v  a 2  s . c  o m*/
 *
 * @param plainText the String text to be encrypted in AES
 * @return the encrypted text String
 *
 */
public static String encrypt(String plainText) {
    try {
        byte[] saltBytes = salt.getBytes("UTF-8");
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
        PBEKeySpec spec = new PBEKeySpec(seeds, saltBytes, iterations, keySize);
        SecretKey secretKey = factory.generateSecret(spec);
        SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));
        byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return new Base64().encodeAsString(encryptedTextBytes);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to encrypt a string. ");
    } catch (InvalidKeySpecException e) {
        logger.error("InvalidKeySpecException when attempting to encrypt a string. ");
    } catch (NoSuchPaddingException e) {
        logger.error("NoSuchPaddingException when attempting to encrypt a string. ");
    } catch (IllegalBlockSizeException e) {
        logger.error("IllegalBlockSizeException when attempting to encrypt a string. ");
    } catch (BadPaddingException e) {
        logger.error("BadPaddingException when attempting to encrypt a string. ");
    } catch (UnsupportedEncodingException e) {
        logger.error("UnsupportedEncodingException when attempting to encrypt a string. ");
    } catch (InvalidKeyException e) {
        logger.error("InvalidKeyException when attempting to encrypt a string. ");
    } catch (InvalidAlgorithmParameterException e) {
        logger.error("InvalidAlgorithmParameterException when attempting to encrypt a string. ");
    }
    return null;
}