List of usage examples for javax.crypto KeyGenerator generateKey
public final SecretKey generateKey()
From source file:org.b3log.latke.util.Crypts.java
/** * Encrypts by AES./* w ww.j a v a 2s . c o m*/ * * @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:org.b3log.latke.util.Crypts.java
/** * Decrypts by AES.//from ww w . ja va 2 s . c o 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:net.theblackchamber.crypto.util.KeystoreUtils.java
/** * Method which will generate a random AES key and add it to a keystore with * the entry name provided.//from w w w. j a v a 2 s . c o m * * @param config * Configuration for generation of key. * @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws CertificateException * @throws IOException */ public static void generateAESSecretKey(KeyConfig config) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException { if (config == null || config.getKeyStoreFile() == null || StringUtils.isEmpty(config.getKeyEntryName()) || config.getAlgorithm() == null) { throw new KeyStoreException("Missing parameters, unable to create keystore."); } SecureRandom random = new SecureRandom(); KeyGenerator keygen = KeyGenerator.getInstance(config.getAlgorithm().toString(), new BouncyCastleProvider()); keygen.init(config.getKeySize(), random); SecretKey key = keygen.generateKey(); KeyStore keyStore = KeyStore.getInstance("JCEKS"); FileInputStream fis = null; if (config.getKeyStoreFile().exists() && FileUtils.sizeOf(config.getKeyStoreFile()) > 0) { fis = new FileInputStream(config.getKeyStoreFile()); } keyStore.load(fis, config.getKeyStorePassword().toCharArray()); KeyStore.ProtectionParameter protectionParameter = new KeyStore.PasswordProtection( config.getKeyStorePassword().toCharArray()); KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(key); keyStore.setEntry(config.getKeyEntryName(), secretKeyEntry, protectionParameter); if (fis != null) { fis.close(); } FileOutputStream fos = new FileOutputStream(config.getKeyStoreFile()); keyStore.store(fos, config.getKeyStorePassword().toCharArray()); fos.close(); }
From source file:pro.hirooka.streaming_server_for_multiple_platforms.Encrypter.java
static Key makeKey(int keyBit) throws NoSuchAlgorithmException { KeyGenerator kg = KeyGenerator.getInstance("AES"); SecureRandom rd = SecureRandom.getInstance("SHA1PRNG"); kg.init(keyBit, rd);/*ww w .j a va 2s .c o m*/ Key key = kg.generateKey(); return key; }
From source file:Main.java
private static byte[] getRawKey(byte[] seed) throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = null;/*from ww w . ja v a 2s . c om*/ if (android.os.Build.VERSION.SDK_INT >= 17) { sr = SecureRandom.getInstance("SHA1PRNG", "Crypto"); } else { sr = SecureRandom.getInstance("SHA1PRNG"); } sr.setSeed(seed); kgen.init(128, sr); //256 bits or 128 bits,192bits SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; }
From source file:com.microsoft.azure.storage.util.KeyVaultUtility.java
/** * Creates a secret in Azure Key Vault and returns its ID. * /* w w w .j a v a 2s. c om*/ * @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:com.lling.qiqu.utils.AesUtils.java
/** * Returns an AES nbit Base64 key/*w ww . ja v a 2s . com*/ * * @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:configuration.Key.java
/** * Creates a random key with the given parameters. * //from w w w . ja v a 2 s . c om * @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.fengduo.bee.commons.security.Digests.java
/** * ??/*from w ww .j a v a 2 s .c o m*/ * * @param algorithm * @return * @throws RuntimeException {@link java.security.NoSuchAlgorithmException} ? */ private static byte[] getHmacKey(String algorithm) { // ?KeyGenerator KeyGenerator keyGenerator = null; try { keyGenerator = KeyGenerator.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } // SecretKey secretKey = keyGenerator.generateKey(); // return secretKey.getEncoded(); }
From source file:org.apache.hadoop.mapreduce.security.TestTokenCache.java
private static void createTokenFileJson() throws IOException { Map<String, String> map = new HashMap<String, String>(); try {/* w ww . j a va2s . co m*/ KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1"); for (int i = 0; i < NUM_OF_KEYS; i++) { SecretKeySpec key = (SecretKeySpec) kg.generateKey(); byte[] enc_key = key.getEncoded(); map.put("alias" + i, new String(Base64.encodeBase64(enc_key))); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } try { File p = new File(tokenFileName.getParent().toString()); p.mkdirs(); // convert to JSON and save to the file mapper.writeValue(new File(tokenFileName.toString()), map); } catch (Exception e) { System.out.println("failed with :" + e.getLocalizedMessage()); } }