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:alfio.manager.CheckInManager.java

public static String decrypt(String key, String payload) {
    try {//from  www . ja  v a  2  s  . c  o  m
        Pair<Cipher, SecretKeySpec> cipherAndSecret = getCypher(key);
        Cipher cipher = cipherAndSecret.getKey();
        String[] splitted = payload.split(Pattern.quote("|"));
        byte[] iv = Base64.decodeBase64(splitted[0]);
        byte[] body = Base64.decodeBase64(splitted[1]);
        cipher.init(Cipher.DECRYPT_MODE, cipherAndSecret.getRight(), new IvParameterSpec(iv));
        byte[] decrypted = cipher.doFinal(body);
        return new String(decrypted, StandardCharsets.UTF_8);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}

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

Key decryptMetadataAndReturnCEK(String partitionKey, String rowKey, EntityProperty encryptionKeyProperty,
        EntityProperty propertyDetailsProperty, EncryptionData encryptionData) throws StorageException {
    // Throw if neither the key nor the key resolver are set.
    if (this.keyWrapper == null && this.keyResolver == null) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.KEY_AND_RESOLVER_MISSING, null);
    }//from   ww  w.  j  av  a  2 s .c o m

    try {
        // Copy the values into the passed in encryption data object so they can be accessed outside of this context
        encryptionData.copyValues(EncryptionData.deserialize(encryptionKeyProperty.getValueAsString()));

        Utility.assertNotNull("contentEncryptionIV", encryptionData.getContentEncryptionIV());
        Utility.assertNotNull("encryptedKey", encryptionData.getWrappedContentKey().getEncryptedKey());

        // Throw if the encryption protocol on the entity doesn't match the version that this client library understands
        // and is able to decrypt.
        if (!Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1
                .equals(encryptionData.getEncryptionAgent().getProtocol())) {
            throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                    SR.ENCRYPTION_PROTOCOL_VERSION_INVALID, null);
        }

        byte[] contentEncryptionKey = null;

        // 1. Invoke the key resolver if specified to get the key. If the resolver is specified but does not have a
        // mapping for the key id, an error should be thrown. This is important for key rotation scenario.
        // 2. If resolver is not specified but a key is specified, match the key id on the key and and use it.
        // Calling UnwrapKeyAsync synchronously is fine because for the storage client scenario, unwrap happens
        // locally. No service call is made.
        if (this.keyResolver != null) {
            IKey keyEncryptionKey = this.keyResolver
                    .resolveKeyAsync(encryptionData.getWrappedContentKey().getKeyId()).get();

            Utility.assertNotNull("keyEncryptionKey", keyEncryptionKey);
            contentEncryptionKey = keyEncryptionKey
                    .unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
                            encryptionData.getWrappedContentKey().getAlgorithm())
                    .get();
        } else {
            if (encryptionData.getWrappedContentKey().getKeyId().equals(this.keyWrapper.getKid())) {
                contentEncryptionKey = this.keyWrapper
                        .unwrapKeyAsync(encryptionData.getWrappedContentKey().getEncryptedKey(),
                                encryptionData.getWrappedContentKey().getAlgorithm())
                        .get();
            } else {
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.KEY_MISMATCH, null);
            }
        }

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        MessageDigest sha256 = MessageDigest.getInstance("SHA-256");

        byte[] metadataIVFull = sha256.digest(Utility.binaryAppend(encryptionData.getContentEncryptionIV(),
                (partitionKey + rowKey + Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS)
                        .getBytes(Constants.UTF8_CHARSET)));

        byte[] metadataIV = new byte[16];
        System.arraycopy(metadataIVFull, 0, metadataIV, 0, 16);

        IvParameterSpec ivParameterSpec = new IvParameterSpec(metadataIV);
        SecretKey keySpec = new SecretKeySpec(contentEncryptionKey, 0, contentEncryptionKey.length, "AES");
        myAes.init(Cipher.DECRYPT_MODE, keySpec, ivParameterSpec);

        byte[] src = propertyDetailsProperty.getValueAsByteArray();
        propertyDetailsProperty.setValue(myAes.doFinal(src, 0, src.length));

        return keySpec;
    } catch (StorageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.DECRYPTION_LOGIC_ERROR, ex);
    }
}

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

