List of usage examples for javax.crypto KeyGenerator getInstance
public static final KeyGenerator getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
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./*w ww .ja v a 2 s .co 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:org.talend.utils.security.AES.java
public AES() { try {/*w ww . ja va 2 s . c o m*/ // TDI-28380: Database password in tac db configuration page becomes empty once restart tomcat on Solaris. // TDI-30348: Whole tac configuration lost for the passwords. Provider p = Security.getProvider("BC"); KeyGenerator keyGen = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM, p); SecureRandom random = SecureRandom.getInstance(RANDOM_SHA1PRNG); random.setSeed(KeyValues); keyGen.init(128, random); Key key = keyGen.generateKey(); ecipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p); dcipher = Cipher.getInstance(ENCRYPTION_ALGORITHM, p); ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { // log the error to avoid that break GWT service log.error(e.getMessage(), e); } }
From source file:com.elkriefy.android.apps.authenticationexample.fingerprintdialog.FingerprintModule.java
@Provides public KeyGenerator providesKeyGenerator() { try {//from w w w .j a v a 2 s. c o m return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyGenerator", e); } }
From source file:eap.util.EDcodeUtil.java
private static byte[] genHmacKey(String algorithm) { try {/*from w w w. ja va2 s . c o m*/ KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm, provider); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("No such algorithm [" + algorithm + "]"); } }
From source file:pl.kotcrab.crypto.CryptoUtils.java
/** Generates random AES key * @return random AES key *//*from w ww . jav a2 s. c o m*/ public static SecretKey getAESRandomKey() { try { KeyGenerator keyGen = KeyGenerator.getInstance("AES", "BC"); keyGen.init(256); return keyGen.generateKey(); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { e.printStackTrace(); } return null; }
From source file:org.apache.abdera.security.util.KeyHelper.java
public static SecretKey generateSecretKey(String type, int size, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator keyGenerator = KeyGenerator.getInstance(type, provider); keyGenerator.init(size);/*from www . j av a 2 s. c o m*/ return keyGenerator.generateKey(); }
From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java
/** * Generate a saved password key for a file *//*from w w w .j ava 2 s . co m*/ @TargetApi(Build.VERSION_CODES.M) public synchronized void generateKey(Uri fileUri) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, IOException { PasswdSafeUtil.dbginfo(TAG, "generateKey: %s", fileUri); if (!itsFingerprintMgr.hasEnrolledFingerprints()) { throw new IOException(itsContext.getString(R.string.no_fingerprints_registered)); } String keyName = getPrefsKey(fileUri); try { KeyGenerator keyGen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE); keyGen.init(new KeyGenParameterSpec.Builder(keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).setKeySize(256) .setUserAuthenticationRequired(true).build()); keyGen.generateKey(); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) { Log.e(TAG, "generateKey failure", e); removeSavedPassword(fileUri); throw e; } }
From source file:de.niklasmerz.cordova.fingerprint.Fingerprint.java
/** * Sets the context of the Command. This can then be used to do things like * get file paths associated with the Activity. * * @param cordova The context of the main Activity. * @param webView The CordovaWebView Cordova is running in. *//*w ww. j a va 2s . c o m*/ public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); Log.v(TAG, "Init Fingerprint"); packageName = cordova.getActivity().getApplicationContext().getPackageName(); mPluginResult = new PluginResult(PluginResult.Status.NO_RESULT); if (android.os.Build.VERSION.SDK_INT < 23) { return; } mKeyguardManager = cordova.getActivity().getSystemService(KeyguardManager.class); mFingerPrintManager = cordova.getActivity().getApplicationContext() .getSystemService(FingerprintManager.class); try { mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE); mKeyStore = KeyStore.getInstance(ANDROID_KEY_STORE); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to get an instance of KeyGenerator", e); } catch (NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyGenerator", e); } catch (KeyStoreException e) { throw new RuntimeException("Failed to get an instance of KeyStore", e); } try { mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("Failed to get an instance of Cipher", e); } catch (NoSuchPaddingException e) { throw new RuntimeException("Failed to get an instance of Cipher", e); } }
From source file:com.POLIS.licensing.common.license.AbstractSerializationBasedLicense.java
@Override public String getEncryptedLicense(PublicKey targetKey) throws SystemStateException, OperationException { byte[] licenseAsBytes; try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { out.writeObject(this); licenseAsBytes = bos.toByteArray(); } catch (IOException ex) { throw new OperationException("An error occured while serializing the license", ex); }//from ww w .jav a 2 s. c o m SecureRandom random = new SecureRandom(); Cipher aescipher; Cipher rsacipher; KeyGenerator aesgenerator; Key symkey; try { aesgenerator = KeyGenerator.getInstance(symmetricKeyType, provider); aesgenerator.init(128, random); symkey = aesgenerator.generateKey(); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SystemStateException("The specified symkey could not be generated.", ex); } try { aescipher = Cipher.getInstance(symmetricEncoding, provider); rsacipher = Cipher.getInstance(asymmetricEncoding, provider); aescipher.init(Cipher.ENCRYPT_MODE, symkey); rsacipher.init(Cipher.ENCRYPT_MODE, targetKey); } catch (NoSuchAlgorithmException | NoSuchProviderException | /*InvalidKeySpecException |*/ NoSuchPaddingException | InvalidKeyException ex) { throw new SystemStateException("The specified encryption provider or algorithm was not found", ex); } String encryptedLicense; try { byte[] encryptedsymkey = rsacipher.doFinal(symkey.getEncoded()); byte[] encryptedlicense = aescipher.doFinal(licenseAsBytes); byte[] licenseWithKey = new byte[encryptedsymkey.length + encryptedlicense.length]; System.arraycopy(encryptedsymkey, 0, licenseWithKey, 0, encryptedsymkey.length); System.arraycopy(encryptedlicense, 0, licenseWithKey, encryptedsymkey.length, encryptedlicense.length); encryptedLicense = Base64.encodeBase64String(licenseWithKey); } catch (IllegalBlockSizeException | BadPaddingException ex) { throw new OperationException("Could not encode to base64", ex); } return encryptedLicense; }
From source file:com.grarak.kerneladiutor.activities.SecurityActivity.java
private void loadFingerprint() { try {/*from w w w. jav a 2 s .c o m*/ KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); 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(); SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null); mCipher.init(Cipher.ENCRYPT_MODE, key); } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException | UnrecoverableKeyException | InvalidKeyException | CertificateException | InvalidAlgorithmParameterException | IOException e) { return; } mCryptoObject = new FingerprintManagerCompat.CryptoObject(mCipher); FrameLayout fingerprintParent = (FrameLayout) findViewById(R.id.fingerprint_parent); final SwirlView swirlView = new SwirlView(new ContextThemeWrapper(this, R.style.Swirl)); swirlView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); fingerprintParent.addView(swirlView); fingerprintParent.setVisibility(View.VISIBLE); mFingerprintUiHelper = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManagerCompat) .build(swirlView, new FingerprintUiHelper.Callback() { @Override public void onAuthenticated() { try { mCipher.doFinal(SECRET_MESSAGE.getBytes()); mPasswordWrong.setVisibility(View.GONE); setResult(1); finish(); } catch (IllegalBlockSizeException | BadPaddingException e) { e.printStackTrace(); swirlView.setState(SwirlView.State.ERROR); } } @Override public void onError() { } }); mFingerprintUiHelper.startListening(mCryptoObject); }