Example usage for javax.crypto KeyGenerator generateKey

List of usage examples for javax.crypto KeyGenerator generateKey

Introduction

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

Prototype

public final SecretKey generateKey() 

Source Link

Document

Generates a secret key.

Usage

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

private Key getInitializationVector(CryptoWrapperBuilder builder) throws NoSuchAlgorithmException {

    KeyGenerator generator = KeyGenerator.getInstance(builder.cipherName);
    generator.init(CryptoWrapper.AES_BLOCK_SIZE_IN_BITS, new SecureRandom());
    return generator.generateKey();
}

From source file:it.scoppelletti.security.keygen.KeyGeneratorBean.java

/**
 * Esegue l’operazione.//w  w  w . ja  va 2  s  . c  o  m
 */
public void run() {
    Properties props;
    OutputStream out = null;
    Key key;
    KeyGenerator keyGen;

    if (myConfigFile == null) {
        throw new PropertyNotSetException(toString(), "configFile");
    }

    try {
        props = loadConfig();
        out = openOutput();
        if (out == null) {
            return;
        }

        keyGen = CryptoUtils.getKeyGenerator(props, myPrefix);
        key = keyGen.generateKey();

        props = CryptoUtils.toProperties(key, myEncoded);
        props.store(out, null);
    } catch (IOException ex) {
        throw new IOOperationException(ex);
    } finally {
        if (out != null && myOutputFile != null) {
            IOUtils.close(out);
            out = null;
        }
    }
}

From source file:com.amazonaws.services.s3.internal.crypto.S3CryptoModuleBase.java

protected final SecretKey generateCEK() {
    KeyGenerator generator;
    try {/*from www .j a v a2  s  .  c  o m*/
        generator = KeyGenerator.getInstance(contentCryptoScheme.getKeyGeneratorAlgorithm());
        generator.init(contentCryptoScheme.getKeyLengthInBits(), cryptoScheme.getSecureRandom());
        return generator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to generate envelope symmetric key:" + e.getMessage(), e);
    }
}

From source file:com.diona.fileReader.CipherUtil.java

/**
 * Generates a random Base64 encoded string value.
 * /*from   ww  w .  j  a v a  2 s. co  m*/
 * @param length
 *          The length of the key.
 * @return A random key value.
 */
public byte[] generateRandomKeyBytes(final int length) {
    byte[] randomKey = null;

    // Use a SecureRandom generator
    try {
        final SecureRandom secureRandom = new SecureRandom();
        final KeyGenerator keyGenerator = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM);
        keyGenerator.init(length, secureRandom);
        final SecretKey secretKey = keyGenerator.generateKey();
        randomKey = secretKey.getEncoded();
    } catch (final NoSuchAlgorithmException e) {
        Log.e(TAG, "Exception generating random key", e);
    }

    return randomKey;
}

From source file:edu.stanford.junction.extra.Encryption.java

