Java Code Examples for android.security.keystore.KeyGenParameterSpec

The following are top voted examples for showing how to use android.security.keystore.KeyGenParameterSpec. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mapbook-android   File: CredentialCryptographer.java   View source code 8 votes vote down vote up
/**
 * Create a new key in the Keystore
 */
private void createNewKey(){
  try {
    final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null);

    final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);

    // Build one key to be used for encrypting and decrypting the file
    keyGenerator.init(
        new KeyGenParameterSpec.Builder(ALIAS,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .build());
    keyGenerator.generateKey();
    Log.i(TAG, "Key created in Keystore");

  }catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException  kS){
    Log.e(TAG, kS.getMessage());
  }
}
 
Example 2
Project: tink   File: AndroidKeystoreKmsClient.java   View source code 7 votes vote down vote up
/**
 * Generates a new key in Android Keystore.
 *
 * <p>At the moment it can generate only AES256-GCM keys.
 */
public static void generateNewAeadKey(String keyUri)
    throws GeneralSecurityException {
  String keyId = Validators.validateKmsKeyUriAndRemovePrefix(PREFIX, keyUri);
  KeyGenerator keyGenerator = KeyGenerator.getInstance(
      KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
  KeyGenParameterSpec spec =
      new KeyGenParameterSpec.Builder(keyId,
          KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
              .setKeySize(256)
              .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
              .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
              .build();
  keyGenerator.init(spec);
  keyGenerator.generateKey();
}
 
Example 3
Project: MakiLite   File: FingerprintUiHelper.java   View source code 6 votes vote down vote up
/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.
 */
public void createKey() {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder
        mKeyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        mKeyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        // Require the user to authenticate with a fingerprint to authorize every use
                        // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());
        mKeyGenerator.generateKey();
    } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Project: Fingerprint   File: CipherHelper.java   View source code 6 votes vote down vote up
private void createCipherKeyGenerator(){
    if(cipherKeyGenCreated){
        return;
    }
    try {
        cipherKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, provider);
        cipherKeyGenerator.init(new KeyGenParameterSpec.Builder(keyName,KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());

        cipherKeyGenCreated = true;
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException("Failed to create key generator", e);
    }
}
 
Example 5
Project: Taxi-Datalogger   File: MqttAuthentication.java   View source code 6 votes vote down vote up
/**
 * Generate a new RSA key pair entry in the Android Keystore by
 * using the KeyPairGenerator API. This creates both a KeyPair
 * and a self-signed certificate, both with the same alias
 */
private void generateAuthenticationKey() throws GeneralSecurityException {

  KeyPairGenerator kpg = KeyPairGenerator.getInstance(
      KeyProperties.KEY_ALGORITHM_RSA, keystoreName);
  kpg.initialize(new KeyGenParameterSpec.Builder(
      keyAlias,
      KeyProperties.PURPOSE_SIGN)
      .setKeySize(2048)
      .setCertificateSubject(new X500Principal("CN=unused"))
      .setDigests(KeyProperties.DIGEST_SHA256)
      .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
      .build());

  kpg.generateKeyPair();
}
 
Example 6
Project: CacheManage   File: KeyStoreHelper.java   View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
static void createKeysM(String alias, boolean requireAuth) {
    try {
        KeyPairGenerator keyPairGenerator =
                KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA,
                        SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
        keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(alias,
                KeyProperties.PURPOSE_ENCRYPT
                        | KeyProperties.PURPOSE_DECRYPT).setAlgorithmParameterSpec(
                new RSAKeyGenParameterSpec(1024, F4))
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384,
                        KeyProperties.DIGEST_SHA512)
                // Only permit the private key to be used if the user authenticated
                // within the last five minutes.
                .setUserAuthenticationRequired(requireAuth)
                .build());
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
    } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Project: GravityBox   File: FingerprintLauncher.java   View source code 6 votes vote down vote up
private void initFingerprintManager() throws Throwable {
    mFpManager = (FingerprintManager) mContext.getSystemService(Context.FINGERPRINT_SERVICE);
    if (!mFpManager.isHardwareDetected())
        throw new IllegalStateException("Fingerprint hardware not present");

    KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
    KeyGenerator keyGenerator = KeyGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    keyStore.load(null);
    keyGenerator.init(new KeyGenParameterSpec.Builder(
            KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
            .build());
    keyGenerator.generateKey();

    Cipher cipher = Cipher.getInstance(
            KeyProperties.KEY_ALGORITHM_AES + "/" +
            KeyProperties.BLOCK_MODE_CBC + "/" +
            KeyProperties.ENCRYPTION_PADDING_PKCS7);
    SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
    cipher.init(Cipher.ENCRYPT_MODE, key);

    mFpHandler = new FingerprintHandler(cipher);

    if (DEBUG) log("Fingeprint manager initialized");
}
 
Example 8
Project: sensorhub-cloud-iot   File: MqttAuthentication.java   View source code 6 votes vote down vote up
/**
 * Generate a new RSA key pair entry in the Android Keystore by
 * using the KeyPairGenerator API. This creates both a KeyPair
 * and a self-signed certificate, both with the same alias
 */
private void generateAuthenticationKey() throws GeneralSecurityException {

  KeyPairGenerator kpg = KeyPairGenerator.getInstance(
      KeyProperties.KEY_ALGORITHM_RSA, keystoreName);
  kpg.initialize(new KeyGenParameterSpec.Builder(
      keyAlias,
      KeyProperties.PURPOSE_SIGN)
      .setKeySize(2048)
      .setCertificateSubject(new X500Principal("CN=unused"))
      .setDigests(KeyProperties.DIGEST_SHA256)
      .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
      .build());

  kpg.generateKeyPair();
}
 
Example 9
Project: ReCRED_FIDO_UAF_OIDC   File: AndroidKeyStoreController.java   View source code 6 votes vote down vote up
public KeyPair generateKeyPair(String keyAlias)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException
{
    if (!allGood)
        return null;

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
            KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");

    keyPairGenerator.initialize(
            new KeyGenParameterSpec.Builder(
                    keyAlias,
                    KeyProperties.PURPOSE_SIGN)
                    .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
                    .setDigests(KeyProperties.DIGEST_SHA256)
                    .setUserAuthenticationRequired(true)
                    .setUserAuthenticationValidityDurationSeconds(5 * 60)
                    .build());

    return keyPairGenerator.generateKeyPair();
}
 
Example 10
Project: DiyCode   File: KeyStoreHelper.java   View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private static void createKeysM(String alias, boolean requireAuth)
    throws NoSuchProviderException, NoSuchAlgorithmException,
    InvalidAlgorithmParameterException {
    KeyPairGenerator keyPairGenerator =
        KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA,
            SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
    keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(alias,
        KeyProperties.PURPOSE_ENCRYPT
            | KeyProperties.PURPOSE_DECRYPT).setAlgorithmParameterSpec(
        new RSAKeyGenParameterSpec(1024, F4))
        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
        .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384,
            KeyProperties.DIGEST_SHA512)
        // Only permit the private key to be used if the user authenticated
        // within the last five minutes.
        .setUserAuthenticationRequired(requireAuth)
        .build());
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    Log.d(TAG, "Public Key is: " + keyPair.getPublic().toString());
}
 