private void prepareEncryptionDictRev6(String ownerPassword, String userPassword,
        PDEncryption encryptionDictionary, int permissionInt) throws IOException {
    try {//www.  j a  va2  s  .  c o m
        SecureRandom rnd = new SecureRandom();
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");

        // make a random 256-bit file encryption key
        encryptionKey = new byte[32];
        rnd.nextBytes(encryptionKey);

        // Algorithm 8a: Compute U
        byte[] userPasswordBytes = truncate127(userPassword.getBytes(Charsets.UTF_8));
        byte[] userValidationSalt = new byte[8];
        byte[] userKeySalt = new byte[8];
        rnd.nextBytes(userValidationSalt);
        rnd.nextBytes(userKeySalt);
        byte[] hashU = computeHash2B(concat(userPasswordBytes, userValidationSalt), userPasswordBytes, null);
        byte[] u = concat(hashU, userValidationSalt, userKeySalt);

        // Algorithm 8b: Compute UE
        byte[] hashUE = computeHash2B(concat(userPasswordBytes, userKeySalt), userPasswordBytes, null);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashUE, "AES"), new IvParameterSpec(new byte[16]));
        byte[] ue = cipher.doFinal(encryptionKey);

        // Algorithm 9a: Compute O
        byte[] ownerPasswordBytes = truncate127(ownerPassword.getBytes(Charsets.UTF_8));
        byte[] ownerValidationSalt = new byte[8];
        byte[] ownerKeySalt = new byte[8];
        rnd.nextBytes(ownerValidationSalt);
        rnd.nextBytes(ownerKeySalt);
        byte[] hashO = computeHash2B(concat(ownerPasswordBytes, ownerValidationSalt, u), ownerPasswordBytes, u);
        byte[] o = concat(hashO, ownerValidationSalt, ownerKeySalt);

        // Algorithm 9b: Compute OE
        byte[] hashOE = computeHash2B(concat(ownerPasswordBytes, ownerKeySalt, u), ownerPasswordBytes, u);
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(hashOE, "AES"), new IvParameterSpec(new byte[16]));
        byte[] oe = cipher.doFinal(encryptionKey);

        // Set keys and other required constants in encryption dictionary
        encryptionDictionary.setUserKey(u);
        encryptionDictionary.setUserEncryptionKey(ue);
        encryptionDictionary.setOwnerKey(o);
        encryptionDictionary.setOwnerEncryptionKey(oe);

        PDCryptFilterDictionary cryptFilterDictionary = new PDCryptFilterDictionary();
        cryptFilterDictionary.setCryptFilterMethod(COSName.AESV3);
        cryptFilterDictionary.setLength(keyLength);
        encryptionDictionary.setStdCryptFilterDictionary(cryptFilterDictionary);
        encryptionDictionary.setStreamFilterName(COSName.STD_CF);
        encryptionDictionary.setStringFilterName(COSName.STD_CF);
        setAES(true);

        // Algorithm 10: compute "Perms" value
        byte[] perms = new byte[16];
        perms[0] = (byte) permissionInt;
        perms[1] = (byte) (permissionInt >>> 8);
        perms[2] = (byte) (permissionInt >>> 16);
        perms[3] = (byte) (permissionInt >>> 24);
        perms[4] = (byte) 0xFF;
        perms[5] = (byte) 0xFF;
        perms[6] = (byte) 0xFF;
        perms[7] = (byte) 0xFF;
        perms[8] = 'T'; // we always encrypt Metadata
        perms[9] = 'a';
        perms[10] = 'd';
        perms[11] = 'b';
        for (int i = 12; i <= 15; i++) {
            perms[i] = (byte) rnd.nextInt();
        }

        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"),
                new IvParameterSpec(new byte[16]));

        byte[] permsEnc = cipher.doFinal(perms);

        encryptionDictionary.setPerms(permsEnc);
    } catch (GeneralSecurityException e) {
        logIfStrongEncryptionMissing();
        throw new IOException(e);
    }
}

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

/**
 * ?//  www. j  a v  a 2s.  co  m
 *
 * @param content
 *            ?
 * @return ??
 */

public static String simpleDecrypt(String content, String key) {
    int SIMPLE_ENCRYPT_KEY_LENGTH = 16;
    byte[] keyBytes = new byte[SIMPLE_ENCRYPT_KEY_LENGTH];
    byte[] decrypt = null;
    byte[] encrypt = null;
    byte[] allData = null;
    try {
        allData = decodeBase64(content);
        encrypt = new byte[allData.length - keyBytes.length];
        System.arraycopy(allData, 0, keyBytes, 0, keyBytes.length);
        System.arraycopy(allData, keyBytes.length, encrypt, 0, encrypt.length);
        byte[] _keyBytes = key.getBytes(CHARSET);
        if (_keyBytes.length < SIMPLE_ENCRYPT_KEY_LENGTH) {
            System.arraycopy(_keyBytes, 0, keyBytes, 0, _keyBytes.length);
        } else {
            System.arraycopy(_keyBytes, 0, keyBytes, 0, SIMPLE_ENCRYPT_KEY_LENGTH);
        }
        Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
        IvParameterSpec IVSpec = new IvParameterSpec(keyBytes);
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(keyBytes, 0, keyBytes.length, "AES"), IVSpec);
        decrypt = cipher.doFinal(encrypt);
        return new String(decrypt, CHARSET);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        keyBytes = decrypt = encrypt = allData = null;
    }
    return "";
}

