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.kactech.otj.Utils.java

public static ByteBuffer seal(String msg, String nymID, PublicKey nymKey) throws InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
    SecureRandom random = new SecureRandom();
    byte[] aesKey = new byte[16];
    random.nextBytes(aesKey);/* ww  w.  ja v  a 2s  .  c  o  m*/
    byte[] vector = new byte[16];
    random.nextBytes(vector);
    return seal(msg, nymID, nymKey, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(vector));
}

From source file:test.PBEncryptLink.java

/**
 * Store the contents of a byte array as the IvParameterSpec. The array is
 * copied and can be safely modified after the IV has been set.
 * /*from ww w. ja va  2 s  . c  o m*/
 * @param iv
 */
public void setIV(byte[] iv) {
    if (iv.length != 8) {
        throw new IllegalArgumentException("The byte array supplied to setIV must be exactly 8 "
                + "elements long. The supplied array was " + iv.length + " elements.");
    }
    IvParameterSpec ivs = new IvParameterSpec(iv);
    ivParmSpec_ = ivs;
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

public static byte[] decrypt(byte[] secure, ExternalContext ctx) {
    if (ctx == null)
        throw new NullPointerException("ExternalContext ctx");

    testConfiguration(ctx);//w w  w.j a  va  2s. com

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("decrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        mac.update(secure, 0, secure.length - macLenght);
        byte[] signedDigestHash = mac.doFinal();

        boolean isMacEqual = true;
        for (int i = 0; i < signedDigestHash.length; i++) {
            if (signedDigestHash[i] != secure[secure.length - macLenght + i]) {
                isMacEqual = false;
                // MYFACES-2934 Must compare *ALL* bytes of the hash, 
                // otherwise a side-channel timing attack is theorically possible
                // but with a very very low probability, because the
                // comparison time is too small to be measured compared to
                // the overall request time and in real life applications,
                // there are too many uncertainties involved.
                //break;
            }
        }
        if (!isMacEqual) {
            throw new ViewExpiredException();
        }

        return cipher.doFinal(secure, 0, secure.length - macLenght);
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

public static byte[] decrypt(byte[] secure, ExternalContext ctx) {
    if (ctx == null) {
        throw new NullPointerException("ExternalContext ctx");
    }//w  ww.  jav  a 2s . c  o  m

    testConfiguration(ctx);

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("decrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        mac.update(secure, 0, secure.length - macLenght);
        byte[] signedDigestHash = mac.doFinal();

        boolean isMacEqual = true;
        for (int i = 0; i < signedDigestHash.length; i++) {
            if (signedDigestHash[i] != secure[secure.length - macLenght + i]) {
                isMacEqual = false;
                // MYFACES-2934 Must compare *ALL* bytes of the hash, 
                // otherwise a side-channel timing attack is theorically possible
                // but with a very very low probability, because the
                // comparison time is too small to be measured compared to
                // the overall request time and in real life applications,
                // there are too many uncertainties involved.
                //break;
            }
        }
        if (!isMacEqual) {
            throw new ViewExpiredException();
        }

        return cipher.doFinal(secure, 0, secure.length - macLenght);
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:org.alfresco.repo.lotus.ws.impl.auth.LtpaAuthenticator.java

private IvParameterSpec generateIvParameterSpec(byte key[], int size) {
    byte[] row = new byte[size];

    for (int i = 0; i < size; i++) {
        row[i] = key[i];//from   ww  w.  j  a  v  a  2  s. c o  m
    }

    return new IvParameterSpec(row);
}

From source file:org.ejbca.util.StringTools.java

public static String pbeEncryptStringWithSha256Aes192(final String in)
        throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException {
    if (CryptoProviderTools.isUsingExportableCryptography()) {
        log.warn("Obfuscation not possible due to weak crypto policy.");
        return in;
    }//from  www  . j a v  a  2 s .  c  o  m
    final Digest digest = new SHA256Digest();

    final PKCS12ParametersGenerator pGen = new PKCS12ParametersGenerator(digest);
    pGen.init(PBEParametersGenerator.PKCS12PasswordToBytes(p), getSalt(), iCount);

    final ParametersWithIV params = (ParametersWithIV) pGen.generateDerivedParameters(192, 128);
    final SecretKeySpec encKey = new SecretKeySpec(((KeyParameter) params.getParameters()).getKey(), "AES");
    final Cipher c;
    c = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
    c.init(Cipher.ENCRYPT_MODE, encKey, new IvParameterSpec(params.getIV()));

    final byte[] enc = c.doFinal(in.getBytes("UTF-8"));

    final byte[] hex = Hex.encode(enc);
    return new String(hex);
}

From source file:com.tcs.ebw.security.EBWSecurity.java

public byte[] decryptSymmetric(byte[] encdata)

        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException

        , NoSuchPaddingException, InvalidAlgorithmParameterException, Exception {

    //EBWLogger.trace(this,"Starting method public String  decrypt(String encdata)");

    //EBWLogger.trace(this," Encrypted data :"+new String(encdata));

    /** Initialize cipher used for Symmetric Crypto **/

    cipherSymmetric = Cipher.getInstance(EBWConstants.ENCRYPTION_KEYGEN_ALGORITHM + "/"
            + EBWConstants.ENCRYPTION_MODE + "/" + EBWConstants.ENCRYPTION_PADDING);

    IvParameterSpec ivps = new IvParameterSpec(getSecretVector());

    cipherSymmetric.init(Cipher.DECRYPT_MODE, generateKeyForSymmetric(), ivps);

    byte[] decResult = cipherSymmetric.doFinal(encdata);

    //EBWLogger.trace(this,"Returning from method public String  decrypt(String encdata)");

    return decResult;

}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Decrypt the body.//w ww.j  a v a  2 s .c  o m
 *
 * @param jsonArray the encrypted payload
 * @return the decrypted payload.
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeySpecException
 * @throws InvalidAlgorithmParameterException
 * @throws JSONException
 */
private String decrypt(JSONArray jsonArray) throws IllegalBlockSizeException, BadPaddingException,
        UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, InvalidKeySpecException, JSONException {
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, getCiperKey(Base64.decodeBase64(jsonArray.getString(0).getBytes("UTF-8"))),
            new IvParameterSpec(Base64.decodeBase64(jsonArray.getString(1).getBytes("UTF-8"))));
    return new String(cipher.doFinal(Base64.decodeBase64(jsonArray.getString(2).getBytes("UTF-8"))));
}

From source file:com.microsoft.azure.storage.table.TableEncryptionPolicy.java

/**
 * Return a decrypted entity. This method is used for decrypting entity properties.
 *//*from www . j a v a2  s  .  co m*/
HashMap<String, EntityProperty> decryptEntity(HashMap<String, EntityProperty> properties,
        HashSet<String> encryptedPropertyDetailsSet, String partitionKey, String rowKey,
        Key contentEncryptionKey, EncryptionData encryptionData) throws StorageException {
    HashMap<String, EntityProperty> decryptedProperties = new HashMap<String, EntityProperty>();

    try {
        switch (encryptionData.getEncryptionAgent().getEncryptionAlgorithm()) {
        case AES_CBC_256:
            Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");

            for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
                if (kvp.getKey() == Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS
                        || kvp.getKey() == Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS) {
                    // Do nothing. Do not add to the result properties.
                } else if (encryptedPropertyDetailsSet.contains(kvp.getKey())) {
                    MessageDigest digest = MessageDigest.getInstance("SHA-256");
                    byte[] columnIVFull = digest
                            .digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                                    (partitionKey + rowKey + kvp.getKey()).getBytes(Constants.UTF8_CHARSET)));

                    byte[] columnIV = new byte[16];
                    System.arraycopy(columnIVFull, 0, columnIV, 0, 16);

                    myAes.init(Cipher.DECRYPT_MODE, contentEncryptionKey, new IvParameterSpec(columnIV));

                    byte[] src = kvp.getValue().getValueAsByteArray();
                    byte[] dest = myAes.doFinal(src, 0, src.length);
                    String destString = new String(dest, Constants.UTF8_CHARSET);
                    decryptedProperties.put(kvp.getKey(), new EntityProperty(destString));
                } else {
                    decryptedProperties.put(kvp.getKey(), kvp.getValue());
                }
            }
            return decryptedProperties;

        default:
            throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                    SR.INVALID_ENCRYPTION_ALGORITHM, null);
        }
    } catch (StorageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.DECRYPTION_LOGIC_ERROR, ex);
    }
}

