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.owncloud.android.utils.EncryptionUtils.java

public static byte[] generateKey() {
    KeyGenerator keyGenerator;//from  w w w  .ja va2 s . c om
    try {
        keyGenerator = KeyGenerator.getInstance(AES);
        keyGenerator.init(128);

        return keyGenerator.generateKey().getEncoded();
    } catch (NoSuchAlgorithmException e) {
        Log_OC.e(TAG, e.getMessage());
    }

    return null;
}

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

/**
 * Generates a one-time use Symmetric Key on-the-fly for use in envelope encryption.
 *///from w  w w  . j a v  a  2  s .  c o  m
public static SecretKey generateOneTimeUseSymmetricKey() {
    KeyGenerator generator;
    try {
        generator = KeyGenerator.getInstance(JceEncryptionConstants.SYMMETRIC_KEY_ALGORITHM);
        generator.init(JceEncryptionConstants.SYMMETRIC_KEY_LENGTH, new SecureRandom());
        return generator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        throw new AmazonClientException("Unable to generate envelope symmetric key:" + e.getMessage(), e);
    }
}

From source file:pt.lunacloud.services.storage.internal.crypto.EncryptionUtils.java

/**
 * Generates a one-time use Symmetric Key on-the-fly for use in envelope encryption.
 *//*  w  w  w .jav  a2s.com*/
public static SecretKey generateOneTimeUseSymmetricKey() {
    KeyGenerator generator;
    try {
        generator = KeyGenerator.getInstance(JceEncryptionConstants.SYMMETRIC_KEY_ALGORITHM);
        generator.init(JceEncryptionConstants.SYMMETRIC_KEY_LENGTH, new SecureRandom());
        return generator.generateKey();
    } catch (NoSuchAlgorithmException e) {
        throw new LunacloudClientException("Unable to generate envelope symmetric key:" + e.getMessage(), e);
    }
}

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

private KeyGenerator getKeyGenerator() throws WSSecurityException {
    try {/*from   w  w w .j  a  v a  2s.  c  o m*/
        //
        // Assume AES as default, so initialize it
        //
        String keyAlgorithm = JCEMapper.getJCEKeyAlgorithmFromURI(symEncAlgo);
        KeyGenerator keyGen = KeyGenerator.getInstance(keyAlgorithm);
        if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_128)) {
            keyGen.init(128);
        } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_192)) {
            keyGen.init(192);
        } else if (symEncAlgo.equalsIgnoreCase(WSConstants.AES_256)) {
            keyGen.init(256);
        }
        return keyGen;
    } catch (NoSuchAlgorithmException e) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e);
    }
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

