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:org.mozilla.android.sync.Cryptographer.java

public static KeyBundle generateKeys() {
    KeyGenerator keygen;/* w w w  .ja  va 2  s . co  m*/
    try {
        keygen = KeyGenerator.getInstance(KEY_ALGORITHM_SPEC);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        return null;
    }

    keygen.init(KEY_SIZE);
    byte[] encryptionKey = keygen.generateKey().getEncoded();
    byte[] hmacKey = keygen.generateKey().getEncoded();
    return new KeyBundle(encryptionKey, hmacKey);
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static SecretKey generateSecretKey(String type, int size)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(type);
    keyGenerator.init(size);//from   ww  w . j a  va2s.co m
    return keyGenerator.generateKey();
}

From source file:com.hernandez.rey.crypto.TripleDES.java

/**
 * Generate a secret TripleDES encryption/decryption key
 * //from  ww w  . j a v  a 2  s . c om
 * @return the secret key generated
 * @throws NoSuchAlgorithmException
 */
public static SecretKey generateKey() throws NoSuchAlgorithmException {
    // Get a key generator for Triple DES (a.k.a DESede)
    final KeyGenerator keygen = KeyGenerator.getInstance("DESede");
    // Use it to generate a key
    return keygen.generateKey();
}

From source file:org.apache.abdera.security.util.KeyHelper.java

public static Key generateKey(String type) throws NoSuchAlgorithmException {
    KeyGenerator keygen = KeyGenerator.getInstance(type);
    keygen.init(new SecureRandom());
    return keygen.generateKey();
}

From source file:configuration.Key.java

/**
 * Creates a random key with the given parameters.
 * //from  w  w w . j av  a2 s  .com
 * @param keySize
 *            the length of the key in bits.
 * @param version
 *            the version of the key.
 * @param algorithm
 *            the string representation of the cipher or HMAC algorithm
 *            used.
 * @return the random key with the specified parameters or <code>null</code>
 *         , if the key cannot be generated.
 */
public static Key randomKey(int keySize, int version, String algorithm) {
    if (keySize < 1) {
        throw new IllegalArgumentException("keySize has to be at least one!");
    }
    if (version < 1) {
        throw new IllegalArgumentException("version must be at least one!");
    }
    if (algorithm == null) {
        throw new NullPointerException("algorithm may not be null!");
    }

    SecretKey secretKey = null;

    try {
        KeyGenerator generator = KeyGenerator.getInstance(getSecretKeyAlgorithm(algorithm));
        generator.init(keySize);
        secretKey = generator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    return (secretKey != null) ? new Key(secretKey, version, algorithm) : null;
}

From source file:com.doplgangr.secrecy.filesystem.encryption.AES_Crypter.java

AES_Crypter(String vaultPath, String passphrase, String encryptionMode) throws InvalidKeyException {
    secureRandom = new SecureRandom();
    this.vaultPath = vaultPath;
    this.encryptionMode = encryptionMode;

    File headerFile = new File(this.vaultPath + VAULT_HEADER_FILENAME);
    if (!headerFile.exists()) {
        try {/*from  ww  w .j av  a  2  s .c  om*/
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            keyGenerator.init(AES_KEY_SIZE_BIT);
            Key encryptionKey = keyGenerator.generateKey();

            byte[] vaultNonce = new byte[NONCE_LENGTH_BYTE];
            byte[] salt = new byte[SALT_SIZE_BYTE];
            secureRandom.nextBytes(vaultNonce);
            secureRandom.nextBytes(salt);

            int pbkdf2Iterations = generatePBKDF2IterationCount(passphrase, salt);

            SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
            SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(
                    new PBEKeySpec(passphrase.toCharArray(), salt, pbkdf2Iterations, AES_KEY_SIZE_BIT));

            writeVaultHeader(headerFile, vaultNonce, salt, pbkdf2Iterations, encryptionKey, keyFromPassphrase);
        } catch (Exception e) {
            Util.log("Cannot create vault header!");
            e.printStackTrace();
        }
    }

    try {
        FileInputStream headerInputStream = new FileInputStream(headerFile);
        vaultHeader = VaultHeader.parseFrom(headerInputStream);
    } catch (Exception e) {
        Util.log("Cannot read vault header!");
        e.printStackTrace();
    }

    try {
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(SECRET_KEY_ALGORITHM);
        SecretKey keyFromPassphrase = secretKeyFactory.generateSecret(new PBEKeySpec(passphrase.toCharArray(),
                vaultHeader.getSalt().toByteArray(), vaultHeader.getPbkdf2Iterations(), AES_KEY_SIZE_BIT));
        Cipher c = Cipher.getInstance(HEADER_ENCRYPTION_MODE);
        c.init(Cipher.UNWRAP_MODE, keyFromPassphrase,
                new IvParameterSpec(vaultHeader.getVaultIV().toByteArray()));

        vaultFileEncryptionKey = (SecretKey) c.unwrap(vaultHeader.getEncryptedAesKey().toByteArray(),
                KEY_ALGORITHM, Cipher.SECRET_KEY);
    } catch (InvalidKeyException e) {
        throw new InvalidKeyException("Passphrase is wrong!");
    } catch (Exception e) {
        Util.log("Cannot decrypt AES key");
        e.printStackTrace();
    }
}

From source file:org.apache.ws.security.message.EncryptionTest.java

/**
 * Setup method/*w  w  w  .j  a  v  a2 s .c  om*/
 * 
 * @throws java.lang.Exception Thrown when there is a problem in setup
 */
@org.junit.Before
public void setUp() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    key = keyGen.generateKey();
    keyData = key.getEncoded();
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    wssConfig.setWsiBSPCompliant(true);
    secEngine.setWssConfig(wssConfig);
}