From source file:org.chililog.server.common.CryptoUtils.java

/**
 * <p>/*from   ww  w  . j a v a 2  s . c  o m*/
 * Encrypt a plain text string using TripleDES. The output is an encrypted plain text string. See
 * http://stackoverflow.com/questions/20227/how-do-i-use-3des-encryption-decryption-in-java
 * </p>
 * <p>
 * The algorithm used is <code>base64(tripleDES(plainText))</code>
 * </p>
 * <p>
 * TripleDES is a lot quicker than AES.
 * </p>
 * 
 * @param plainText
 *            text to encrypt
 * @param password
 *            password to use for encryption
 * @return encrypted text
 * @throws ChiliLogException
 */
public static String encryptTripleDES(String plainText, byte[] password) throws ChiliLogException {
    try {
        final MessageDigest md = MessageDigest.getInstance("md5");
        final byte[] digestOfPassword = md.digest(password);
        final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
        for (int j = 0, k = 16; j < 8;) {
            keyBytes[k++] = keyBytes[j++];
        }

        final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
        final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
        final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);

        final byte[] plainTextBytes = plainText.getBytes("UTF-8");
        final byte[] cipherText = cipher.doFinal(plainTextBytes);

        // Convert hash to string
        Base64 encoder = new Base64(1000, new byte[] {}, false);
        return encoder.encodeToString(cipherText);
    } catch (Exception ex) {
        throw new ChiliLogException(ex, "Error attempting to encrypt. " + ex.getMessage());
    }
}

From source file:servlets.module.challenge.BrokenCryptoHomeMade.java

/**
 * Encrypts plain text into cipher text based on encryption key
 * @param key Encryption Key (Must be 16 Bytes)
 * @param value Plain text to encrypt/*from   ww  w  .  j  a  va 2 s .c  o  m*/
 * @return Cipher text based on plain text and key submitted
 * @throws GeneralSecurityException
 */
public static String encrypt(String key, String value) throws GeneralSecurityException {
    byte[] raw = key.getBytes(Charset.forName("US-ASCII"));
    if (raw.length != 16) {
        throw new IllegalArgumentException("Invalid key size.");
    }
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));
    return Base64.encodeBase64String(cipher.doFinal(value.getBytes(Charset.forName("US-ASCII"))));
}

From source file:net.sourceforge.msscodefactory.cflib.v2_1.CFLib.Tip.CFTipClientHandler.java

public void issueLoginRequest(String body)
        throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException,
        BadPaddingException, InvalidAlgorithmParameterException {
    final String S_ProcName = "issueLoginRequest";

    if (responseHandler == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Response handler must be set first by setResponseHandler()");
    }//from   ww  w  .j ava 2  s. c  om

    if (serverInfo == null) {
        throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
                "Server info must be queried first by requestServerInfo()");
    }

    if ((body == null) || (body.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1, "body");
    }

    SecureRandom random = new SecureRandom();
    byte iv[] = new byte[16];
    random.nextBytes(iv);
    byte[] base64IV = Base64.encodeBase64(iv);
    String stringIV = new String(base64IV);
    IvParameterSpec ivspec = new IvParameterSpec(iv);

    byte[] encodedSessionKey = getEncodedSessionKey();
    byte[] encryptedSessionKey = encryptWithServerPublicKey(encodedSessionKey);
    byte[] base64SessionKey = Base64.encodeBase64(encryptedSessionKey);
    String stringSessionKey = new String(base64SessionKey);

    byte bodyBytes[] = body.getBytes();
    byte serverEncrypted[] = encryptWithSessionKey(ivspec, bodyBytes);
    byte base64Encrypted[] = Base64.encodeBase64(serverEncrypted);
    String encoded = new String(base64Encrypted);

    final String msg = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<CFTIPEnvelope\n"
            + "\t\txmlns=\"uri://net.sourceforge.msscodefactory/cftipenvelope\"\n"
            + "\t\txmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "\t\txmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n"
            + "\t\txsi:schemaLocation=\"uri://net.sourceforge.msscodefactory/cftipenvelope file://xsd/cftip-envelope.xsd\" >\n"
            + "\t<LoginRequest MessageIV=\"" + stringIV + "\" AES256Key=\"" + stringSessionKey + "\" Payload=\""
            + encoded + "\" />\n" + "</CFTIPEnvelope>\n";
    String response = sendReceive(msg);
    if ((response == null) || (response.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                "response");
    }
    byte responseBytes[] = Base64.decodeBase64(response);
    byte decrypted[] = decryptWithSessionKey(ivspec, responseBytes);
    String decryptedResponse = new String(decrypted);
    responseHandler.parseStringContents(decryptedResponse);
}

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