private static byte[] findSecret(String secret, String algorithm) {
    byte[] bytes = null;

    if (secret == null) {
        try {/*from   ww  w .ja v  a 2  s . com*/
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            bytes = kg.generateKey().getEncoded();

            if (log.isLoggable(Level.FINE))
                log.fine("generated random password of length " + bytes.length);
        } catch (NoSuchAlgorithmException e) {
            // Generate random password length 8, 
            int length = 8;
            bytes = new byte[length];
            new Random().nextBytes(bytes);

            if (log.isLoggable(Level.FINE))
                log.fine("generated random password of length " + length);
        }
    } else {
        bytes = new Base64().decode(secret.getBytes());
    }

    return bytes;
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

private static byte[] findSecret(String secret, String algorithm) {
    byte[] bytes = null;

    if (secret == null) {
        try {//from  www  .  j a  v  a 2s  . co m
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            bytes = kg.generateKey().getEncoded();

            if (log.isLoggable(Level.FINE)) {
                log.fine("generated random password of length " + bytes.length);
            }
        } catch (NoSuchAlgorithmException e) {
            // Generate random password length 8, 
            int length = 8;
            bytes = new byte[length];
            new Random().nextBytes(bytes);

            if (log.isLoggable(Level.FINE)) {
                log.fine("generated random password of length " + length);
            }
        }
    } else {
        bytes = new Base64().decode(secret.getBytes());
    }

    return bytes;
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

private static byte[] findMacSecret(String secret, String algorithm) {
    byte[] bytes = null;

    if (secret == null) {
        try {// ww  w . ja  v  a 2s  .com
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            bytes = kg.generateKey().getEncoded();

            if (log.isLoggable(Level.FINE))
                log.fine("generated random mac password of length " + bytes.length);
        } catch (NoSuchAlgorithmException e) {
            // Generate random password length 8, 
            int length = 8;
            bytes = new byte[length];
            new Random().nextBytes(bytes);

            if (log.isLoggable(Level.FINE))
                log.fine("generated random mac password of length " + length);
        }
    } else {
        bytes = new Base64().decode(secret.getBytes());
    }

    return bytes;
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

private static byte[] findMacSecret(String secret, String algorithm) {
    byte[] bytes = null;

    if (secret == null) {
        try {//from   w  ww.j  a v a 2 s.com
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            bytes = kg.generateKey().getEncoded();

            if (log.isLoggable(Level.FINE)) {
                log.fine("generated random mac password of length " + bytes.length);
            }
        } catch (NoSuchAlgorithmException e) {
            // Generate random password length 8, 
            int length = 8;
            bytes = new byte[length];
            new Random().nextBytes(bytes);

            if (log.isLoggable(Level.FINE)) {
                log.fine("generated random mac password of length " + length);
            }
        }
    } else {
        bytes = new Base64().decode(secret.getBytes());
    }

    return bytes;
}

From source file:it.scoppelletti.programmerpower.security.CryptoUtils.java

/**
 * Restituisce un generatore di chiavi simmetriche.
 * /*from w  w  w  . ja  va  2s . com*/
 * <H4>1. Propriet&agrave;</H4>
 * 
 * <P><TABLE WIDTH="100%" BORDER="1" CELLPADDING="5">
 * <THEAD>
 * <TR>
 *     <TH>Propriet&agrave;</TH>
 *     <TH>Descrizione</TH>     
 * </TR>
 * </THEAD>
 * <TBODY>
 * <TR>
 *      <TD>{@code alg}</TD>
 *      <TD>Codice dell&rsquo;algoritmo di crittografia.</TD>
 * </TR>
 * <TR>
 *      <TD>{@code param.factory}</TD>
 *      <TD>Nome della classe di factory dei parametri specifici
 *      dell&rsquo;algoritmo; la classe deve implementare
 *      l&rsquo;interfaccia {@code AlgorithmParameterSpecFactory} e
 *      pu&ograve; prevedere altre propriet&agrave;.</TD>          
 * </TR>
 * <TR>
 *      <TD>{@code param.factory.prefix}</TD>
 *      <TD>Eventuale prefisso da applicare al nome delle propriet&agrave;
 *      interrogate dal provider {@code param.factory}.</TD>          
 * </TR> 
 * <TR>
 *      <TD>{@code key.size}</TD>
 *      <TD>Dimensione della chiave (numero di bit).</TD>          
 * </TR> 
 * <TR>
 *     <TD COLSPAN="2">Le propriet&agrave; {@code param.factory} e
 *     {@code key.size} non possono essere entrambe impostate; se nessuna
 *     delle due propriet&agrave; &egrave; impostata, il generatore
 *     sar&agrave; inizializzato con i parametri di default definiti dallo
 *     specifico provider JCA.</TD>
 * </TR>
 * </TBODY>
 * </TABLE></P>
 *    
 * @param  props  Propriet&agrave;.
 * @param  prefix Prefisso da applicare al nome delle propriet&agrave; da
 *                interrogare. Pu&ograve; essere {@code null}.
 * @return        Oggetto.
 * @see    it.scoppelletti.programmerpower.security.spi.AlgorithmParameterSpecFactory
 * @see    <A HREF="{@docRoot}/it/scoppelletti/programmerpower/security/CryptoUtils.html#idAlg">Algoritmi
 *         di crittografia</A> 
 */
public static KeyGenerator getKeyGenerator(Properties props, String prefix) {
    int keySize;
    String alg, name;
    KeyGenerator gen;
    AlgorithmParameterSpec params;
    SecurityResources res = new SecurityResources();

    if (props == null) {
        throw new ArgumentNullException("props");
    }

    name = Strings.concat(prefix, CryptoUtils.PROP_KEYALGORITHM);
    alg = props.getProperty(name);
    if (Strings.isNullOrEmpty(alg)) {
        throw new ArgumentNullException(name);
    }

    params = CryptoUtils.getAlgorithmParameterSpec(props, prefix);
    keySize = CryptoUtils.getKeySize(props, prefix);
    if (params != null && keySize >= 0) {
        throw new IllegalArgumentException(
                res.getArgumentIncompatibilityException(Strings.concat(prefix, CryptoUtils.PROP_PARAMFACTORY),
                        Strings.concat(prefix, CryptoUtils.PROP_KEYSIZE)));
    }

    try {
        gen = KeyGenerator.getInstance(alg);
        if (params != null) {
            gen.init(params);
        }
        if (keySize >= 0) {
            gen.init(keySize);
        }
    } catch (GeneralSecurityException ex) {
        throw SecurityUtils.toSecurityException(ex);
    }

    return gen;
}

From source file:org.apache.hadoop.mapreduce.v2.app.MRAppMaster.java

/**
 * Obtain the tokens needed by the job and put them in the UGI
 * @param conf/*from  w w  w  . j  a  va2s. c  o m*/
 */
protected void initJobCredentialsAndUGI(Configuration conf) {

    try {
        this.currentUser = UserGroupInformation.getCurrentUser();
        this.jobCredentials = ((JobConf) conf).getCredentials();
        if (CryptoUtils.isEncryptedSpillEnabled(conf)) {
            int keyLen = conf.getInt(MRJobConfig.MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS,
                    MRJobConfig.DEFAULT_MR_ENCRYPTED_INTERMEDIATE_DATA_KEY_SIZE_BITS);
            KeyGenerator keyGen = KeyGenerator.getInstance(INTERMEDIATE_DATA_ENCRYPTION_ALGO);
            keyGen.init(keyLen);
            encryptedSpillKey = keyGen.generateKey().getEncoded();
        } else {
            encryptedSpillKey = new byte[] { 0 };
        }
    } catch (IOException e) {
        throw new YarnRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new YarnRuntimeException(e);
    }
}