KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(keyName, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setUserAuthenticationRequired(true) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7); builder.setInvalidatedByBiometricEnrollment(invalidatedByBiometricEnrollment); mKeyGenerator.init(builder.build()); mKeyGenerator.generateKey(); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException
KeyGenParameterSpec spec= new KeyGenParameterSpec.Builder( alias, KeyProperties.PURPOSE_SIGN|KeyProperties.PURPOSE_VERIFY) .setCertificateSubject(new X500Principal("CN=Inspeckage, OU=ACPM, O=ACPM, C=BR")) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1) .setCertificateNotBefore(start.getTime()) .setCertificateNotAfter(end.getTime()) .setKeyValidityStart(start.getTime()) .setKeyValidityEnd(end.getTime()) .setKeySize(2048) .setCertificateSerialNumber(BigInteger.valueOf(1)) .build();
final KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(attestationKeystoreAlias, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) .setAlgorithmParameterSpec(new ECGenParameterSpec(EC_CURVE)) .setDigests(KEY_DIGEST) .setAttestationChallenge(challenge) .setKeyValidityStart(startTime); if (hasPersistentKey) { builder.setKeyValidityEnd(new Date(startTime.getTime() + EXPIRE_OFFSET_MS)); generateKeyPair(KEY_ALGORITHM_EC, builder.build());
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder( KEYSTORE_WIGLE_CREDS_KEY_V1, KeyProperties.PURPOSE_DECRYPT | KeyProperties.PURPOSE_ENCRYPT) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP) .build();
final KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(KEYSTORE_ALIAS_SAMPLE, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) .setAlgorithmParameterSpec(new ECGenParameterSpec(AttestationProtocol.EC_CURVE)) .setDigests(AttestationProtocol.KEY_DIGEST) .setAttestationChallenge("sample".getBytes()); AttestationProtocol.generateKeyPair(KEY_ALGORITHM_EC, builder.build()); final Certificate[] certs = keyStore.getCertificateChain(KEYSTORE_ALIAS_SAMPLE); keyStore.deleteEntry(KEYSTORE_ALIAS_SAMPLE); if (Build.VERSION.SDK_INT >= 28) { try { builder.setIsStrongBoxBacked(true); AttestationProtocol.generateKeyPair(KEY_ALGORITHM_EC, builder.build()); strongBoxCerts = keyStore.getCertificateChain(KEYSTORE_ALIAS_SAMPLE); keyStore.deleteEntry(KEYSTORE_ALIAS_SAMPLE);
final KeyGenerator generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE_PROVIDER); generator.init( new KeyGenParameterSpec.Builder(AES_LOCAL_PROTECTION_KEY_ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setKeySize(AES_GCM_KEY_SIZE_IN_BITS) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .build()); key = generator.generateKey();
when(mAesBuilder.setBlockModes(anyString())).thenReturn(mAesBuilder); when(mAesBuilder.setEncryptionPaddings(anyString())).thenReturn(mAesBuilder); when(mAesBuilder.setKeySize(anyInt())).thenReturn(mAesBuilder); when(mAesBuilder.setKeyValidityForOriginationEnd(any(Date.class))).thenReturn(mAesBuilder); when(mAesBuilder.build()).thenReturn(mock(KeyGenParameterSpec.class)); when(mKeyStore.getEntry(argThat(new ArgumentMatcher<String>() {
keyGenerator.init(new KeyGenParameterSpec.Builder( alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(BLOCK_MODE) .setKeySize(256) .setUserAuthenticationRequired(false) .setRandomizedEncryptionRequired(true) .setEncryptionPaddings(PADDING) .build()); keyGenerator.generateKey();
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();
spec = new KeyGenParameterSpec.Builder(mAlias, KeyProperties.PURPOSE_SIGN) .setCertificateSubject(new X500Principal("CN=" + mAlias)) .setDigests(KeyProperties.DIGEST_SHA256) .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1) .setCertificateSerialNumber(BigInteger.valueOf(1337)) .setCertificateNotBefore(start.getTime()) .setCertificateNotAfter(end.getTime()) .build();
KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setCertificateSubject(new X500Principal(X500_PRINCIPAL)) .setCertificateSerialNumber(BigInteger.ONE) .setCertificateNotBefore(start.getTime()) .setCertificateNotAfter(end.getTime()) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) .setRandomizedEncryptionRequired(false) .build(); keyGenerator.initialize(spec); keyGenerator.generateKeyPair();
mKeyStore.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();
kpg.initialize(new KeyGenParameterSpec.Builder( alias, KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY) .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA512) .build());
@Override public void writeResult(PrintWriter out) throws GeneralSecurityException { String alias = intent.getStringExtra("alias"); String algorithm = intent.getStringExtra("algorithm"); int purposes = intent.getIntExtra("purposes", 0); String[] digests = intent.getStringArrayExtra("digests"); int size = intent.getIntExtra("size", 2048); String curve = intent.getStringExtra("curve"); int userValidity = intent.getIntExtra("validity", 0); KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(alias, purposes); builder.setDigests(digests); if (algorithm.equals(KeyProperties.KEY_ALGORITHM_RSA)) { // only the exponent 65537 is supported for now builder.setAlgorithmParameterSpec( new RSAKeyGenParameterSpec(size, RSAKeyGenParameterSpec.F4)); builder.setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1); } if (algorithm.equals(KeyProperties.KEY_ALGORITHM_EC)) { builder.setAlgorithmParameterSpec(new ECGenParameterSpec(curve)); } if (userValidity > 0) { builder.setUserAuthenticationRequired(true); builder.setUserAuthenticationValidityDurationSeconds(userValidity); } KeyPairGenerator generator = KeyPairGenerator.getInstance(algorithm, PROVIDER); generator.initialize(builder.build()); generator.generateKeyPair(); } });
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(); return true;
@TargetApi(M) public void createKeyPair() { KeyPairGenerator keyPairGenerator; try { keyPairGenerator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyPairGenerator", e); } /* By calling setUserAuthenticationRequired(true), we are indicating that any time the private key for this pair so to be used, we have to be authed via fingerprint. This is what enforces the invariant that the successful verification of the signature implies that an authorized individual has touched the fingerprint sensor. */ try { keyPairGenerator.initialize( new KeyGenParameterSpec.Builder(KEY_NAME, PURPOSE_SIGN) .setKeySize(2048) .setDigests(DIGEST_SHA256) .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1) .setUserAuthenticationRequired(true) .build()); keyPairGenerator.generateKeyPair(); } catch (InvalidAlgorithmParameterException e) { throw new RuntimeException("failed to generate key pair", e); } }
/** * 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) { FPLog.log(" Failed to createKey, e:" + Log.getStackTraceString(e)); throw new RuntimeException(e); } }
/** * 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); } }
/** * Prepares the key store and our keys for encrypting/decrypting. Keys will be generated if we * haven't done so yet, and keys will be re-generated if the old ones have been invalidated. In * both cases, our K/V store will be cleared before continuing. */ void prepareKeyStore() { try { Key key = keyStore.getKey(keyAlias, null); Certificate certificate = keyStore.getCertificate(keyAlias); if (key != null && certificate != null) { try { createCipher().init(Cipher.DECRYPT_MODE, key); // We have a keys in the store and they're still valid. return; } catch (KeyPermanentlyInvalidatedException e) { Log.d(TAG, "Key invalidated."); } } storage.clear(); keyGenerator.initialize(new KeyGenParameterSpec.Builder(keyAlias, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) // .setBlockModes(KeyProperties.BLOCK_MODE_ECB) // .setUserAuthenticationRequired(true) // .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_PKCS1) // .build()); keyGenerator.generateKeyPair(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
private static void checkMigrateKeystoreVersion2(SharedPreferences prefs, Context context) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) { try { final KeyStore keyStore = getKeyStore(); if (keyStore.containsAlias(KEYSTORE_WIGLE_CREDS_KEY_V2)) { MainActivity.info("[TOKEN] Key present and up-to-date V2 AES - no change."); return; } // get old token final String token = getApiToken(prefs); MainActivity.info("Got old token, length: " + (token == null ? null : token.length())); // set up aes key KeyGenerator keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE); keyGenerator.init( new KeyGenParameterSpec.Builder(KEYSTORE_WIGLE_CREDS_KEY_V2, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .build()); keyGenerator.generateKey(); if (token != null && !token.isEmpty()) setApiToken(prefs, token); } catch (Exception ex) { MainActivity.error("Exception migrating to version 2: " + ex, ex); } } }