@Override
public boolean beforeActivityCreate() {
    try {/*  ww w .j  a  va 2  s . com*/
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        SecretKey skey = kgen.generateKey();

        mKey = skey.getEncoded();
        init();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return true;
}

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

/**
 * Prepare the document for encryption./*ww  w .  j a v  a  2  s. co  m*/
 *
 * @param doc The document that will be encrypted.
 *
 * @throws CryptographyException If there is an error while encrypting.
 */
public void prepareDocumentForEncryption(PDDocument doc) throws CryptographyException {

    try {
        Security.addProvider(new BouncyCastleProvider());

        PDEncryptionDictionary dictionary = doc.getEncryptionDictionary();
        if (dictionary == null) {
            dictionary = new PDEncryptionDictionary();
        }

        dictionary.setFilter(FILTER);
        dictionary.setLength(this.keyLength);
        dictionary.setVersion(2);

        // remove CF, StmF, and StrF entries that may be left from a previous encryption
        dictionary.removeV45filters();

        dictionary.setSubFilter(SUBFILTER);

        byte[][] recipientsField = new byte[policy.getRecipientsNumber()][];

        // create the 20 bytes seed

        byte[] seed = new byte[20];

        KeyGenerator key = KeyGenerator.getInstance("AES");
        key.init(192, new SecureRandom());
        SecretKey sk = key.generateKey();
        System.arraycopy(sk.getEncoded(), 0, seed, 0, 20); // create the 20 bytes seed

        Iterator it = policy.getRecipientsIterator();
        int i = 0;

        while (it.hasNext()) {
            PublicKeyRecipient recipient = (PublicKeyRecipient) it.next();
            X509Certificate certificate = recipient.getX509();
            int permission = recipient.getPermission().getPermissionBytesForPublicKey();

            byte[] pkcs7input = new byte[24];
            byte one = (byte) (permission);
            byte two = (byte) (permission >>> 8);
            byte three = (byte) (permission >>> 16);
            byte four = (byte) (permission >>> 24);

            System.arraycopy(seed, 0, pkcs7input, 0, 20); // put this seed in the pkcs7 input

            pkcs7input[20] = four;
            pkcs7input[21] = three;
            pkcs7input[22] = two;
            pkcs7input[23] = one;

            DERObject obj = createDERForRecipient(pkcs7input, certificate);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            DEROutputStream k = new DEROutputStream(baos);

            k.writeObject(obj);

            recipientsField[i] = baos.toByteArray();

            i++;
        }

        dictionary.setRecipients(recipientsField);

        int sha1InputLength = seed.length;

        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            sha1InputLength += string.getBytes().length;
        }

        byte[] sha1Input = new byte[sha1InputLength];

        System.arraycopy(seed, 0, sha1Input, 0, 20);

        int sha1InputOffset = 20;

        for (int j = 0; j < dictionary.getRecipientsLength(); j++) {
            COSString string = dictionary.getRecipientStringAt(j);
            System.arraycopy(string.getBytes(), 0, sha1Input, sha1InputOffset, string.getBytes().length);
            sha1InputOffset += string.getBytes().length;
        }

        MessageDigest md = MessageDigest.getInstance("SHA-1");

        byte[] mdResult = md.digest(sha1Input);

        this.encryptionKey = new byte[this.keyLength / 8];
        System.arraycopy(mdResult, 0, this.encryptionKey, 0, this.keyLength / 8);

        doc.setEncryptionDictionary(dictionary);
        doc.getDocument().setEncryptionDictionary(dictionary.encryptionDictionary);

    } catch (NoSuchAlgorithmException ex) {
        throw new CryptographyException(ex);
    } catch (NoSuchProviderException ex) {
        throw new CryptographyException(ex);
    } catch (Exception e) {
        LOG.error(e, e);
        throw new CryptographyException(e);
    }

}

From source file:io.kodokojo.bdd.stage.cluster.ClusterApplicationGiven.java

private void startRedis() {
    redisService = StageUtils.startDockerRedis(dockerTestSupport);
    KeyGenerator kg = null;
    try {//from   w w  w  .  j a v  a2 s  . c  o m
        kg = KeyGenerator.getInstance("AES");
        userStore = new RedisUserStore(kg.generateKey(), redisService.getHost(), redisService.getPort());
    } catch (NoSuchAlgorithmException e) {
        fail(e.getMessage());
    }
}

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 .ja  va 2s .c  om*/
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.aperigeek.dropvault.web.dao.MongoFileService.java

protected KeyStore getKeyStore(String username, char[] password) {
    try {//w  ww.j  a  va 2s .  c  o  m
        File keyStoreFile = new File(secretsFolder, username + ".jks");
        KeyStore keyStore = KeyStore.getInstance("JCEKS");
        if (keyStoreFile.exists()) {
            keyStore.load(new FileInputStream(keyStoreFile), password);
            return keyStore;
        } else {
            KeyGenerator gen = KeyGenerator.getInstance("Blowfish");
            SecretKey key = gen.generateKey();

            keyStore.load(null, password);
            keyStore.setEntry(username, new SecretKeyEntry(key), new KeyStore.PasswordProtection(password));

            keyStore.store(new FileOutputStream(keyStoreFile), password);

            return keyStore;
        }
    } catch (Exception ex) {
        // TODO: better exception handling
        Logger.getAnonymousLogger().log(Level.SEVERE, "ERROR", ex);
        throw new RuntimeException(ex);
    }
}

From source file:org.tolven.security.password.PasswordHolder.java

private void generateSecretKey(File secretKeyFile) {
    if (getSecretKeyFile().exists()) {
        throw new RuntimeException("A secretkey file already exists at: " + getSecretKeyFile().getPath());
    }/*  w  w  w  .  j  a  v  a2  s.com*/
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(112);
        secretKey = keyGenerator.generateKey();
        String alias = getKeyStore().aliases().nextElement();
        Certificate adminCert = getKeyStore().getCertificate(alias);
        PublicKey publicKey = adminCert.getPublicKey();
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] encryptedSecretKey = cipher.wrap(secretKey);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(secretKeyFile);
            out.write(Base64.encodeBase64(encryptedSecretKey));
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Could not generate secret key for file: " + secretKeyFile.getPath(), ex);
    }
}