List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
From source file:com.z299studio.pb.FingerprintDialog.java
private void initCipher(int mode) { try {//from w ww. j a v a 2s. c o m IvParameterSpec ivParams; KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey key; mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); if (mode == Cipher.ENCRYPT_MODE) { KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); mCipher.init(mode, keyGenerator.generateKey()); } else { key = (SecretKey) keyStore.getKey(KEY_NAME, null); ivParams = new IvParameterSpec(Application.getInstance().getFpIv()); mCipher.init(mode, key, ivParams); } mCryptoObject = new FingerprintManager.CryptoObject(mCipher); } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchProviderException | InvalidAlgorithmParameterException | NoSuchPaddingException e) { Log.e("Pb:FingerprintDialog", "Runtime error in initCipher."); Log.e("Pb:FingerprintDialog", e.toString()); } }
From source file:com.keepassdroid.fingerprint.FingerPrintHelper.java
public FingerPrintHelper(final Context context, final FingerPrintCallback fingerPrintCallback) { if (!isFingerprintSupported()) { // really not much to do when no fingerprint support found setInitOk(false);/*ww w. j a v a2s .c om*/ return; } this.fingerprintManager = FingerprintManagerCompat.from(context); this.keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); this.fingerPrintCallback = fingerPrintCallback; if (hasEnrolledFingerprints()) { try { this.keyStore = KeyStore.getInstance("AndroidKeyStore"); this.keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); this.cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); this.cryptoObject = new FingerprintManagerCompat.CryptoObject(cipher); setInitOk(true); } catch (final Exception e) { setInitOk(false); fingerPrintCallback.onException(); } } }
From source file:com.glaf.core.security.SecurityUtils.java
/** * ?//from w w w .j av a 2 s. c o m * * @param ctx * * @return key */ public static Key generateSecretKey(SecurityContext ctx) { try { KeyGenerator skg = KeyGenerator.getInstance(ctx.getSymmetryKeyAlgorithm(), ctx.getJceProvider()); SecureRandom secureRandom = SecureRandom.getInstance(ctx.getSecureRandomAlgorithm()); skg.init(ctx.getSymmetryKeySize(), secureRandom); SecretKey key = skg.generateKey(); return key; } catch (Exception ex) { throw new SecurityException(ex); } }
From source file:org.panbox.core.crypto.CryptCore.java
public static SecretKey generateSymmetricKey() { KeyGenerator generator;/*from w w w. j a va 2 s.co m*/ try { generator = KeyGenerator.getInstance(KeyConstants.SYMMETRIC_ALGORITHM, KeyConstants.PROV_BC); generator.init(KeyConstants.SYMMETRIC_KEY_SIZE); return generator.generateKey(); } catch (NoSuchAlgorithmException e) { logger.error("Error during symmetric key generation: " + e); } catch (NoSuchProviderException e) { logger.error("Error during symmetric key generation: " + e); } return null; }
From source file:de.schildbach.wallet.util.FingerprintHelper.java
@RequiresApi(api = Build.VERSION_CODES.M) private boolean initKeyStore() { try {// w ww .jav a 2s . c o m keyStore = KeyStore.getInstance("AndroidKeyStore"); KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyStore.load(null); if (getLastIv() == null) { KeyGenParameterSpec keyGeneratorSpec = createKeyGenParameterSpec(); keyGenerator.init(keyGeneratorSpec); keyGenerator.generateKey(); } } catch (Throwable t) { log.info("Failed init of keyStore & keyGenerator: " + t.getMessage()); return false; } return true; }
From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java
/** * Creates a symmetric key in the Android Key Store which can only be used after the user has * authenticated with device credentials within the last X seconds. *///from ww w .jav a2s. c o m private void createKey() { // Generate a key to decrypt payment credentials, tokens, etc. // This will most likely be a registration step for the user when they are setting up your app. try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); // Set the alias of the entry in Android KeyStore where the key will appear // and the constrains (purposes) in the constructor of the Builder keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) // Require that the user has unlocked in the last 30 seconds .setUserAuthenticationValidityDurationSeconds(AUTHENTICATION_DURATION_SECONDS) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | KeyStoreException | CertificateException | IOException e) { throw new RuntimeException("Failed to create a symmetric key", e); } }
From source file:com.owncloud.android.ui.activity.FingerprintActivity.java
@TargetApi(Build.VERSION_CODES.M) protected void generateKey() { try {// w w w.j a va 2 s. c o m keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); } catch (Exception e) { Log_OC.e(TAG, "Error getting KeyStore", e); } KeyGenerator keyGenerator; try { keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { return; } try { keyStore.load(null); keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build()); keyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException | IOException e) { return; } }
From source file:org.lsc.utils.security.SymmetricEncryption.java
/** * Generate a random key file.// w ww . j a v a 2s. c o m * @param keyPath The filename where to write the key * @param algo The supported algorithm to use * @param strength The encryption strength * @return boolean false if an error occurred * @throws NoSuchAlgorithmException * @throws NoSuchProviderException */ public boolean generateRandomKeyFile(String keyPath, String algo, int strength) throws NoSuchAlgorithmException, NoSuchProviderException { OutputStream os = null; try { KeyGenerator kg = KeyGenerator.getInstance(algo, securityProvider.getName()); SecretKey cipherKey = kg.generateKey(); SecureRandom sr = new SecureRandom(); kg.init(strength, sr); os = new FileOutputStream(keyPath); os.write(cipherKey.getEncoded()); } catch (IOException e) { LOGGER.error("Unable to write new generated key in " + keyPath + ". Encountered exception is : " + e.getLocalizedMessage(), e); return false; } finally { try { if (os != null) { os.close(); } } catch (IOException e1) { } } return true; }
From source file:edu.vt.middleware.crypt.CryptProvider.java
/** * <p>This finds a <code>KeyGenerator</code> using the known providers and the * supplied algorithm parameter.</p> * * @param algorithm <code>String</code> name * * @return <code>KeyGenerator</code> * * @throws CryptException if the algorithm is not available from any * provider or if the provider is not available in the environment */// w w w . j a va 2 s . c o m public static KeyGenerator getKeyGenerator(final String algorithm) throws CryptException { final Log logger = LogFactory.getLog(CryptProvider.class); KeyGenerator generator = null; for (int i = 0; i < providers.length; i++) { try { generator = KeyGenerator.getInstance(algorithm, providers[i]); } catch (NoSuchAlgorithmException e) { if (logger.isDebugEnabled()) { logger.debug("Could not find algorithm " + algorithm + " in " + providers[i]); } } catch (NoSuchProviderException e) { if (logger.isDebugEnabled()) { logger.debug("Could not find provider " + providers[i]); } } finally { if (generator != null) { break; } } } if (generator == null) { try { generator = KeyGenerator.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { if (logger.isDebugEnabled()) { logger.debug("Could not find algorithm " + algorithm); } throw new CryptException(e.getMessage()); } } return generator; }
From source file:eap.util.EDcodeUtil.java
private static byte[] aes(byte[] data, byte[] key, int keyLen, int opMode) { try {/* w w w . j av a 2 s . co m*/ KeyGenerator kgen = KeyGenerator.getInstance("AES", provider); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); // provider secureRandom.setSeed(key); kgen.init(keyLen, secureRandom); SecretKey secretKey = kgen.generateKey(); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES"); /* mode: ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128<br/> * padding: Nopadding/PKCS5Padding/ISO10126Padding */ Cipher cipher = Cipher.getInstance("AES", provider); // ECB/PKCS5Padding cipher.init(opMode, keySpec); return cipher.doFinal(data); } catch (Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } // // we're using Bouncy Castle // Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()) // // // create our key specification // val secretKeySpec = new SecretKeySpec(hexStringToByteArray(hexEncodedKey), "AES") // // // create an AES engine in CTR mode (no padding) // val aes = Cipher.getInstance("AES/CTR/NoPadding", BouncyCastleProvider.PROVIDER_NAME) // // // initialize the AES engine in encrypt mode with the key and IV // aes.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(hexStringToByteArray(hexEncodedIv))) // // // encrypt the message and return the encrypted byte array // aes.doFinal(hexStringToByteArray(hexEncodedMessage)) }