Example 11
Project: android-fingerprint-example   File: MainActivity.java   View source code 6 votes vote down vote up
public void createKey() {
    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        mKeyStore.load(null);
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        mKeyGenerator.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());
        mKeyGenerator.generateKey();

    } catch (Exception e) {
        Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}
 
Example 12
Project: DynamicShuttleRide   File: MainActivity.java   View source code 6 votes vote down vote up
/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.
 */
public void createKey() {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        mKeyStore.load(null);
        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder
        mKeyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        // Require the user to authenticate with a fingerprint to authorize every use
                        // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());
        mKeyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
            | CertificateException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
Project: Android-Sensor-Programming-By-Example   File: FingerPrintActivity.java   View source code 6 votes vote down vote up
/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.
 */
public boolean initKey() {
    try {
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        mKeyStore.load(null);
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        mKeyGenerator.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());
        mKeyGenerator.generateKey();
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 14
Project: toshi-android-client   File: KeystoreHandler23.java   View source code 6 votes vote down vote up
@Override
protected void createNewKeysIfNeeded() throws KeyStoreException {
    try {
        if (this.keyStore.containsAlias(this.alias)) return;

        final KeyGenerator keyGenerator = KeyGenerator
                .getInstance(KeyProperties.KEY_ALGORITHM_AES, KeyStoreBase.ANDROID_KEY_STORE);

        keyGenerator.init(new KeyGenParameterSpec.Builder(this.alias,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setRandomizedEncryptionRequired(false)
                .build());

        keyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | InvalidAlgorithmParameterException | java.security.KeyStoreException e) {
        throw new KeyStoreException(new Throwable(e.getMessage()));
    }
}
 
Example 15
Project: OIDCAndroidLib   File: SensitiveDataPostApi23.java   View source code 6 votes vote down vote up
protected SecretKey generateKey() {
    SecretKey key = null;
    try {
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
                getKeyAlias(),
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);

        KeyGenParameterSpec keySpec = builder
                .setKeySize(CIPHER_KEY_LENGHT)
                .setBlockModes(CIPHER_BLOCKS)
                .setEncryptionPaddings(CIPHER_PADDING)
                .setRandomizedEncryptionRequired(false) //FIXME: set to true because we should be using IND-CPA but this means that a IV has to be store per token (less generic than i though)
                .setUserAuthenticationRequired(isKeyPinRequired())
                .setUserAuthenticationValidityDurationSeconds(getKeyPinDuration())
                .build();

        KeyGenerator  kg = KeyGenerator.getInstance(CIPHER_ALGO, KEYSTORE_TYPE);
        kg.init(keySpec);
        key = kg.generateKey();
    } catch (InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException e) {
        Log.e(TAG, "Couldn't generate secret key", e);
    }
    return key;
}
 
Example 16
Project: HardwareLibrary   File: CryptoHelper.java   View source code 6 votes vote down vote up
@Nullable private SecretKey createKey() {
    try {
        final KeyGenerator keyGen = KeyGenerator.getInstance(DEFAULT_ALGORITHM, KEY_STORE_ANDROID);
        keyGen.init(new KeyGenParameterSpec.Builder(keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(DEFAULT_BLOCK_MODE)
                .setEncryptionPaddings(DEFAULT_PADDING)
                .setKeySize(KEY_SIZE_DEFAULT)
                .setUserAuthenticationRequired(true)
                .build());
        return keyGen.generateKey();
    } catch (Exception exc) {
        if (Constants.DEBUG) {
            Log.e(TAG, "Could not create key", exc);
        }
    }
    return null;
}
 
Example 17
Project: LolliPin   File: FingerprintUiHelper.java   View source code 6 votes vote down vote up
/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.
 */
public void createKey() {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        // Set the alias of the entry in Android KeyStore where the key will appear
        // and the constrains (purposes) in the constructor of the Builder
        mKeyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        mKeyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        // Require the user to authenticate with a fingerprint to authorize every use
                        // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());
        mKeyGenerator.generateKey();
    } catch (NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Project: simple-marshmallow-samples   File: FingerprintActivity.java   View source code 6 votes vote down vote up
private static void generateKey() {
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER_NAME);

        keyGenerator.init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .setUserAuthenticationRequired(true)
                .setUserAuthenticationValidityDurationSeconds(AUTH_VALID_DURATION_IN_SECOND)
                .build());
        keyGenerator.generateKey();

    } catch (InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchProviderException e) {
        Log.e(TAG, e.getClass().getSimpleName(), e);
    }
}
 
Example 19
Project: android-java-connect-rest-sample   File: SensitiveDataPostApi23.java   View source code 6 votes vote down vote up
protected SecretKey generateKey() {
    SecretKey key = null;
    try {
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
                getKeyAlias(),
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);

        KeyGenParameterSpec keySpec = builder
                .setKeySize(CIPHER_KEY_LENGHT)
                .setBlockModes(CIPHER_BLOCKS)
                .setEncryptionPaddings(CIPHER_PADDING)
                .setRandomizedEncryptionRequired(false) //FIXME: set to true because we should be using IND-CPA but this means that a IV has to be store per token (less generic than i though)
                .setUserAuthenticationRequired(isKeyPinRequired())
                .setUserAuthenticationValidityDurationSeconds(getKeyPinDuration())
                .build();

        KeyGenerator  kg = KeyGenerator.getInstance(CIPHER_ALGO, KEYSTORE_TYPE);
        kg.init(keySpec);
        key = kg.generateKey();
    } catch (InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException e) {
        Log.e(TAG, "Couldn't generate secret key", e);
    }
    return key;
}
 
