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.b3log.latke.util.Crypts.java

/**
 * Encrypts by AES./*  ww w .  j  a va2  s  . com*/
 *
 * @param content the specified content to encrypt
 * @param key     the specified key
 * @return encrypted content
 * @see #decryptByAES(java.lang.String, java.lang.String)
 */
public static String encryptByAES(final String content, final String key) {
    try {
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        final SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.setSeed(key.getBytes());
        kgen.init(128, secureRandom);
        final SecretKey secretKey = kgen.generateKey();
        final byte[] enCodeFormat = secretKey.getEncoded();
        final SecretKeySpec keySpec = new SecretKeySpec(enCodeFormat, "AES");
        final Cipher cipher = Cipher.getInstance("AES");
        final byte[] byteContent = content.getBytes("UTF-8");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        final byte[] result = cipher.doFinal(byteContent);

        return Hex.encodeHexString(result);
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Encrypt failed", e);

        return null;
    }
}

From source file:com.lling.qiqu.utils.AesUtils.java

/**
 * Returns an AES nbit Base64 key/*from  w w w .java2  s  .c o m*/
 *
 * @param keySize Size of the key
 * @return AES 128bit Base64 key
 */
public static String generateKey(int keySize) {
    String key = "";
    KeyGenerator kgen = null;
    try {
        kgen = KeyGenerator.getInstance("AES");
        kgen.init(keySize);
        SecretKey skey = kgen.generateKey();
        byte[] raw = skey.getEncoded();
        key = new String(Base64.encodeBase64(raw));
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return key;
}

From source file:com.miyue.util.Cryptos.java

/**
 * ?HMAC-SHA1,,160?(20)./*from w ww.  j a v  a  2 s. co  m*/
 * HMAC-SHA1?, RFC2401160?(20).
 */
public static byte[] generateHmacSha1Key() {
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
        keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
        SecretKey secretKey = keyGenerator.generateKey();
        return secretKey.getEncoded();
    } catch (GeneralSecurityException e) {
        throw Exceptions.unchecked(e);
    }
}

From source file:org.craftercms.commons.crypto.CryptoUtils.java

/**
 * Generates a random encryption key./*www  . java2s.c  o m*/
 *
 * @param cipherAlgorithm the cipher algorithm the key will be used with. Will determine the key size
 * @return the generated key
 */
public static SecretKey generateKey(String cipherAlgorithm) throws NoSuchAlgorithmException {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(cipherAlgorithm);
    keyGenerator.init(secureRandom);

    return keyGenerator.generateKey();
}

From source file:com.credomatic.gprod.db2query2csv.Security.java

/**
 * Cifra una cadena de carateres utilizando el algoritmo AES y una llave (128, 256, o 512 bits). 
 * @param KeySize tamao de la llave autogenerada para relizar el cifrado
 * @param value cadena de caracteres que sera cifrada
 * @return instancia de tipo ${@link SecurityParams} con el resultado del proceso de cifrado
 *//*  ww  w. ja  va2  s . c o m*/
public static SecurityParams encrypt(int KeySize, String value) {

    SecurityParams result = null;
    try {
        // Get the KeyGenerator
        final KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(KeySize);

        // Generate the secret key specs.
        final SecretKey skey = kgen.generateKey();
        final byte[] raw = skey.getEncoded();
        final SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        final Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        final String key = new Base64().encodeAsString(raw);
        final String encrypt = (new Base64()).encodeAsString(cipher.doFinal(value.getBytes()));

        result = new SecurityParams(encrypt, key, KeySize);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:pl.mwaleria.safecommunicator.core.cipher.CipherManager.java

public byte[] encrypt(byte[] input, PublicKey publicKey) throws CryptoException {
    try {//from   w  ww .j a v a2s  .  c  om
        KeyGenerator generator = KeyGenerator.getInstance(Constants.CIPHER_SYMETRIC_ALGORITHM);
        generator.init(Constants.CIPHER_SYMETRIC_SIZE);
        SecretKey key = generator.generateKey();
        byte[] aesKey = key.getEncoded();
        byte[] cryptedAesKey = this.encryptAsymetric(aesKey, publicKey);
        Cipher cipher = Cipher.getInstance(Constants.CIPHER_SYMETRIC_INSTANCE);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return ArrayUtils.addAll(cryptedAesKey, cipher.doFinal(input));
    } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException ex) {
        Logger.getLogger(CipherManager.class.getName()).log(Level.SEVERE, null, ex);
        throw new CryptoException(ex);
    }
}

From source file:com.liferay.util.Encryptor.java

public static Key generateKey(String algorithm) throws EncryptorException {
    try {/* ww w  .  j  a v  a2 s . com*/
        Security.addProvider(getProvider());

        KeyGenerator generator = KeyGenerator.getInstance(algorithm);
        generator.init(56, new SecureRandom());

        Key key = generator.generateKey();

        return key;
    } catch (Exception e) {
        throw new EncryptorException(e);
    }
}

From source file:eml.studio.shared.util.Aes.java

/** 
 * Aes Encryption //  w w  w  .ja v  a  2 s  .com
 * @param content content to be encrypted
 * @param encryptKey encryption key
 * @return 
 * @throws Exception 
 */
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));

    return cipher.doFinal(content.getBytes("utf-8"));
}

From source file:org.vosao.utils.CipherUtils.java

public static String generateKey() {
    try {/*w ww. j a  va2 s.c  om*/
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        return new Base64().encodeToString(kgen.generateKey().getEncoded());
    } catch (NoSuchAlgorithmException e) {
        logger.error("Error generating secret key", e);
        return "";
    }
}

From source file:com.cfs.util.AESCriptografia.java

public String gerarChaveRandomica() {
    String chave = null;//w w w .  j  av a  2 s.  c o  m
    try {
        /* Cria o gerador de chaves */
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        /* Inicializa o gerador de chaves */
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        /* Cria uma chave */
        SecretKey key = keygen.generateKey();
        /* Captura a chave na forma de bytes */
        byte[] buffer = key.getEncoded();
        /* Codifica a chave gerada */
        byte[] chaveGerada = Base64.encodeBase64(buffer);
        /* Converte a chave para texto */
        chave = new String(chaveGerada, "UTF-8");
    } catch (Exception e) {
        e.printStackTrace();
    }
    /* Retorna a chave */
    return chave;
}