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:org.jasig.cas.extension.clearpass.EncryptedMapDecorator.java

protected String decrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }/*from  w  w w.j  a  v a 2s  .c  o m*/

    try {
        final Cipher cipher = getCipherObject();

        byte[] ivByteArray = algorithmParametersHashMap.get(hashedKey).getIV();
        IvParameterSpec ivSpec = new IvParameterSpec(ivByteArray);

        cipher.init(Cipher.DECRYPT_MODE, this.key, ivSpec);

        byte[] valueByteArray = value.getBytes();
        byte[] decrypted64ByteValue = new Base64().decode(valueByteArray);
        byte[] decryptedByteArray = cipher.doFinal(decrypted64ByteValue);

        return new String(decryptedByteArray);

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.cryptomator.crypto.aes256.Aes256Cryptor.java

private Cipher aesCtrCipher(SecretKey key, byte[] iv, int cipherMode) {
    try {/* w  ww  .j a va 2 s  . c om*/
        final Cipher cipher = Cipher.getInstance(AES_CTR_CIPHER);
        cipher.init(cipherMode, key, new IvParameterSpec(iv));
        return cipher;
    } catch (InvalidKeyException ex) {
        throw new IllegalArgumentException("Invalid key.", ex);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException ex) {
        throw new IllegalStateException("Algorithm/Padding should exist and accept an IV.", ex);
    }
}

From source file:tv.ouya.sample.game.OptionsActivity.java

private void requestPurchase(final Options.Level level)
        throws GeneralSecurityException, JSONException, UnsupportedEncodingException {
    final String productId = getProductIdForLevel(level);

    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", productId);
    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 ww  .  j a va 2  s.  c  om
    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, mPublicKey);
    byte[] encryptedKey = cipher.doFinal(keyBytes);

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

    synchronized (mOutstandingPurchaseRequests) {
        mOutstandingPurchaseRequests.put(uniqueId, productId);
    }
    mOuyaFacade.requestPurchase(purchasable, new OuyaResponseListener<String>() {
        @Override
        public void onSuccess(String result) {
            String responseProductId;
            try {
                OuyaEncryptionHelper helper = new OuyaEncryptionHelper();

                JSONObject response = new JSONObject(result);
                String responseUUID = helper.decryptPurchaseResponse(response, mPublicKey);
                synchronized (mOutstandingPurchaseRequests) {
                    responseProductId = mOutstandingPurchaseRequests.remove(responseUUID);
                }
                if (responseProductId == null || !responseProductId.equals(productId)) {
                    onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS,
                            "Purchased product is not the same as purchase request product", Bundle.EMPTY);
                    return;
                }
            } catch (JSONException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (ParseException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (IOException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            } catch (GeneralSecurityException e) {
                onFailure(OuyaErrorCodes.THROW_DURING_ON_SUCCESS, e.getMessage(), Bundle.EMPTY);
                return;
            }

            if (responseProductId.equals(getProductIdForLevel(level))) {
                setNeedsPurchaseText(levelToRadioButton.get(level), false);
                Toast.makeText(OptionsActivity.this, "Level purchased!", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(int errorCode, String errorMessage, Bundle optionalData) {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this,
                    "Error making purchase!\n\nError " + errorCode + "\n" + errorMessage + ")",
                    Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancel() {
            levelToRadioButton.get(FREEDOM).setChecked(true);
            Toast.makeText(OptionsActivity.this, "You cancelled the purchase!", Toast.LENGTH_LONG).show();
        }
    });
}

From source file:com.example.android.vault.EncryptedDocument.java

/**
 * Read and decrypt the section starting at the current file offset.
 * Validates MAC of decrypted data, throwing if mismatch. When finished,
 * file offset is at the end of the entire section.
 *//*  ww w. j a  v  a  2s.c om*/
private void readSection(RandomAccessFile f, OutputStream out) throws IOException, GeneralSecurityException {
    final long start = f.getFilePointer();

    final Section section = new Section();
    section.read(f);

    final IvParameterSpec ivSpec = new IvParameterSpec(section.iv);
    mCipher.init(Cipher.DECRYPT_MODE, mDataKey, ivSpec);
    mMac.init(mMacKey);

    byte[] inbuf = new byte[8192];
    byte[] outbuf;
    int n;
    while ((n = f.read(inbuf, 0, (int) Math.min(section.length, inbuf.length))) != -1) {
        section.length -= n;
        mMac.update(inbuf, 0, n);
        outbuf = mCipher.update(inbuf, 0, n);
        if (outbuf != null) {
            out.write(outbuf);
        }
        if (section.length == 0)
            break;
    }

    section.assertMac(mMac.doFinal());

    outbuf = mCipher.doFinal();
    if (outbuf != null) {
        out.write(outbuf);
    }
}

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

@Override
public byte[] encryptData(byte[] plaintext, SecretKey encryptionKey, SecretKey hmacKey)
        throws CryptorException {

    Validate.notNull(plaintext, "Plaintext cannot be null.");
    Validate.notNull(encryptionKey, "Encryption key cannot be null.");
    Validate.notNull(hmacKey, "HMAC key cannot be null.");

    byte[] iv = getSecureRandomData(AES_BLOCK_SIZE);

    try {//  ww w . j  a  va2s .com
        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(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:io.syndesis.rest.v1.state.ClientSideState.java

static byte[] encrypt(final String encryptionAlgorithm, final byte[] iv, final byte[] clear,
        final SecretKey encryptionKey) {
    try {/* w  w  w.j  a  va  2  s  .co m*/
        final Cipher cipher = Cipher.getInstance(encryptionAlgorithm);

        cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(iv));

        return cipher.doFinal(clear);
    } catch (final GeneralSecurityException e) {
        throw new IllegalStateException("Unable to encrypt the given value", e);
    }
}

From source file:org.primaresearch.web.gwt.server.UserServiceImpl.java

/**
 * Decrypt data (AES encryption) //w w  w  .ja  v  a 2s .c o m
 * @param msgBase64 - Initialisation vector + encrypted data, base64 encoded
 * @return Decrypted data
 */
private String decrypt(String msgBase64, String key) {

    final String PHP_CHAR_ENCODING = encryptionCharEncoding; //Character encoding used for encryption
    final int IV_LENGTH = 16; //Length of initialisation vector (vector required for encryption/decryption)
    Base64 base64 = new org.apache.commons.codec.binary.Base64();

    String decryptedData = null;
    try {
        byte[] msgBytes = base64.decode(msgBase64.getBytes()); //Decode base64
        String m = new String(msgBytes, PHP_CHAR_ENCODING);

        //Split into initialisation vector and encrypted data
        String initialVectorString = m.substring(0, IV_LENGTH);
        String encryptedData = m.substring(IV_LENGTH);

        //byte[] initialVectorBytes = initialVectorString.getBytes();
        byte[] initialVectorBytes = initialVectorString.getBytes(PHP_CHAR_ENCODING);
        byte[] encryptedDataBytes = encryptedData.getBytes(PHP_CHAR_ENCODING);

        //Decrypt
        String md5key = md5(key);
        SecretKeySpec skeySpec = new SecretKeySpec(md5key.getBytes(), "AES");
        IvParameterSpec initialVector = new IvParameterSpec(initialVectorBytes);
        Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, initialVector);
        byte[] decryptedByteArray = cipher.doFinal(encryptedDataBytes);

        decryptedData = new String(decryptedByteArray, PHP_CHAR_ENCODING);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return decryptedData;

}

From source file:egovframework.com.ext.jfile.security.service.CipherServiceImpl.java

/**
 *  ? ? close      . /*from   w  w w. j  a  v  a  2  s  . c  o m*/
 * @param in  
 * @param out  
 * @param isStreamClose close 
 * @throws NoSuchAlgorithmException  ? ?  ?  
 * @throws InvalidKeyException ?  ? key ?  
 * @throws IOException /  
 * @throws IllegalBlockSizeException ?  ? ? ?  
 * @throws NoSuchPaddingException   ?  ?  
 * @throws BadPaddingException ?  ? 
 * @throws InvalidKeySpecException ?  ? keySpec ?  
 * @throws InvalidAlgorithmParameterException  ?  ? ? 
 */
private void decrypt(InputStream in, OutputStream out, boolean isStreamClose) throws NoSuchAlgorithmException,
        InvalidKeyException, IOException, IllegalBlockSizeException, NoSuchPaddingException,
        BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(jcrypto.getAlgorithm());
    if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES);
        cipher.init(Cipher.DECRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec);
    } else {
        cipher.init(Cipher.DECRYPT_MODE, generateKey(JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()),
                this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()));
    }

    byte[] buffer = new byte[2048];
    int bytesRead;
    while ((bytesRead = in.read(buffer)) != -1) {
        out.write(cipher.update(buffer, 0, bytesRead));
    }

    out.write(cipher.doFinal());
    out.flush();
    if (isStreamClose) {
        in.close();
        out.close();
    }
}

From source file:com.microsoft.azure.storage.queue.QueueEncryptionPolicy.java

/**
 * Returns a plain text message given an encrypted message.
 * //from   w  w  w .  j a v a2s .  co m
 * @param inputMessage
 *            The encrypted message.
 * @param requireEncryption
 *          A value to indicate that the data read from the server should be encrypted.
 * @return The plain text message bytes.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
byte[] decryptMessage(String inputMessage, Boolean requireEncryption) throws StorageException {
    Utility.assertNotNull("inputMessage", inputMessage);

    try {
        CloudQueueEncryptedMessage encryptedMessage = CloudQueueEncryptedMessage.deserialize(inputMessage);

        if (requireEncryption != null && requireEncryption && encryptedMessage.getEncryptionData() == null) {
            throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                    SR.ENCRYPTION_DATA_NOT_PRESENT_ERROR, null);
        }

        if (encryptedMessage.getEncryptionData() != null) {
            EncryptionData encryptionData = encryptedMessage.getEncryptionData();

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

            // Throw if the encryption protocol on the message 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);
            }

            // 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);
            }

            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);
                }
            }

            switch (encryptionData.getEncryptionAgent().getEncryptionAlgorithm()) {
            case AES_CBC_256:

                Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");

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

                byte[] src = Base64.decode(encryptedMessage.getEncryptedMessageContents());
                return myAes.doFinal(src, 0, src.length);

            default:
                throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR,
                        SR.INVALID_ENCRYPTION_ALGORITHM, null);
            }
        } else {
            return Base64.decode(encryptedMessage.getEncryptedMessageContents());
        }
    } catch (StorageException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new StorageException(StorageErrorCodeStrings.DECRYPTION_ERROR, SR.DECRYPTION_LOGIC_ERROR, ex);
    }
}

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

/**
 * Returns the decrypted plaintext.//from   w w  w.j  a  v a2  s .co m
 *
 * @param protectedValue the cipher text read from the {@code nifi.properties} file
 * @return the raw value to be used by the application
 * @throws SensitivePropertyProtectionException if there is an error decrypting the cipher text
 */
@Override
public String unprotect(String protectedValue) throws SensitivePropertyProtectionException {
    if (protectedValue == null || protectedValue.trim().length() < MIN_CIPHER_TEXT_LENGTH) {
        throw new IllegalArgumentException(
                "Cannot decrypt a cipher text shorter than " + MIN_CIPHER_TEXT_LENGTH + " chars");
    }

    if (!protectedValue.contains(DELIMITER)) {
        throw new IllegalArgumentException("The cipher text does not contain the delimiter " + DELIMITER
                + " -- it should be of the form Base64(IV) || Base64(cipherText)");
    }

    protectedValue = protectedValue.trim();

    final String IV_B64 = protectedValue.substring(0, protectedValue.indexOf(DELIMITER));
    byte[] iv = Base64.decode(IV_B64);
    if (iv.length < IV_LENGTH) {
        throw new IllegalArgumentException(
                "The IV (" + iv.length + " bytes) must be at least " + IV_LENGTH + " bytes");
    }

    String CIPHERTEXT_B64 = protectedValue.substring(protectedValue.indexOf(DELIMITER) + 2);

    // Restore the = padding if necessary to reconstitute the GCM MAC check
    if (CIPHERTEXT_B64.length() % 4 != 0) {
        final int paddedLength = CIPHERTEXT_B64.length() + 4 - (CIPHERTEXT_B64.length() % 4);
        CIPHERTEXT_B64 = StringUtils.rightPad(CIPHERTEXT_B64, paddedLength, '=');
    }

    try {
        byte[] cipherBytes = Base64.decode(CIPHERTEXT_B64);

        cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(iv));
        byte[] plainBytes = cipher.doFinal(cipherBytes);
        logger.info(getName() + " decrypted a sensitive value successfully");
        return new String(plainBytes, StandardCharsets.UTF_8);
    } catch (BadPaddingException | IllegalBlockSizeException | DecoderException
            | InvalidAlgorithmParameterException | InvalidKeyException e) {
        final String msg = "Error decrypting a protected value";
        logger.error(msg, e);
        throw new SensitivePropertyProtectionException(msg, e);
    }
}