Example usage for android.security.keystore KeyProperties PURPOSE_ENCRYPT

List of usage examples for android.security.keystore KeyProperties PURPOSE_ENCRYPT

Introduction

In this page you can find the example usage for android.security.keystore KeyProperties PURPOSE_ENCRYPT.

Prototype

int PURPOSE_ENCRYPT

To view the source code for android.security.keystore KeyProperties PURPOSE_ENCRYPT.

Click Source Link

Document

Purpose of key: encryption.

Usage

From source file:Main.java

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint.//from  ww  w.  java2  s.c o  m
 */
private static void createKey()
        throws CertificateException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException {
    // 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.
    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();
}

From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java

/**
 * Generate a saved password key for a file
 *//*from   w  w  w .  j av  a  2s.com*/
@TargetApi(Build.VERSION_CODES.M)
public synchronized void generateKey(Uri fileUri) throws InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, NoSuchProviderException, IOException {
    PasswdSafeUtil.dbginfo(TAG, "generateKey: %s", fileUri);

    if (!itsFingerprintMgr.hasEnrolledFingerprints()) {
        throw new IOException(itsContext.getString(R.string.no_fingerprints_registered));
    }

    String keyName = getPrefsKey(fileUri);
    try {
        KeyGenerator keyGen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, KEYSTORE);
        keyGen.init(new KeyGenParameterSpec.Builder(keyName,
                KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                        .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
                        .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).setKeySize(256)
                        .setUserAuthenticationRequired(true).build());
        keyGen.generateKey();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException e) {
        Log.e(TAG, "generateKey failure", e);
        removeSavedPassword(fileUri);
        throw e;
    }
}

From source file:com.z299studio.pb.FingerprintDialog.java

private void initCipher(int mode) {
    try {//from  w  w w  .j  a v  a2  s.  c  om
        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());
    }
}

From source file:com.grarak.kerneladiutor.activities.SecurityActivity.java

private void loadFingerprint() {
    try {//www. j a  va 2s . co m
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
                "AndroidKeyStore");
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);

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

        SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null);
        mCipher.init(Cipher.ENCRYPT_MODE, key);
    } catch (KeyStoreException | NoSuchProviderException | NoSuchAlgorithmException | NoSuchPaddingException
            | UnrecoverableKeyException | InvalidKeyException | CertificateException
            | InvalidAlgorithmParameterException | IOException e) {
        return;
    }

    mCryptoObject = new FingerprintManagerCompat.CryptoObject(mCipher);
    FrameLayout fingerprintParent = (FrameLayout) findViewById(R.id.fingerprint_parent);
    final SwirlView swirlView = new SwirlView(new ContextThemeWrapper(this, R.style.Swirl));
    swirlView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    fingerprintParent.addView(swirlView);
    fingerprintParent.setVisibility(View.VISIBLE);

    mFingerprintUiHelper = new FingerprintUiHelper.FingerprintUiHelperBuilder(mFingerprintManagerCompat)
            .build(swirlView, new FingerprintUiHelper.Callback() {
                @Override
                public void onAuthenticated() {
                    try {
                        mCipher.doFinal(SECRET_MESSAGE.getBytes());
                        mPasswordWrong.setVisibility(View.GONE);
                        setResult(1);
                        finish();
                    } catch (IllegalBlockSizeException | BadPaddingException e) {
                        e.printStackTrace();
                        swirlView.setState(SwirlView.State.ERROR);
                    }
                }

                @Override
                public void onError() {
                }
            });
    mFingerprintUiHelper.startListening(mCryptoObject);
}

From source file:de.schildbach.wallet.util.FingerprintHelper.java

@NonNull
@RequiresApi(api = Build.VERSION_CODES.M)
private KeyGenParameterSpec createKeyGenParameterSpec() {
    return new KeyGenParameterSpec.Builder(KEYSTORE_ALIAS,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
                    .setBlockModes(KeyProperties.BLOCK_MODE_CBC).setUserAuthenticationRequired(true)
                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7).build();
}

From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java

/**
 * 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.
 *///  w  w w .j  a  va 2  s .  c  o m
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);
    }
}

From source file:com.owncloud.android.ui.activity.FingerprintActivity.java

@TargetApi(Build.VERSION_CODES.M)
protected void generateKey() {
    try {// w  w w . jav  a 2s. c o m
        keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
    } catch (Exception e) {
        Log_OC.e(TAG, "Error getting KeyStore", e);
    }

    KeyGenerator keyGenerator;
    try {
        keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        return;
    }

    try {
        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();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | CertificateException
            | IOException e) {
        return;
    }
}

From source file:com.keepassdroid.fingerprint.FingerPrintHelper.java

private void createNewKeyIfNeeded(final boolean allowDeleteExisting) {
    if (!isFingerprintInitialized()) {
        return;/*w w  w.  j a  v a 2s  .com*/
    }
    try {
        keyStore.load(null);
        if (allowDeleteExisting && keyStore.containsAlias(ALIAS_KEY)) {

            keyStore.deleteEntry(ALIAS_KEY);
        }

        // Create new key if needed
        if (!keyStore.containsAlias(ALIAS_KEY)) {
            // Set the alias of the entry in Android KeyStore where the key will appear
            // and the constrains (purposes) in the constructor of the Builder
            AlgorithmParameterSpec algSpec = KeyGenParameterSpecCompat.build(ALIAS_KEY,
                    KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT, KeyProperties.BLOCK_MODE_CBC,
                    true, KeyProperties.ENCRYPTION_PADDING_PKCS7);

            keyGenerator.init(algSpec);
            keyGenerator.generateKey();
        }
    } catch (final Exception e) {
        fingerPrintCallback.onException();
    }
}

From source file:com.example.android.fingerprintdialog.MainActivity.java

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint./*from www . ja  va 2 s  .  c  om*/
 */
@TargetApi(VERSION_CODES.M)
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 = KeyStore.getInstance("AndroidKeyStore");
        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
        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)
                        // 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();
    } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | KeyStoreException
            | CertificateException | NoSuchProviderException | IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.home.pr.opendoor.MainActivity.java

/**
 * Creates a symmetric key in the Android Key Store which can only be used after the user has
 * authenticated with fingerprint./*  ww  w  .  j  a va 2  s .co  m*/
 */
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);
    }
}