public byte[] encryptSymmetric(byte[] inputdata)

        throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, NoSuchPaddingException,

        NoSuchAlgorithmException {

    //EBWLogger.trace(this,"Starting method public String  encrypt(String data)");

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

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

    //        cipherSymmetric = Cipher.getInstance(EBWConstants.ENCRYPTION_KEYGEN_ALGORITHM);

    //        cipherSymmetric.init(Cipher.ENCRYPT_MODE,generateKeyForSymmetric());

    try {/*from w w w.  java  2 s .c o  m*/

        //           cipherSymmetric = Cipher.getInstance(EBWConstants.ENCRYPTION_KEYGEN_ALGORITHM+"/CFB/NoPadding");

        System.out.println("[" + EBWConstants.ENCRYPTION_KEYGEN_ALGORITHM + "/" + EBWConstants.ENCRYPTION_MODE
                + "/" + EBWConstants.ENCRYPTION_PADDING + "]");

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

        IvParameterSpec ivps = new IvParameterSpec(getSecretVector());

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

    } catch (InvalidAlgorithmParameterException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (Exception e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

    /**Create a byte data for encrypting.
            
            
    All inputs given to encryption are bytes.**/

    byte[] encResult = cipherSymmetric.doFinal(inputdata);

    //EBWLogger.trace(this,"Returning from method public static String  encrypt(String data)");

    return encResult;

}

From source file:ws.salient.aws.dynamodb.DynamoDBStore.java

public Item decrypt(Item item, SecretKeySpec key, String... attributes) {
    try {/* w  w  w .  java  2 s.co  m*/
        if (key != null) {
            String transformation = (String) item.getMap("cipher").get("transformation");
            byte[] iv = (byte[]) item.getMap("cipher").get("iv");
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
            for (String attribute : attributes) {
                byte[] value = item.getBinary(attribute);
                item.withBinary(attribute, cipher.doFinal(value));
            }
        }
        return item;

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {
        throw new RuntimeException(ex);
    }
}

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

@Override
public void renameFile(File file, String newName) throws SecrecyCipherStreamException, FileNotFoundException {
    Cipher c;//www.  j a  v  a 2s  .c  o  m
    try {
        c = Cipher.getInstance(encryptionMode);
    } catch (NoSuchAlgorithmException e) {
        throw new SecrecyCipherStreamException("Encryption algorithm not found!");
    } catch (NoSuchPaddingException e) {
        throw new SecrecyCipherStreamException("Selected padding not found!");
    }

    File headerFile = new File(file.getParent() + FILE_HEADER_PREFIX + file.getName());
    if (!headerFile.exists()) {
        throw new FileNotFoundException("Header file not found!");
    }

    FileHeader fileHeader;
    try {
        fileHeader = FileHeader.parseFrom(new FileInputStream(headerFile));
    } catch (IOException e) {
        throw new SecrecyCipherStreamException("Cannot parse file header!");
    }

    try {
        c.init(Cipher.ENCRYPT_MODE, vaultFileEncryptionKey,
                new IvParameterSpec(fileHeader.getFileNameIV().toByteArray()));
    } catch (InvalidKeyException e) {
        throw new SecrecyCipherStreamException("Invalid encryption key!");
    } catch (InvalidAlgorithmParameterException e) {
        throw new SecrecyCipherStreamException("Invalid algorithm parameter!");
    }

    byte[] encryptedFileName;
    try {
        encryptedFileName = c.doFinal(newName.getBytes());
    } catch (IllegalBlockSizeException e) {
        throw new SecrecyCipherStreamException("Illegal block size!");
    } catch (BadPaddingException e) {
        throw new SecrecyCipherStreamException("Bad padding");
    }

    FileHeader.Builder fileHeaderBuilder = fileHeader.toBuilder();
    fileHeaderBuilder.setEncryptedFileName(ByteString.copyFrom(encryptedFileName));

    FileOutputStream headerOutputStream = new FileOutputStream(headerFile);
    try {
        fileHeaderBuilder.build().writeTo(headerOutputStream);
        headerOutputStream.close();
    } catch (IOException e) {
        throw new SecrecyCipherStreamException("IO exception while writing file header");
    }
}