Java Code Examples for android.security.keystore.KeyProperties#PURPOSE_ENCRYPT

The following examples show how to use android.security.keystore.KeyProperties#PURPOSE_ENCRYPT . 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: 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 2
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 3
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 4
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 5
Source File: RNSensitiveInfoModule.java    From react-native-sensitive-info with MIT License 5 votes vote down vote up
private void prepareKey() throws Exception {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
        return;
    }
    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);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        try {
            builder.setInvalidatedByBiometricEnrollment(invalidateEnrollment);
        } catch (Exception e) {
            Log.d("RNSensitiveInfo", "Error setting setInvalidatedByBiometricEnrollment: " + e.getMessage());
        }
    }

    keyGenerator.init(builder.build());
    keyGenerator.generateKey();
}
 
Example 6
Source File: MainActivity.java    From SafeApp with Apache License 2.0 4 votes vote down vote up
/**
 * Generates a new AES key and stores it under the { @code KEY_ALIAS_AES } in the
 * Android Keystore.
 */
@SuppressWarnings("StatementWithEmptyBody")
private void generateAesKey() {
    try {
        // The KeyGenerator is an engine class for creating symmetric keys utilizing the
        // algorithm it was initialized with.
        KeyGenerator keyGenerator = KeyGenerator.getInstance(
                KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE_PROVIDER);

        // Create a new instance of the KeyGenParameterSpec.Builder, hand over
        // the key alias and the different purposes for which you want to use the key.
        // Keep in mind that you can only use the key for the operations you have specified
        // here - once the key is created it can't be changed.
        KeyGenParameterSpec.Builder builder = new KeyGenParameterSpec.Builder(
                KEY_ALIAS_AES,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT);

        // Define the basic encryption parameters for the key. The set configuration
        // matches the AES_DEFAULT_TRANSFORMATION constant.
        builder.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                .setKeySize(256)
                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7);

        if (mRadioUserAuthentication.isChecked()) {
            // Create a key which requires the user to be authenticated during
            // the last 30 seconds. Could also be 30 seconds or even 5 minutes -
            // choose whatever fits your security guidelines best.
            // Before continuing, check if the user has set up a secure lockscreen -
            // if not, prompt the user to set one up ;-)
            if (!hasSetupSecureLockscreen()) return;

            builder.setUserAuthenticationRequired(true)
                    .setUserAuthenticationValidityDurationSeconds(15);
        } else if (mRadioUserFingerprint.isChecked()) {
            // Create a key which needs fingerprint authentication every time.
            // Before continuing, check if the device supports fingerprint
            // authentication and if the user has at least enrolled one fingerprint -
            // if not, prompt the user to enroll one ;-)
            if (!hasSetupFingerprint()) return;

            builder.setUserAuthenticationRequired(true);
        } else {
            // Create a key which does not need any user authentication.
            // Nothing more to add here!
        }

        // Initialize the KeyGenerator with the KeyGenParameterSpec which will be created by
        // the KeyGenParameterSpec.Builder .
        keyGenerator.init(builder.build());

        // Finally, generate the key...
        keyGenerator.generateKey();

        // ...and show a TextView with a confirmation text.
        showSuccessTextView();
    } catch (NoSuchAlgorithmException | NoSuchProviderException
            | InvalidAlgorithmParameterException e) {
        throw new RuntimeException("Failed to create a symmetric key", e);
    }
}