Example usage for javax.crypto KeyGenerator init

List of usage examples for javax.crypto KeyGenerator init

Introduction

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

Prototype

public final void init(int keysize, SecureRandom random) 

Source Link

Document

Initializes this key generator for a certain keysize, using a user-provided source of randomness.

Usage

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

protected final SecretKey generateCEK() {
    KeyGenerator generator;
    try {/*from   w ww . j av a2s  .  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.
 * //w  ww  . j av a2s  .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:org.apache.pdfbox.pdmodel.encryption.PublicKeySecurityHandler.java

/**
 * Prepare the document for encryption./*from   w  w w. j  a v  a2 s .c  o  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:org.apache.usergrid.persistence.Schema.java

private static byte[] getRawKey(byte[] seed) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
    sr.setSeed(seed);//from  w  w  w.j a  va2s  .  com
    keyGenerator.init(128, sr); // 192 and 256 bits may not be available
    SecretKey secretKey = keyGenerator.generateKey();
    return secretKey.getEncoded();
}

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

public void initSessionKey() throws NoSuchAlgorithmException {
    KeyGenerator kg = KeyGenerator.getInstance("AES");
    kg.init(256, new SecureRandom());
    sessionKey = kg.generateKey();//  w  w  w  . ja  v a  2  s  .  c  o m
}