Example 20
Project: breadwallet-android   File: BRKeyStore.java   View source code 6 votes vote down vote up
private static SecretKey createKeys(String alias, boolean auth_required) throws InvalidAlgorithmParameterException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException {
    // Create the keys if necessary

    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);

    // 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(alias,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(NEW_BLOCK_MODE)
            .setUserAuthenticationRequired(auth_required)
            .setUserAuthenticationValidityDurationSeconds(AUTH_DURATION_SEC)
            .setRandomizedEncryptionRequired(false)
            .setEncryptionPaddings(NEW_PADDING)
            .build());
    return keyGenerator.generateKey();

}
 
Example 21
Project: AmazeFileManager   File: CryptUtil.java   View source code 6 votes vote down vote up
/**
 * Gets a secret key from Android key store.
 * If no key has been generated with a given alias then generate a new one
 * @return
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws InvalidAlgorithmParameterException
 * @throws UnrecoverableKeyException
 */
@RequiresApi(api = Build.VERSION_CODES.M)
private static Key getSecretKey() throws GeneralSecurityException, IOException {

    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ANDROID);
    keyStore.load(null);

    if (!keyStore.containsAlias(KEY_ALIAS_AMAZE)) {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEY_STORE_ANDROID);

        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_ALIAS_AMAZE,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);
        builder.setBlockModes(KeyProperties.BLOCK_MODE_GCM);
        builder.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE);
        builder.setRandomizedEncryptionRequired(false);

        keyGenerator.init(builder.build());
        return keyGenerator.generateKey();
    } else {
        return keyStore.getKey(KEY_ALIAS_AMAZE, null);
    }
}
 
