Example usage for javax.crypto KeyGenerator getInstance

List of usage examples for javax.crypto KeyGenerator getInstance

Introduction

In this page you can find the example usage for javax.crypto KeyGenerator getInstance.

Prototype

public static final KeyGenerator getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyGenerator object that generates secret keys for the specified algorithm.

Usage

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

/**
 * Return an encrypted base64 encoded message along with encryption related metadata given a plain text message.
 * //w  ww .j  av  a2s.c  o m
 * @param inputMessage
 *            The input message in bytes.
 * @return The encrypted message that will be uploaded to the service.
 * @throws StorageException
 *             An exception representing any error which occurred during the operation.
 */
String encryptMessage(byte[] inputMessage) throws StorageException {
    Utility.assertNotNull("inputMessage", inputMessage);

    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    CloudQueueEncryptedMessage encryptedMessage = new CloudQueueEncryptedMessage();
    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptedMessage.setEncryptedMessageContents(
                new String(Base64.encode(myAes.doFinal(inputMessage, 0, inputMessage.length))));

        encryptionData.setContentEncryptionIV(myAes.getIV());
        encryptedMessage.setEncryptionData(encryptionData);
        return encryptedMessage.serialize();
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:com.keybox.manage.util.KeyStoreUtil.java

/**
 * create new keystore// w  w w  .java  2 s  .com
 */
private static void initializeKeyStore() {
    try {
        keyStore = KeyStore.getInstance("JCEKS");
        //create keystore
        keyStore.load(null, KEYSTORE_PASS);

        //set encryption key
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        KeyStoreUtil.setSecret(KeyStoreUtil.ENCRYPTION_KEY_ALIAS, keyGenerator.generateKey().getEncoded());

        //write keystore
        FileOutputStream fos = new FileOutputStream(keyStoreFile);
        keyStore.store(fos, KEYSTORE_PASS);
        fos.close();
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }
}

From source file:org.pentaho.di.trans.steps.symmetriccrypto.symmetricalgorithm.SymmetricCrypto.java

public byte[] generateKey(int keySize) throws CryptoKeyException {
    try {//w  ww  .  j  a va2 s. c  o  m
        // Get a key generator for algorithm
        KeyGenerator kg = KeyGenerator.getInstance(meta.getAlgorithm());
        // SecureRandom random = new SecureRandom();
        kg.init(keySize);
        // Use it to generate a key
        SecretKey secretKey = kg.generateKey();

        return secretKey.getEncoded();

    } catch (Exception e) {
        throw new CryptoKeyException(e);
    }
}

From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java

@Override
public String generateKey(int keySize)
        throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
    LOG.info("Generating a new encryption key of size " + keySize);
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(keySize);//from w  w w .  j ava 2s.c o m
    SecretKey secretKey = keyGen.generateKey();
    return new String(Base64.encode(secretKey.getEncoded()), "UTF-8");
}

From source file:com.wabacus.util.DesEncryptTools.java

