Example usage for javax.crypto Cipher getIV

List of usage examples for javax.crypto Cipher getIV

Introduction

In this page you can find the example usage for javax.crypto Cipher getIV.

Prototype

public final byte[] getIV() 

Source Link

Document

Returns the initialization vector (IV) in a new buffer.

Usage

From source file:it.doqui.index.ecmengine.business.personalization.encryption.CryptoTransformationSpec.java

public static byte[] generateIv(CryptoTransformationSpec spec, SecretKey key) {
    logger.debug("[CryptoTransformationSpec::generateIv] BEGIN");
    try {/*from ww  w.java  2s . com*/
        Cipher cipher = null;
        byte[] iv = null;

        try {
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(spec), "SunJCE");
        } catch (NoSuchProviderException e) {
            logger.warn("[CryptoTransformationSpec::generateIv] Unknown provider \"SunJCE\". Using default...");
            cipher = Cipher.getInstance(CryptoTransformationSpec.buildTransformationString(spec));
        }

        cipher.init(Cipher.ENCRYPT_MODE, key);

        iv = cipher.getIV();

        return iv;
    } catch (NoSuchPaddingException e) {
        logger.warn("[CryptoTransformationSpec::generateIv] Invalid padding: " + spec.getPadding());
        throw new EncryptionRuntimeException("Invalid padding: " + spec.getPadding(), e);
    } catch (NoSuchAlgorithmException e) {
        logger.warn("[CryptoTransformationSpec::generateIv] Invalid algorithm: " + spec.getAlgorithm());
        throw new EncryptionRuntimeException("Invalid algorithm: " + spec.getAlgorithm(), e);
    } catch (InvalidKeyException e) {
        logger.warn("[CryptoTransformationSpec::generateIv] Invalid key!");
        throw new EncryptionRuntimeException("Invalid key!", e);
    } finally {
        logger.debug("[CryptoTransformationSpec::generateIv] END");
    }
}

From source file:org.mozilla.android.sync.crypto.Cryptographer.java

/**
 * @param info CryptoInfo to be encrypted
 * @return encrypted CryptoInfo//  www. j  a  v a  2 s .c  om
 * @throws CryptoException on error
 */
public static CryptoInfo encrypt(CryptoInfo info) throws CryptoException {

    Cipher cipher = getCipher();
    try {
        byte[] encryptionKey = info.getKeys().getEncryptionKey();
        SecretKeySpec spec = new SecretKeySpec(encryptionKey, KEY_ALGORITHM_SPEC);

        // If no IV is provided, we allow the cipher to provide one.
        if (info.getIV() == null || info.getIV().length == 0) {
            cipher.init(Cipher.ENCRYPT_MODE, spec);
        } else {
            System.out.println("IV is " + info.getIV().length);
            cipher.init(Cipher.ENCRYPT_MODE, spec, new IvParameterSpec(info.getIV()));
        }
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(ex);
    }

    // Encrypt.
    byte[] encryptedBytes = commonCrypto(cipher, info.getMessage());
    info.setMessage(encryptedBytes);

    // Save IV.
    info.setIV(cipher.getIV());

    // Generate HMAC.
    info.setHMAC(generateHMAC(info));

    return info;

}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Encrypt private key with symmetric AES encryption, GCM mode mode and no padding
 *
 * @param privateKey byte64 encoded string representation of private key
 * @param keyPhrase  key used for encryption, e.g. 12 random words
 *                   {@link EncryptionUtils#getRandomWords(int, Context)}
 * @return encrypted string, bytes first encoded base64, IV separated with "|", then to string
 *//*w w w.j  av  a  2s . c  om*/
public static String encryptPrivateKey(String privateKey, String keyPhrase)
        throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException {
    Cipher cipher = Cipher.getInstance(AES_CIPHER);

    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] salt = randomBytes(saltLength);
    KeySpec spec = new PBEKeySpec(keyPhrase.toCharArray(), salt, iterationCount, keyStrength);
    SecretKey tmp = factory.generateSecret(spec);
    SecretKeySpec key = new SecretKeySpec(tmp.getEncoded(), AES);

    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] bytes = encodeStringToBase64Bytes(privateKey);
    byte[] encrypted = cipher.doFinal(bytes);

    byte[] iv = cipher.getIV();
    String encodedIV = encodeBytesToBase64String(iv);
    String encodedSalt = encodeBytesToBase64String(salt);
    String encodedEncryptedBytes = encodeBytesToBase64String(encrypted);

    return encodedEncryptedBytes + ivDelimiter + encodedIV + ivDelimiter + encodedSalt;
}

From source file:com.bamboocloud.im.provisioner.json.crypto.simple.SimpleEncryptor.java