Example 22
Project: masterpassword   File: FingerprintUtil.java   View source code 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
private static SecretKey createKey() throws FingerprintException {
    try {

        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_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                // Require the user to authenticate with a fingerprint to authorize every use
                // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());
        return keyGenerator.generateKey();

    } catch (Exception e) {
        throw new FingerprintException(App.get().getString(R.string.fingeprint_secretKeyGenerationFailed), e);
    }
}
 
Example 23
Project: FingerPrint-Authentication-With-React-Native-Android   File: Encryptor.java   View source code 5 votes vote down vote up
@NonNull
private SecretKey getSecretKey(final String alias) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidAlgorithmParameterException {

    final KeyGenerator keyGenerator = KeyGenerator
            .getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);

    keyGenerator.init(new KeyGenParameterSpec.Builder(alias,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .build());

    return keyGenerator.generateKey();
}
 
Example 24
Project: Automata   File: Login.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
private void generateKey() throws FingerprintException {
    try {
        // Obtain a reference to the Keystore using the standard Android keystore container identifier (“AndroidKeystore”)//
        keyStore = KeyStore.getInstance("AndroidKeyStore");

        //Generate the key//
        keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");

        //Initialize an empty KeyStore//
        keyStore.load(null);

        //Initialize the KeyGenerator//
        keyGenerator.init(new

                //Specify the operation(s) this key can be used for//
                KeyGenParameterSpec.Builder(KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)

                //Configure this key so that the user has to confirm their identity with a fingerprint each time they want to use it//
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(
                        KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());

        //Generate the key//
        keyGenerator.generateKey();

    } catch (KeyStoreException
            | NoSuchAlgorithmException
            | NoSuchProviderException
            | InvalidAlgorithmParameterException
            | CertificateException
            | IOException exc) {
        exc.printStackTrace();
        throw new FingerprintException(exc);
    }
}
 
Example 25
Project: citizen-sdk-android   File: CryptoService.java   View source code 5 votes vote down vote up
@TargetApi(23)
   public KeyPair createKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws CryptoException
{
	KeyPair keyPair = null;

	try {
		KeyStore mKeyStore = KeyStore.getInstance(REST_AUTH_KEYSTORE_NAME);
		mKeyStore.load(null);

		KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(
				KeyProperties.KEY_ALGORITHM_EC, REST_AUTH_KEYSTORE_NAME);


		KeyGenParameterSpec.Builder builder
				= new KeyGenParameterSpec.Builder(keyName,
				                                  KeyProperties.PURPOSE_ENCRYPT |
						                          KeyProperties.PURPOSE_DECRYPT |
						                          KeyProperties.PURPOSE_SIGN)
				.setDigests(KeyProperties.DIGEST_SHA256)
				.setAlgorithmParameterSpec(new ECGenParameterSpec(REST_AUTH_EC_CURVE))
				.setUserAuthenticationRequired(true);

           // This call is only available on API level >= 24.
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
		}

		keyPairGenerator.initialize(builder.build());
		keyPair = keyPairGenerator.generateKeyPair();

	} catch (NoSuchAlgorithmException | NoSuchProviderException | KeyStoreException |
		   InvalidAlgorithmParameterException | CertificateException | IOException e)
	{
		throw new CryptoException(e.getMessage());
	}

	return keyPair;
}
 
