android.security.keystore.KeyGenParameterSpec Java Examples

The following examples show how to use android.security.keystore.KeyGenParameterSpec. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestActivity.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
public boolean createKeyPair() {
    try {
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
                .setDigests(KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
                .setKeySize(2048);
        builder.setIsStrongBoxBacked(true);
        builder.setInvalidatedByBiometricEnrollment(true);
        builder.setUserAuthenticationRequired(true);

        keyPairGenerator.initialize(builder.build());
        keyPairGenerator.generateKeyPair();
        return true;
    } catch (InvalidAlgorithmParameterException e) {
        return false;
    }
}
 
Example #2
Source File: KeyStoreHelper.java    From Hauk with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves a key store helper for the given key store alias.
 *
 * @param alias The alias to retrieve a helper for.
 */
public KeyStoreHelper(KeyStoreAlias alias) {
    try {
        // Load the key store if not already loaded.
        if (store == null) loadKeyStore();

        // Check if the alias exists. If not, create it.
        if (!store.containsAlias(alias.getAlias())) {
            Log.i("Generating new key for alias %s", alias); //NON-NLS
            KeyGenerator keygen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
            KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias.getAlias(), KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    .build();
            keygen.init(spec);
            this.key = keygen.generateKey();
        } else {
            Log.i("Loading existing key for alias %s", alias); //NON-NLS
            KeyStore.SecretKeyEntry keyEntry = (KeyStore.SecretKeyEntry) store.getEntry(alias.getAlias(), null);
            this.key = keyEntry.getSecretKey();
        }
    } catch (Exception e) {
        Log.e("Unable to load key store or generate keys", e); //NON-NLS
    }
}
 
Example #3
Source File: Cryptography.java    From zap-android with MIT License 6 votes vote down vote up
@RequiresApi(api = Build.VERSION_CODES.M)
protected void generateKeysForAPIMOrGreater(String keyAlias) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
    KeyGenerator keyGenerator;
    keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE_NAME);
    keyGenerator.init(
            new KeyGenParameterSpec.Builder(keyAlias,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
                    // NOTE no Random IV. According to above this is less secure but acceptably so.
                    .setRandomizedEncryptionRequired(false)
                    .build());
    // Note according to [docs](https://developer.android.com/reference/android/security/keystore/KeyGenParameterSpec.html)
    // this generation will also add it to the keystore.
    keyGenerator.generateKey();
}
 
Example #4
Source File: CredentialSafe.java    From android-webauthn-authenticator with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Generate a new ES256 keypair (COSE algorithm -7, ECDSA + SHA-256 over the NIST P-256 curve).
 *
 * @param alias The alias used to identify this keypair in the keystore. Needed to use key
 *              in the future.
 * @return The KeyPair object representing the newly generated keypair.
 * @throws VirgilException
 */
private KeyPair generateNewES256KeyPair(String alias) throws VirgilException {
    KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec(CURVE_NAME))
            .setDigests(KeyProperties.DIGEST_SHA256)
            .setUserAuthenticationRequired(this.authenticationRequired) // fingerprint or similar
            .setUserConfirmationRequired(false) // TODO: Decide if we support Android Trusted Confirmations
            .setInvalidatedByBiometricEnrollment(false)
            .setIsStrongBoxBacked(this.strongboxRequired)
            .build();
    try {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, KEYSTORE_TYPE);
        keyPairGenerator.initialize(spec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        throw new VirgilException("couldn't generate key pair: " + e.toString());
    }
}
 
Example #5
Source File: CryptUtil.java    From PowerFileExplorer with GNU General Public License v3.0 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 KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, NoSuchProviderException,
        InvalidAlgorithmParameterException,
        UnrecoverableKeyException {

    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 #6
Source File: AttestationProtocol.java    From Auditor with MIT License 6 votes vote down vote up
static void generateKeyPair(final String algorithm, final KeyGenParameterSpec spec)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidAlgorithmParameterException, IOException {
    // Handle RuntimeExceptions caused by a broken keystore. A common issue involves users
    // unlocking the device and wiping the encrypted TEE attestation keys from the persist
    // partition. Additionally, some non-CTS compliant devices or operating systems have a
    // non-existent or broken implementation. No one has reported these uncaught exceptions,
    // presumably because they know their device or OS is broken, but the crash reports are
    // being spammed to the Google Play error collection and causing it to think the app is
    // unreliable.
    try {
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm,
                "AndroidKeyStore");
        keyPairGenerator.initialize(spec);
        keyPairGenerator.generateKeyPair();
    } catch (final ProviderException e) {
        throw new IOException(e);
    }
}
 
