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.microsoft.azure.storage.util.KeyVaultUtility.java

/**
 * Creates a secret in Azure Key Vault and returns its ID.
 * /*from  w  w w. jav a 2 s. c o m*/
 * @param secretName
 *            The name of the secret to create
 * @return The ID of the created secret
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws NoSuchAlgorithmException
 * @throws URISyntaxException
 * @throws MalformedURLException
 */
public static String SetUpKeyVaultSecret(String secretName) throws InterruptedException, ExecutionException,
        NoSuchAlgorithmException, URISyntaxException, MalformedURLException {
    KeyVaultClient cloudVault = GetKeyVaultClient();

    if (Utility.vaultURL == null || Utility.vaultURL.isEmpty()) {
        throw new IllegalArgumentException("No Keyvault URL specified.");
    }

    try {
        // Delete the secret if it exists.
        cloudVault.deleteSecretAsync(Utility.vaultURL, secretName).get();
    } catch (ExecutionException ex) {
        boolean keyNotFound = false;
        if (ex.getCause().getClass() == ServiceException.class) {
            ServiceException serviceException = (ServiceException) ex.getCause();
            if (serviceException.getHttpStatusCode() == 404) {
                keyNotFound = true;
            }
        }

        if (!keyNotFound) {
            System.out.println(
                    "Unable to access the specified vault. Please confirm the KVClientId, KVClientKey, and VaultUri are valid in the app.config file.");
            System.out.println(
                    "Also ensure that the client ID has previously been granted full permissions for Key Vault secrets using the Set-AzureKeyVaultAccessPolicy command with the -PermissionsToSecrets parameter.");
            System.out.println("Press any key to exit");
            Scanner input = new Scanner(System.in);
            input.nextLine();
            input.close();
            throw ex;
        }
    }

    // Create a 256bit symmetric key and convert it to Base64.
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(256); // Note that we cannot use SymmetricKey.KeySize256,
                      // because this resolves to '0x20'.
    SecretKey wrapKey = keyGen.generateKey();

    // Store the Base64 of the key in the key vault. Note that the
    // content-type of the secret must
    // be application/octet-stream or the KeyVaultKeyResolver will not load
    // it as a key.
    Map<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/octet-stream");
    Secret cloudSecret = cloudVault.setSecretAsync(Utility.vaultURL, secretName,
            Base64.encodeBase64String(wrapKey.getEncoded()), "application/octet-stream", null, null).get();

    // Return the base identifier of the secret. This will be resolved to
    // the current version of the secret.
    return cloudSecret.getSecretIdentifier().getBaseIdentifier();
}

From source file:org.b3log.latke.util.Crypts.java

/**
 * Decrypts by AES./*from w  w w  .j  ava  2  s. co m*/
 *
 * @param content the specified content to decrypt
 * @param key     the specified key
 * @return original content
 * @see #encryptByAES(java.lang.String, java.lang.String)
 */
public static String decryptByAES(final String content, final String key) {
    try {
        final byte[] data = Hex.decodeHex(content.toCharArray());
        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");
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        final byte[] result = cipher.doFinal(data);

        return new String(result, "UTF-8");
    } catch (final Exception e) {
        LOGGER.log(Level.WARN, "Decrypt failed");

        return null;
    }
}

From source file:org.paxml.util.CryptoUtils.java

public static byte[] encrypt(String data, String password) {

    SecretKey SecKey = getSecretKey(password);
    try {/*from w w w. ja v a  2 s.  c  o  m*/
        KeyGenerator KeyGen = KeyGenerator.getInstance(KEY_TYPE);
        KeyGen.init(KEY_LENGTH_BITS);

        Cipher cipher = Cipher.getInstance(KEY_TYPE);

        byte[] clear = data.getBytes(KEY_VALUE_ENCODING);

        cipher.init(Cipher.ENCRYPT_MODE, SecKey);
        return cipher.doFinal(clear);
    } catch (Exception e) {
        throw new PaxmlRuntimeException(e);
    }

}

From source file:com.thoughtworks.go.server.util.EncryptionHelper.java

public static SecretKey generateAESKey() throws NoSuchAlgorithmException {
    KeyGenerator generator = KeyGenerator.getInstance("AES");
    generator.init(128); // The AES key size in number of bits
    return generator.generateKey();
}

From source file:org.apache.xml.security.samples.encryption.Encrypter.java

private static SecretKey GenerateDataEncryptionKey() throws Exception {

    String jceAlgorithmName = "AES";
    KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
    keyGenerator.init(128);//from  w  w w  . j  a va 2 s. c o  m
    return keyGenerator.generateKey();
}

From source file:com.adaptris.security.password.AesCrypto.java

public String encode(String plainText, String charset) throws PasswordException {
    String result = null;//from w  ww. j a v a 2 s.c  o m
    try {
        KeyGenerator kg = KeyGenerator.getInstance(ALG);
        kg.init(KEY_LEN, SecurityUtil.getSecureRandom());
        SecretKey sessionKey = kg.generateKey();
        Cipher dataCipher = Cipher.getInstance(CIPHER);
        dataCipher.init(Cipher.ENCRYPT_MODE, sessionKey);
        byte[] encryptedBody = dataCipher.doFinal(seed(plainText, charset));
        Output output = new Output();
        output.setSessionKey(sessionKey.getEncoded());
        output.setSessionVector(dataCipher.getIV());
        output.setEncryptedData(encryptedBody);
        result = Password.PORTABLE_PASSWORD + output.write();
    } catch (Exception e) {
        throw new PasswordException(e);
    }
    return result;
}

From source file:org.jasig.cas.web.flow.CasFlowExecutionKeyFactory.java

public CasFlowExecutionKeyFactory(final ConversationManager conversationManager,
        final FlowExecutionSnapshotFactory snapshotFactory)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException {
    this(conversationManager, snapshotFactory, DEFAULT_CIPHER_ALGORITHM,
            KeyGenerator.getInstance(DEFAULT_ENCRYPTION_ALGORITHM).generateKey());
}

From source file:com.janrain.backplane.common.HmacHashUtils.java

private static SecretKey generateMacKey(String algorithm, int keySize) throws NoSuchAlgorithmException {
    KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
    keyGen.init(keySize);//w  w  w  .  jav a  2 s.  c  o  m
    return keyGen.generateKey();
}

From source file:press.gfw.chat.Encrypt.java

@SuppressLint("TrulyRandom")
public Encrypt() {

    super();/*from 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);

    }

}

From source file:com.jwm123.loggly.reporter.TripleDesCipher.java

private void getKey() throws NoSuchAlgorithmException, IOException {
    File keyFile = appDir.getFileDir(keyPath);
    if (keyFile.exists()) {
        key = Base64.decode(FileUtils.readFileToString(keyFile));
    } else {//from   ww  w. j  av a 2s  .com
        KeyGenerator generator = KeyGenerator.getInstance("DESede");
        SecretKey desKey = generator.generateKey();
        key = desKey.getEncoded();
        FileUtils.writeStringToFile(keyFile, new String(Base64.encode(key)));
    }

}