Example 26
Project: encryptedprefs   File: Vault.java   View source code 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
public SecretKey createSecretKey(String alias, short keySize)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, InvalidKeySpecException {

    ESLog.v("%s=>createSecretKey(%s, %d)", getClass().getSimpleName(), alias, keySize);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        ESLog.d("Generating KeyStore symmetric key.");

        KeyGenerator keyGenerator = KeyGenerator.getInstance(
                symmetricKeyAlgorithm(), KEYSTORE_PROVIDER);

        keyGenerator.init(new KeyGenParameterSpec.Builder(alias,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                .setKeySize(keySize)
                .setRandomizedEncryptionRequired(true)
                .setUserAuthenticationRequired(false)
                .build());

        SecretKey secretKey = keyGenerator.generateKey();
        if (secretKey == null) {
            ESLog.w("Could not generate KeyStore secret key.");
            return null;
        }
        ESLog.i("KeyStore secret key was generated.");
        return secretKey;
    }

    UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException();
    ESLog.wtf("Unsupported operation. This code should be called only from M onwards.", unsupportedOperationException.getCause());
    throw unsupportedOperationException;
}
 
Example 27
Project: buildAPKsSamples   File: MainActivity.java   View source code 5 votes vote down vote up
/**
 * 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.
 */
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);
    }
}
 
Example 28
Project: lock-screen   File: EnterPinActivity.java   View source code 5 votes vote down vote up
private void generateKey() throws FingerprintException {
    try {
        // Obtain a reference to the Keystore using the standard Android keystore container identifier (“AndroidKeystore”)//
        mKeyStore = KeyStore.getInstance("AndroidKeyStore");

        //Generate the key//
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");

        //Initialize an empty KeyStore//
        mKeyStore.load(null);

        //Initialize the KeyGenerator//
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mKeyGenerator.init(new

                    //Specify the operation(s) this key can be used for//
                    KeyGenParameterSpec.Builder(FINGER_PRINT_KEY,
                    KeyProperties.PURPOSE_ENCRYPT |
                            KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC)

                    //Configure this key so that the user has to confirm their identity with a fingerprint each time they want to use it//
                    .setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(
                            KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    .build());
        }

        //Generate the key//
        mKeyGenerator.generateKey();

    } catch (KeyStoreException
            | NoSuchAlgorithmException
            | NoSuchProviderException
            | InvalidAlgorithmParameterException
            | CertificateException
            | IOException exc) {
        throw new FingerprintException(exc);
    }
}
 