Example #7
Source File: PFSecurityUtils.java    From PFLockScreen-Android with Apache License 2.0 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.M)
private boolean generateKey(String keystoreAlias, boolean isAuthenticationRequired)  {
    try {
        final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
        keyGenerator.initialize(
                new KeyGenParameterSpec.Builder(keystoreAlias,
                        KeyProperties.PURPOSE_ENCRYPT |
                                KeyProperties.PURPOSE_DECRYPT)
                        .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
                        .setUserAuthenticationRequired(isAuthenticationRequired)
                        .build());
        keyGenerator.generateKeyPair();
        return true;

    } catch ( NoSuchAlgorithmException
            | NoSuchProviderException
            | InvalidAlgorithmParameterException exc) {
        exc.printStackTrace();
        return false;
    }
}
 
Example #8
Source File: KeyStoreHelper.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
private static SecretKey createKeyStoreEntry() {
  try {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
    KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
        .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
        .build();

    keyGenerator.init(keyGenParameterSpec);

    return keyGenerator.generateKey();
  } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
}
 
Example #9
Source File: CryptoObjectCreator.java    From LockDemo with Apache License 2.0 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.
 */
private 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) {
        Log.e(""," Failed to createKey, e:");
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: MainActivity.java    From android-biometricprompt with Apache License 2.0 6 votes vote down vote up
private KeyPair generateKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");

    KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
            KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
            .setDigests(KeyProperties.DIGEST_SHA256,
                    KeyProperties.DIGEST_SHA384,
                    KeyProperties.DIGEST_SHA512)
            // Require the user to authenticate with a biometric to authorize every use of the key
            .setUserAuthenticationRequired(true);

    // Generated keys will be invalidated if the biometric templates are added more to user device
    if (Build.VERSION.SDK_INT >= 24) {
        builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);
    }

    keyPairGenerator.initialize(builder.build());

    return keyPairGenerator.generateKeyPair();
}
 
Example #11
Source File: KeystoreTool.java    From secure-storage-android with Apache License 2.0 6 votes vote down vote up
@RequiresApi(api = M)
private static void generateKeyPairForMarshmallow(@NonNull Context context) throws SecureStorageException {
    try {
        if (isRTL(context)) {
            Locale.setDefault(Locale.US);
        }

        KeyPairGenerator generator = KeyPairGenerator.getInstance(KEY_ENCRYPTION_ALGORITHM, KEY_KEYSTORE_NAME);

        KeyGenParameterSpec keyGenParameterSpec =
                new KeyGenParameterSpec.Builder(KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                        .build();

        generator.initialize(keyGenParameterSpec);
        generator.generateKeyPair();
    } catch (Exception e) {
        throw new SecureStorageException(e.getMessage(), e, KEYSTORE_EXCEPTION);
    }
}
 
Example #12
Source File: CipherHelper.java    From Fingerprint with MIT License 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 #13
Source File: AuthKeyGenerator.java    From sensorhub-cloud-iot with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new 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,
 * using the {@link #keyAlgorithm} provided.
 */
private void generateAuthenticationKey() throws GeneralSecurityException {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgorithm, keystoreName);
    KeyGenParameterSpec.Builder specBuilder =
            new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_SIGN)
            .setCertificateSubject(new X500Principal("CN=unused"))
            .setDigests(KeyProperties.DIGEST_SHA256);

    if (keyAlgorithm.equals(KeyProperties.KEY_ALGORITHM_RSA)) {
        specBuilder.setKeySize(KEY_SIZE_RSA)
                .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1);
    } else if (keyAlgorithm.equals(KeyProperties.KEY_ALGORITHM_EC)) {
        specBuilder.setKeySize(KEY_SIZE_EC);
    }
    kpg.initialize(specBuilder.build());

    kpg.generateKeyPair();
}
 
Example #14
Source File: FingerprintActivity.java    From AndroidSamples with Apache License 2.0 6 votes vote down vote up
/**
 * Generate NIST P-256 EC Key pair for signing and verification
 *
 * @param keyName
 * @param invalidatedByBiometricEnrollment
 * @return
 * @throws Exception
 */