/**
 * Encrypts with a symmetric cipher./*  w  w w . j  av  a  2s  .  c om*/
 *
 * @param value the value to be encrypted.
 * @return the encrypted value.
 * @throws GeneralSecurityException if a cryptographic operation failed.
 * @throws IOException if an I/O exception occurred.
 */
private Object symmetric(Object object) throws GeneralSecurityException, IOException {
    Cipher symmetric = Cipher.getInstance(cipher);
    symmetric.init(Cipher.ENCRYPT_MODE, key);
    String data = Base64.encodeBase64String(symmetric.doFinal(mapper.writeValueAsBytes(object)));
    byte[] iv = symmetric.getIV();
    HashMap<String, Object> result = new HashMap<String, Object>();
    result.put("cipher", this.cipher);
    result.put("key", this.alias);
    result.put("data", data);
    if (iv != null) {
        result.put("iv", Base64.encodeBase64String(iv));
    }
    return result;
}

From source file:io.personium.core.model.file.DataCryptorTest.java

/**
 * Test encode().//  ww  w  .jav a  2  s .  c  om
 * normal.
 * @throws Exception Unexpected error.
 */
@Test
public void encode_Normal() throws Exception {
    // --------------------
    // Test method args
    // --------------------
    String str = "0123456789";
    InputStream input = new ByteArrayInputStream(str.getBytes(CharEncoding.UTF_8));

    // --------------------
    // Mock settings
    // --------------------
    // Nothing.

    // --------------------
    // Expected result
    // --------------------
    // Nothing.

    // --------------------
    // Run method
    // --------------------
    DataCryptor cryptor = new DataCryptor("zyxwvutsrqponmlk");
    CipherInputStream encodedInputStream = null;
    encodedInputStream = (CipherInputStream) cryptor.encode(input, true);

    // --------------------
    // Confirm result
    // --------------------
    Field field = FilterInputStream.class.getDeclaredField("in");
    field.setAccessible(true);
    InputStream actualInput = (InputStream) field.get(encodedInputStream);

    assertThat(actualInput, is(input));

    field = CipherInputStream.class.getDeclaredField("cipher");
    field.setAccessible(true);
    Cipher actualCipher = (Cipher) field.get(encodedInputStream);
    byte[] expectedIV = "klmnopqrstuvwxyz".getBytes(CharEncoding.UTF_8);
    String expectedAlgorithm = "AES/CBC/PKCS5Padding";

    assertThat(actualCipher.getIV(), is(expectedIV));
    assertThat(actualCipher.getAlgorithm(), is(expectedAlgorithm));
}

From source file:io.personium.core.model.file.DataCryptorTest.java

/**
 * Test decode()./*from  w ww  .  j av  a2 s. c  o  m*/
 * normal.
 * @throws Exception Unexpected error.
 */
@Test
public void decode_Normal() throws Exception {
    // --------------------
    // Test method args
    // --------------------
    String str = "0123456789";
    InputStream input = new ByteArrayInputStream(str.getBytes(CharEncoding.UTF_8));

    // --------------------
    // Mock settings
    // --------------------
    // Nothing.

    // --------------------
    // Expected result
    // --------------------
    // Nothing.

    // --------------------
    // Run method
    // --------------------
    DataCryptor cryptor = new DataCryptor("zyxwvutsrqponmlk");
    CipherInputStream encodedInputStream = null;
    encodedInputStream = (CipherInputStream) cryptor.decode(input, DataCryptor.ENCRYPTION_TYPE_AES);

    // --------------------
    // Confirm result
    // --------------------
    Field field = FilterInputStream.class.getDeclaredField("in");
    field.setAccessible(true);
    InputStream actualInput = (InputStream) field.get(encodedInputStream);

    assertThat(actualInput, is(input));

    field = CipherInputStream.class.getDeclaredField("cipher");
    field.setAccessible(true);
    Cipher actualCipher = (Cipher) field.get(encodedInputStream);
    byte[] expectedIV = "klmnopqrstuvwxyz".getBytes(CharEncoding.UTF_8);
    String expectedAlgorithm = "AES/CBC/PKCS5Padding";

    assertThat(actualCipher.getIV(), is(expectedIV));
    assertThat(actualCipher.getAlgorithm(), is(expectedAlgorithm));
}

From source file:org.apache.nifi.provenance.AESProvenanceEventEncryptor.java

/**
 * Encrypts the provided {@link ProvenanceEventRecord}, serialized to a byte[] by the RecordWriter.
 *
 * @param plainRecord the plain record, serialized to a byte[]
 * @param recordId    an identifier for this record (eventId, generated, etc.)
 * @param keyId       the ID of the key to use
 * @return the encrypted record//  w  w  w  .  ja  v a  2  s  .  c  om
 * @throws EncryptionException if there is an issue encrypting this record
 */