Example 29
Project: ReCRED_FIDO_UAF_OIDC   File: AndroidKeyStoreController.java   View source code 5 votes vote down vote up
public SecretKey generateSym() throws NoSuchAlgorithmException, NoSuchProviderException,
    InvalidAlgorithmParameterException
{
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");

    keyGenerator.init(new KeyGenParameterSpec.Builder("wrap.sym",
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setUserAuthenticationRequired(true)
            .setUserAuthenticationValidityDurationSeconds(5 * 60)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .build());

    return keyGenerator.generateKey();
}
 
Example 30
Project: AndroidFingerPrintDemo   File: CryptoObjectHelper.java   View source code 5 votes vote down vote up
void CreateKey() throws Exception
{
    KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGORITHM, KEYSTORE_NAME);
    KeyGenParameterSpec keyGenSpec =
            new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(BLOCK_MODE)
                    .setEncryptionPaddings(ENCRYPTION_PADDING)
                    .setUserAuthenticationRequired(true)
                    .build();
    keyGen.init(keyGenSpec);
    keyGen.generateKey();
}
 
Example 31
Project: pandroid   File: RsaAesCryptoManager.java   View source code 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
protected void initializeKeystoreAndroidM() throws KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    // Create new key if needed
    if (!keyStore.containsAlias(keyAlias)) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE);
        keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_ECB)
                .setUserAuthenticationRequired(false)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1).build());
        keyPairGenerator.generateKeyPair();
    }
}
 
Example 32
Project: LLApp   File: CryptoObjectHelper.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
void CreateKey() throws Exception
{
    KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGORITHM, KEYSTORE_NAME);
    KeyGenParameterSpec keyGenSpec =
            new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(BLOCK_MODE)
                    .setEncryptionPaddings(ENCRYPTION_PADDING)
                    .setUserAuthenticationRequired(true)
                    .build();
    keyGen.init(keyGenSpec);
    keyGen.generateKey();
}
 
Example 33
Project: react-native-sensitive-info   File: RNSensitiveInfoModule.java   View source code 5 votes vote down vote up
/**
 * Generates a new AES key and stores it under the { @code KEY_ALIAS_AES } in the
 * Android Keystore.
 */
private void initKeyStore() {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
        return;
    }
    try {
        mKeyStore = KeyStore.getInstance(ANDROID_KEYSTORE_PROVIDER);
        mKeyStore.load(null);

        // Check if a generated key exists under the KEY_ALIAS_AES .
        if (!mKeyStore.containsAlias(KEY_ALIAS_AES)) {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(
                    KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER);

            KeyGenParameterSpec.Builder builder = null;
            builder = new KeyGenParameterSpec.Builder(
                    KEY_ALIAS_AES,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);

            builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                    .setKeySize(256)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                    // forces user authentication with fingerprint
                    .setUserAuthenticationRequired(true);

            keyGenerator.init(builder.build());
            keyGenerator.generateKey();
        }
    } catch (Exception e) {
    }
}
 
Example 34
Project: AlchemistAndroidUtil   File: FingerprintHelper.java   View source code 5 votes vote down vote up
/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.
 */
@TargetApi(Build.VERSION_CODES.M)
public boolean createKey() {
    // The enrolling flow for fingerprint. This is where you ask the user to set up fingerprint
    // for your flow. Use of keys is necessary if you need to know if the set of
    // enrolled fingerprints has changed.
    try {
        keyStore.load(null);
        // 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)
                // Require the user to authenticate with a fingerprint to authorize every use
                // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());
        keyGenerator.generateKey();
        
        return true;
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
            | CertificateException | IOException e) {
        e.printStackTrace();
        Log.e(getClass().getSimpleName(), e.getMessage());
        return false;
    }
}
 