@TargetApi(Build.VERSION_CODES.P)
private KeyPair generateKeyPair(String keyName, boolean invalidatedByBiometricEnrollment) throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore");

    KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName,
            KeyProperties.PURPOSE_SIGN)
            .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
            .setDigests(KeyProperties.DIGEST_SHA256,
                    KeyProperties.DIGEST_SHA384,
                    KeyProperties.DIGEST_SHA512)
            // Require the user to authenticate with a biometric to authorize every use of the key
            .setUserAuthenticationRequired(true)
            .setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment);

    keyPairGenerator.initialize(builder.build());

    return keyPairGenerator.generateKeyPair();
}
 
Example #15
Source File: FingerprintActivity.java    From AndroidSamples with Apache License 2.0 6 votes vote down vote up
/**
 * 创建密钥
 */
@TargetApi(Build.VERSION_CODES.M)
private void initKey() {
    try {
        keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(DEFAULT_KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
        keyGenerator.init(builder.build());
        keyGenerator.generateKey();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source File: FingerprintUtil.java    From masterpassword with GNU General Public License v3.0 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 #17
Source File: TestActivity.java    From Telegram-FOSS with GNU General Public License v2.0 6 votes vote down vote up
public boolean createKeyPair() {
    try {
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEY_NAME, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT)
                .setDigests(KeyProperties.DIGEST_SHA1, KeyProperties.DIGEST_SHA256)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
                .setKeySize(2048);
        builder.setIsStrongBoxBacked(true);
        builder.setInvalidatedByBiometricEnrollment(true);
        builder.setUserAuthenticationRequired(true);

        keyPairGenerator.initialize(builder.build());
        keyPairGenerator.generateKeyPair();
        return true;
    } catch (InvalidAlgorithmParameterException e) {
        return false;
    }
}
 
Example #18
Source File: MainActivity.java    From android-AsymmetricFingerprintDialog with Apache License 2.0 6 votes vote down vote up
/**
 * Generates an asymmetric key pair in the Android Keystore. Every use of the private key must
 * be authorized by the user authenticating with fingerprint. Public key use is unrestricted.
 */
public void createKeyPair() {
    // 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
        mKeyPairGenerator.initialize(
                new KeyGenParameterSpec.Builder(KEY_NAME,
                        KeyProperties.PURPOSE_SIGN)
                        .setDigests(KeyProperties.DIGEST_SHA256)
                        .setAlgorithmParameterSpec(new ECGenParameterSpec("secp256r1"))
                        // Require the user to authenticate with a fingerprint to authorize
                        // every use of the private key
                        .setUserAuthenticationRequired(true)
                        .build());
        mKeyPairGenerator.generateKeyPair();
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    }
}
 
Example #19
Source File: SensitiveDataPostApi23.java    From android-java-connect-rest-sample with MIT License 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
Source File: FingerprintUiHelper.java    From LolliPin with MIT License 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 #21
Source File: CipherStorageKeystoreRsaEcb.java    From react-native-keychain with MIT License 6 votes vote down vote up
/** Get builder for encryption and decryption operations with required user Authentication. */
@NonNull
@Override
@SuppressLint("NewApi")
protected KeyGenParameterSpec.Builder getKeyGenSpecBuilder(@NonNull final String alias)
  throws GeneralSecurityException {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    throw new KeyStoreAccessException("Unsupported API" + Build.VERSION.SDK_INT + " version detected.");
  }

  final int purposes = KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT;

  return new KeyGenParameterSpec.Builder(alias, purposes)
    .setBlockModes(BLOCK_MODE_ECB)
    .setEncryptionPaddings(PADDING_PKCS1)
    .setRandomizedEncryptionRequired(true)
    .setUserAuthenticationRequired(true)
    .setUserAuthenticationValidityDurationSeconds(1)
    .setKeySize(ENCRYPTION_KEY_SIZE);
}
 