public static boolean createEncryptKey(File file) {
    SecretKey deskey = null;//ww  w  .j a v a 2s  .co  m
    try {
        KeyGenerator keygen = KeyGenerator.getInstance("DESede");
        deskey = keygen.generateKey();
    } catch (NoSuchAlgorithmException e) {
        throw new WabacusConfigLoadingException("?", e);
    }
    if (deskey == null)
        return false;
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;
    try {
        fos = new FileOutputStream(file);
        oos = new ObjectOutputStream(fos);
        oos.writeObject(deskey);
    } catch (FileNotFoundException e) {
        throw new WabacusConfigLoadingException(
                "?" + file.getPath(), e);
    } catch (IOException e) {
        throw new WabacusConfigLoadingException(
                "?" + file.getPath() + "", e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        try {
            if (oos != null)
                oos.close();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}

From source file:org.dhatim.dropwizard.jwt.cookie.authentication.JwtCookieAuthBundle.java

private static KeyGenerator getHmacSha256KeyGenerator() {
    try {//from  w  ww. j  a va2s . com
        return KeyGenerator.getInstance(HS256.getJcaName());
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(e);
    }
}

From source file:org.openintents.safe.CryptoHelper.java

/**
 * @return null if failure, otherwise hex string version of key
 * @author Isaac Potoczny-Jones//from ww w. j  a  va2  s. co  m
 */
public static String generateMasterKey() throws NoSuchAlgorithmException {
    try {
        KeyGenerator keygen;
        keygen = KeyGenerator.getInstance("AES");
        keygen.init(256);
        SecretKey genDesKey = keygen.generateKey();
        return toHexString(genDesKey.getEncoded());
    } catch (NoSuchAlgorithmException e) {
        Log.e(TAG, "generateMasterKey(): " + e.toString());
        throw e;
    }
}

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

/**
 * Return an encrypted entity. This method is used for encrypting entity properties.
 *//*from w ww.  j a  v  a  2s  . c o  m*/
Map<String, EntityProperty> encryptEntity(Map<String, EntityProperty> properties, String partitionKey,
        String rowKey, EncryptionResolver encryptionResolver) throws StorageException {
    Utility.assertNotNull("properties", properties);

    // The Key should be set on the policy for encryption. Otherwise, throw an error.
    if (this.keyWrapper == null) {
        throw new IllegalArgumentException(SR.KEY_MISSING);
    }

    EncryptionData encryptionData = new EncryptionData();
    encryptionData.setEncryptionAgent(new EncryptionAgent(Constants.EncryptionConstants.ENCRYPTION_PROTOCOL_V1,
            EncryptionAlgorithm.AES_CBC_256));

    try {
        Map<String, EntityProperty> encryptedProperties = new HashMap<String, EntityProperty>();
        HashSet<String> encryptionPropertyDetailsSet = new HashSet<String>();

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);

        Cipher myAes = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKey aesKey = keyGen.generateKey();
        myAes.init(Cipher.ENCRYPT_MODE, aesKey);

        // Wrap key
        Pair<byte[], String> encryptedKey = this.keyWrapper
                .wrapKeyAsync(aesKey.getEncoded(), null /* algorithm */).get();
        encryptionData.setWrappedContentKey(new WrappedContentKey(this.keyWrapper.getKid(),
                encryptedKey.getKey(), encryptedKey.getValue()));

        encryptionData.setContentEncryptionIV(myAes.getIV());

        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        for (Map.Entry<String, EntityProperty> kvp : properties.entrySet()) {
            if (encryptionResolver != null
                    && encryptionResolver.encryptionResolver(partitionKey, rowKey, kvp.getKey())) {
                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity case
                // where a user adds a new property as follows - ent.Properties.Add("foo2", null);
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                kvp.getValue().setIsEncrypted(true);
            }

            // IsEncrypted is set to true when either the EncryptPropertyAttribute is set on a property or when it is 
            // specified in the encryption resolver or both.
            if (kvp.getValue() != null && kvp.getValue().isEncrypted()) {
                // Throw if users try to encrypt non-string properties.
                if (kvp.getValue().getEdmType() != EdmType.STRING) {
                    throw new IllegalArgumentException(String
                            .format(SR.UNSUPPORTED_PROPERTY_TYPE_FOR_ENCRYPTION, kvp.getValue().getEdmType()));
                }

                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.ENCRYPT_MODE, aesKey, new IvParameterSpec(columnIV));

                // Throw if users try to encrypt null properties. This could happen in the DynamicTableEntity or POCO
                // case when the property value is null.
                if (kvp.getValue() == null) {
                    throw new IllegalArgumentException(SR.ENCRYPTING_NULL_PROPERTIES_NOT_ALLOWED);
                }

                byte[] src = kvp.getValue().getValueAsString().getBytes(Constants.UTF8_CHARSET);
                byte[] dest = myAes.doFinal(src, 0, src.length);

                // Store the encrypted properties as binary values on the service instead of base 64 encoded strings because strings are stored as a sequence of 
                // WCHARs thereby further reducing the allowed size by half. During retrieve, it is handled by the response parsers correctly 
                // even when the service does not return the type for JSON no-metadata.
                encryptedProperties.put(kvp.getKey(), new EntityProperty(dest));
                encryptionPropertyDetailsSet.add(kvp.getKey());
            } else {
                encryptedProperties.put(kvp.getKey(), kvp.getValue());
            }

            // Encrypt the property details set and add it to entity properties.
            byte[] metadataIVFull = digest.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);
            myAes.init(Cipher.ENCRYPT_MODE, aesKey, new IvParameterSpec(metadataIV));

            byte[] src = Arrays.toString(encryptionPropertyDetailsSet.toArray())
                    .getBytes(Constants.UTF8_CHARSET);
            byte[] dest = myAes.doFinal(src, 0, src.length);
            encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_PROPERTY_DETAILS,
                    new EntityProperty(dest));
        }

        encryptedProperties.put(Constants.EncryptionConstants.TABLE_ENCRYPTION_KEY_DETAILS,
                new EntityProperty(encryptionData.serialize()));

        return encryptedProperties;
    } catch (Exception e) {
        throw StorageException.translateClientException(e);
    }
}

From source file:com.qubit.solution.fenixedu.bennu.webservices.services.client.WebServiceClientHandler.java

private static byte[] generateAESKey() throws NoSuchAlgorithmException {
    KeyGenerator generator;//  w  w  w.ja  v a 2s . co m
    try {
        generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        return generator.generateKey().getEncoded();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.kuali.rice.core.impl.encryption.DemonstrationGradeEncryptionServiceImpl.java

private SecretKey unwrapEncodedKey(String key) throws Exception {
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey desKey = keygen.generateKey();

    // Create the cipher
    Cipher cipher = Cipher.getInstance(ALGORITHM);
    cipher.init((Cipher.UNWRAP_MODE), desKey);

    byte[] bytes = Base64.decodeBase64(key.getBytes());

    SecretKeyFactory desFactory = SecretKeyFactory.getInstance("DES");

    DESKeySpec keyspec = new DESKeySpec(bytes);
    SecretKey k = desFactory.generateSecret(keyspec);

    return k;/*from w  w  w . ja  va 2s  .c o  m*/

}