Example 35
Project: Auth0.Android   File: CryptoUtilTest.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
private KeyGenParameterSpec.Builder newKeyGenParameterSpecBuilder(KeyGenParameterSpec expectedBuilderOutput) {
    KeyGenParameterSpec.Builder builder = PowerMockito.mock(KeyGenParameterSpec.Builder.class);
    PowerMockito.when(builder.setKeySize(anyInt())).thenReturn(builder);
    PowerMockito.when(builder.setCertificateSubject(any(X500Principal.class))).thenReturn(builder);
    PowerMockito.when(builder.setCertificateSerialNumber(any(BigInteger.class))).thenReturn(builder);
    PowerMockito.when(builder.setCertificateNotBefore(any(Date.class))).thenReturn(builder);
    PowerMockito.when(builder.setCertificateNotAfter(any(Date.class))).thenReturn(builder);
    //noinspection WrongConstant
    PowerMockito.when(builder.setEncryptionPaddings(anyString())).thenReturn(builder);
    //noinspection WrongConstant
    PowerMockito.when(builder.setBlockModes(anyString())).thenReturn(builder);
    PowerMockito.when(builder.build()).thenReturn(expectedBuilderOutput);
    return builder;
}
 
Example 36
Project: PasswordRecorder   File: FingerCrypto.java   View source code 5 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
void CreateKey() throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance(KEY_ALGORITHM, KEYSTORE_NAME);
    KeyGenParameterSpec keyGenSpec =
            new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(BLOCK_MODE)
                    .setEncryptionPaddings(ENCRYPTION_PADDING)
                    .setUserAuthenticationRequired(true)
                    .build();
    keyGen.init(keyGenSpec);
    keyGen.generateKey();
}
 
Example 37
Project: fingerlock   File: Key.java   View source code 5 votes vote down vote up
public boolean recreateKey() {
    try {
        keyStore.load(null);


        // 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(keyName,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                // Require the user to authenticate with a fingerprint to authorize every use
                // of the key
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
                .build());

        keyGenerator.generateKey();

        Log.d(TAG, String.format("Key \"%s\" recreated", keyName));

        return true;

    } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException | CertificateException | InvalidAlgorithmParameterException e) {
        Log.e(TAG, "recreateKey: ", e);
        return false;
    }
}
 
Example 38
Project: Android-Vault   File: AbstractAndroidKeystoreSecretKeyWrapper.java   View source code 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private AlgorithmParameterSpec buildApi23AlgorithmParameterSpec(String alias, Calendar start, Calendar end, BigInteger serialNumber, X500Principal subject) {
    return new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_SIGN)
            .setCertificateSubject(subject)
            .setCertificateSerialNumber(serialNumber)
            .setKeyValidityStart(start.getTime())
            .setCertificateNotBefore(start.getTime())
            .setKeyValidityEnd(end.getTime())
            .setCertificateNotAfter(end.getTime())
            .setEncryptionPaddings(getEncryptionPadding())
            .setBlockModes(getBlockModes())
            .setDigests(getDigests())
            .build();
}
 
Example 39
Project: RxFingerprint   File: CipherProvider.java   View source code 5 votes vote down vote up
@NonNull
@TargetApi(Build.VERSION_CODES.M)
static KeyGenParameterSpec.Builder getKeyGenParameterSpecBuilder(String keyName, String blockModes, String encryptionPaddings, boolean invalidatedByBiometricEnrollment) {
	KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
			KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
			.setBlockModes(blockModes)
			.setUserAuthenticationRequired(true)
			.setEncryptionPaddings(encryptionPaddings);
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
		builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
	}
	return builder;
}
 
Example 40
Project: Passbook   File: FingerprintDialog.java   View source code 5 votes vote down vote up
private void initCipher(int mode) {
    try {
        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());
    }
}