From source file:com.badlogic.gdx.pay.android.ouya.PurchaseManagerAndroidOUYA.java

public void requestPurchase(final Product product)
        throws GeneralSecurityException, UnsupportedEncodingException, JSONException {
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");

    // This is an ID that allows you to associate a successful purchase with
    // it's original request. The server does nothing with this string except
    // pass it back to you, so it only needs to be unique within this instance
    // of your app to allow you to pair responses with requests.
    String uniqueId = Long.toHexString(sr.nextLong());

    JSONObject purchaseRequest = new JSONObject();
    purchaseRequest.put("uuid", uniqueId);
    purchaseRequest.put("identifier", product.getIdentifier());
    // purchaseRequest.put("testing", "true"); // !!!! This value is only needed for testing, not setting it results in a live purchase
    String purchaseRequestJson = purchaseRequest.toString();

    byte[] keyBytes = new byte[16];
    sr.nextBytes(keyBytes);//from  w  w w . j  a  v  a 2s  . co m
    SecretKey key = new SecretKeySpec(keyBytes, "AES");

    byte[] ivBytes = new byte[16];
    sr.nextBytes(ivBytes);
    IvParameterSpec iv = new IvParameterSpec(ivBytes);

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, key, iv);
    byte[] payload = cipher.doFinal(purchaseRequestJson.getBytes("UTF-8"));

    cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");
    cipher.init(Cipher.ENCRYPT_MODE, ouyaPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

    purchasable = new Purchasable(product.getIdentifier(), Base64.encodeToString(encryptedKey, Base64.NO_WRAP),
            Base64.encodeToString(ivBytes, Base64.NO_WRAP), Base64.encodeToString(payload, Base64.NO_WRAP));

    synchronized (ouyaOutstandingPurchaseRequests) {
        ouyaOutstandingPurchaseRequests.put(uniqueId, product);
    }
}