@Override
public byte[] encrypt(byte[] plainRecord, String recordId, String keyId) throws EncryptionException {
    if (plainRecord == null || CryptoUtils.isEmpty(keyId)) {
        throw new EncryptionException("The provenance record and key ID cannot be missing");
    }

    if (keyProvider == null || !keyProvider.keyExists(keyId)) {
        throw new EncryptionException("The requested key ID is not available");
    } else {
        byte[] ivBytes = new byte[IV_LENGTH];
        new SecureRandom().nextBytes(ivBytes);
        try {
            logger.debug("Encrypting provenance record " + recordId + " with key ID " + keyId);
            Cipher cipher = initCipher(EncryptionMethod.AES_GCM, Cipher.ENCRYPT_MODE, keyProvider.getKey(keyId),
                    ivBytes);
            ivBytes = cipher.getIV();

            // Perform the actual encryption
            byte[] cipherBytes = cipher.doFinal(plainRecord);

            // Serialize and concat encryption details fields (keyId, algo, IV, version, CB length) outside of encryption
            EncryptionMetadata metadata = new EncryptionMetadata(keyId, ALGORITHM, ivBytes, VERSION,
                    cipherBytes.length);
            byte[] serializedEncryptionMetadata = serializeEncryptionMetadata(metadata);

            // Add the sentinel byte of 0x01
            logger.debug("Encrypted provenance event record " + recordId + " with key ID " + keyId);
            return CryptoUtils.concatByteArrays(SENTINEL, serializedEncryptionMetadata, cipherBytes);
        } catch (EncryptionException | BadPaddingException | IllegalBlockSizeException | IOException
                | KeyManagementException e) {
            final String msg = "Encountered an exception encrypting provenance record " + recordId;
            logger.error(msg, e);
            throw new EncryptionException(msg, e);
        }
    }
}

From source file:com.invariantproperties.sandbox.springentitylistener.service.EncryptorBean.java

/**
 * Encrypt string. We should use a container class to contain the ciphertext
 * and key but an array is good enough for testing.
 *///w ww. ja va  2  s. c o m
public String[] encryptString(String plaintext) {
    String ciphertext = null;
    String salt = null;

    if (plaintext != null) {
        try {
            // Encryptor encryptor = JavaEncryptor.getInstance();
            // CipherText ct = encryptor.encrypt(key, new
            // PlainText(plaintext));
            // ciphertext =
            // Base64.encodeBytes(ct.asPortableSerializedByteArray());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            ciphertext = Base64.encodeBytes(cipher.doFinal(plaintext.getBytes()));
            salt = Base64.encodeBytes(cipher.getIV());
        } catch (NoSuchAlgorithmException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (NoSuchPaddingException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (InvalidKeyException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (BadPaddingException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (IllegalBlockSizeException e) {
            // handle exception. Perhaps set value to null?
            System.out.println("decryption exception: " + e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace(System.out);
        }
    }

    return new String[] { ciphertext, salt };
}

From source file:cn.ctyun.amazonaws.services.s3.internal.crypto.EncryptionUtils.java

private static void updateMetadata(ObjectMetadata metadata, byte[] keyBytesToStoreInMetadata,
        Cipher symmetricCipher, Map<String, String> materialsDescription) {
    // If we generated a symmetric key to encrypt the data, store it in the object metadata.
    if (keyBytesToStoreInMetadata != null) {
        keyBytesToStoreInMetadata = Base64.encodeBase64(keyBytesToStoreInMetadata);
        metadata.addUserMetadata(Headers.CRYPTO_KEY, new String(keyBytesToStoreInMetadata));
    }/*from  w  w  w  .j  a  v a  2 s .  co m*/

    // Put the cipher initialization vector (IV) into the object metadata
    byte[] initVectorBytes = symmetricCipher.getIV();
    initVectorBytes = Base64.encodeBase64(initVectorBytes);
    metadata.addUserMetadata(Headers.CRYPTO_IV, new String(initVectorBytes));

    // Put the materials description into the object metadata as JSON
    JSONObject descriptionJSON = new JSONObject(materialsDescription);
    metadata.addUserMetadata(Headers.MATERIALS_DESCRIPTION, descriptionJSON.toString());
}

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

public Item encrypt(Item item, SecretKeySpec key, String... attributes) {
    try {//from   w  w w .  j a  va  2s .  co  m
        if (key != null) {
            Cipher cipher = Cipher.getInstance(transformation);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] iv = cipher.getIV();
            for (String attribute : attributes) {
                byte[] value = item.getBinary(attribute);
                item.withBinary(attribute, cipher.doFinal(value));
            }
            item.withMap("cipher", new LinkedHashMap());
            item.getMap("cipher").put("transformation", transformation);
            item.getMap("cipher").put("iv", iv);
        }
        return item;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        throw new RuntimeException(ex);
    }
}