Example #22
Source File: CipherStorageKeystoreAesCbc.java    From react-native-keychain with MIT License 6 votes vote down vote up
/** Get encryption algorithm specification builder instance. */
@NonNull
@Override
protected KeyGenParameterSpec.Builder getKeyGenSpecBuilder(@NonNull final String alias)
  throws GeneralSecurityException {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    throw new KeyStoreAccessException("Unsupported API" + Build.VERSION.SDK_INT + " version detected.");
  }

  final int purposes = KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT;

  return new KeyGenParameterSpec.Builder(alias, purposes)
    .setBlockModes(BLOCK_MODE_CBC)
    .setEncryptionPaddings(PADDING_PKCS7)
    .setRandomizedEncryptionRequired(true)
    .setKeySize(ENCRYPTION_KEY_SIZE);
}
 
Example #23
Source File: MainActivity.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
@TargetApi(23)
private void initKey() {
    try {
        keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(DEFAULT_KEY_NAME,
                KeyProperties.PURPOSE_ENCRYPT |
                        KeyProperties.PURPOSE_DECRYPT)
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setUserAuthenticationRequired(true)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);
        keyGenerator.init(builder.build());
        keyGenerator.generateKey();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #24
Source File: FingerprintDialog.java    From journaldev with MIT License 6 votes vote down vote up
public void createKey(String keyName) {
    // 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

        KeyGenParameterSpec.Builder builder = 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);

        mKeyGenerator.init(builder.build());
        mKeyGenerator.generateKey();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
            | CertificateException | IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
Source File: SecurePreferencesHelper.java    From PresencePublisher with MIT License 6 votes vote down vote up
public static SharedPreferences getSecurePreferences(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        try {
            KeyGenParameterSpec keyGenParameterSpec = MasterKeys.AES256_GCM_SPEC;
            String masterKeyAlias = MasterKeys.getOrCreate(keyGenParameterSpec);
            return EncryptedSharedPreferences
                    .create(
                            FILENAME,
                            masterKeyAlias,
                            context,
                            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
                            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
                    );
        } catch (Exception e) {
            HyperLog.w(TAG, "Unable to get secure preferences", e);
            throw new RuntimeException("Unable to get secure preferences");
        }
    } else {
        return context.getSharedPreferences(FILENAME, Context.MODE_PRIVATE);
    }
}
 
Example #26
Source File: AbstractAndroidKeystoreSecretKeyWrapper.java    From Android-Vault with Apache License 2.0 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 #27
Source File: CipherStorageKeystoreAesCbc.java    From react-native-keychain with MIT License 5 votes vote down vote up
/** Try to generate key from provided specification. */
@NonNull
@Override
protected Key generateKey(@NonNull final KeyGenParameterSpec spec) throws GeneralSecurityException {
  if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
    throw new KeyStoreAccessException("Unsupported API" + Build.VERSION.SDK_INT + " version detected.");
  }

  final KeyGenerator generator = KeyGenerator.getInstance(getEncryptionAlgorithm(), KEYSTORE_TYPE);

  // initialize key generator
  generator.init(spec);

  return generator.generateKey();
}
 
Example #28
Source File: KeyStoreHelper.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
public static SecretKey createKeyStoreEntryHmac() {
  try {
    KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_HMAC_SHA256, ANDROID_KEY_STORE);

    KeyGenParameterSpec.Builder keySpecBuilder = new KeyGenParameterSpec.Builder(KEY_ALIAS_HMAC, KeyProperties.PURPOSE_SIGN);
    KeyGenParameterSpec keyGenParameterSpec = keySpecBuilder.build();

    keyGenerator.init(keyGenParameterSpec);

    return keyGenerator.generateKey();
  } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
}
 
Example #29
Source File: CipherProvider.java    From RxFingerprint with Apache License 2.0 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 #30
Source File: SQRLStorage.java    From secure-quick-reliable-login with MIT License 5 votes vote down vote up
private void encryptIdentityKeyBiometric(byte[] encKey) {
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        try {
            KeyPairGenerator keyPairGenerator =
                    KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
            keyPairGenerator.initialize(new KeyGenParameterSpec.Builder(
                    "quickPass",
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT
                )
                .setAlgorithmParameterSpec(new RSAKeyGenParameterSpec(2048, F4))
                .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1)
                .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384,
                            KeyProperties.DIGEST_SHA512)
                .setUserAuthenticationRequired(true)
                .build());

            KeyPair keyPair = keyPairGenerator.generateKeyPair();

            Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); //or try with "RSA"
            cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());

            byte[] biometricKeyEncrypted = cipher.doFinal(encKey);

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("biometricKey", EncryptionUtils.byte2hex(biometricKeyEncrypted));
            editor.apply();

        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
        }
    }
}