From source file:com.torchmind.authenticator.AbstractTokenGenerator.java

/**
 * {@inheritDoc}/*  w w  w. ja v a 2  s . co  m*/
 */
@NonNull
@Override
public SecretKey generateSecret() {
    try {
        KeyGenerator generator = KeyGenerator.getInstance("Hmac" + this.algorithm.name());
        generator.init(80);
        return generator.generateKey();
    } catch (NoSuchAlgorithmException ex) {
        throw new UnsupportedOperationException(
                "The specified algorithm is not supported by this Java VM implementation: " + ex.getMessage(),
                ex);
    }
}

From source file:org.apache.hadoop.hdfs.security.AccessTokenHandler.java

/** Initialize access keys */
private synchronized void generateKeys() throws NoSuchAlgorithmException {
    keyGen = KeyGenerator.getInstance("HmacSHA1");
    /*/*from  ww  w  .  j  a  v  a2s.c  om*/
     * Need to set estimated expiry dates for currentKey and nextKey so that if
     * NN crashes, DN can still expire those keys. NN will stop using the newly
     * generated currentKey after the first keyUpdateInterval, however it may
     * still be used by DN and Balancer to generate new tokens before they get a
     * chance to sync their keys with NN. Since we require keyUpdInterval to be
     * long enough so that all live DN's and Balancer will sync their keys with
     * NN at least once during the period, the estimated expiry date for
     * currentKey is set to now() + 2 * keyUpdateInterval + tokenLifetime.
     * Similarly, the estimated expiry date for nextKey is one keyUpdateInterval
     * more.
     */
    serialNo++;
    currentKey = new BlockAccessKey(serialNo, new Text(keyGen.generateKey().getEncoded()),
            System.currentTimeMillis() + 2 * keyUpdateInterval + tokenLifetime);
    serialNo++;
    nextKey = new BlockAccessKey(serialNo, new Text(keyGen.generateKey().getEncoded()),
            System.currentTimeMillis() + 3 * keyUpdateInterval + tokenLifetime);
    allKeys.put(currentKey.getKeyID(), currentKey);
    allKeys.put(nextKey.getKeyID(), nextKey);
}

From source file:press.gfw.Encrypt.java

public Encrypt() {

    super();/*  w w  w . j  a v a2  s.c o m*/

    secureRandom = new SecureRandom();

    try {

        cipher = Cipher.getInstance("AES/CFB/NoPadding"); // Advanced Encryption Standard - Cipher Feedback Mode - No Padding

        keyGenerator = KeyGenerator.getInstance("AES");

    } catch (NoSuchAlgorithmException | NoSuchPaddingException ex) {

        throw new RuntimeException(ex);

    }

}