Example usage for android.security.keystore KeyProperties KEY_ALGORITHM_AES

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

Introduction

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

Prototype

String KEY_ALGORITHM_AES

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

Click Source Link

Document

Advanced Encryption Standard (AES) key.

Usage

From source file:Main.java

/**
 * Initializes the keystore and creates the key if necessary
 *
 * @return true, if a new key has been generated
 * @throws GeneralSecurityException/*from  w w w.jav a2 s .c o  m*/
 * @throws IOException
 */
static boolean init() throws GeneralSecurityException, IOException {
    mKeyStore = KeyStore.getInstance("AndroidKeyStore");
    mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    if (!hasKey()) {
        createKey();
        return true;
    } else {
        return false;
    }
}

From source file:com.elkriefy.android.apps.authenticationexample.fingerprintdialog.FingerprintModule.java

@Provides
public KeyGenerator providesKeyGenerator() {
    try {/*from  w  ww. ja  v a 2s  .  com*/
        return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    }
}

From source file:com.elkriefy.android.apps.authenticationexample.fingerprintdialog.FingerprintModule.java

@Provides
public Cipher providesCipher(KeyStore keyStore) {
    try {/*from   w  w w .j a va  2 s.c om*/
        return Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
}

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

/**
 * Tries to encrypt some data with the generated key in {@link #createKey} which is
 * only works if the user has just authenticated via device credentials.
 *//*from  w  w w.j  ava2 s  . co  m*/
private boolean tryEncrypt() {
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null);
        Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC
                + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);

        // Try encrypting something, it will only work if the user authenticated within
        // the last AUTHENTICATION_DURATION_SECONDS seconds.
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        cipher.doFinal(SECRET_BYTE_ARRAY);

        // If the user has recently authenticated, you will reach here.
        showAlreadyAuthenticated();
        return true;
    } catch (UserNotAuthenticatedException e) {
        // User is not authenticated, let's authenticate with device credentials.
        showAuthenticationScreen();
        return false;
    } catch (KeyPermanentlyInvalidatedException e) {
        // This happens if the lock screen has been disabled or reset after the key was
        // generated after the key was generated.
        Toast.makeText(this, "Keys are invalidated after created. Retry the purchase\n" + e.getMessage(),
                Toast.LENGTH_LONG).show();
        return false;
    } catch (BadPaddingException | IllegalBlockSizeException | KeyStoreException | CertificateException
            | UnrecoverableKeyException | IOException | NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidKeyException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Generate a saved password key for a file
 *//*from ww w  . ja  v a  2  s.  c om*/
@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:de.niklasmerz.cordova.fingerprint.Fingerprint.java

/**
 * Sets the context of the Command. This can then be used to do things like
 * get file paths associated with the Activity.
 *
 * @param cordova The context of the main Activity.
 * @param webView The CordovaWebView Cordova is running in.
 *//*w w w .j a v a  2s  .c om*/

public void initialize(CordovaInterface cordova, CordovaWebView webView) {
    super.initialize(cordova, webView);
    Log.v(TAG, "Init Fingerprint");
    packageName = cordova.getActivity().getApplicationContext().getPackageName();
    mPluginResult = new PluginResult(PluginResult.Status.NO_RESULT);

    if (android.os.Build.VERSION.SDK_INT < 23) {
        return;
    }

    mKeyguardManager = cordova.getActivity().getSystemService(KeyguardManager.class);
    mFingerPrintManager = cordova.getActivity().getApplicationContext()
            .getSystemService(FingerprintManager.class);

    try {
        mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE);
        mKeyStore = KeyStore.getInstance(ANDROID_KEY_STORE);

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    } catch (NoSuchProviderException e) {
        throw new RuntimeException("Failed to get an instance of KeyGenerator", e);
    } catch (KeyStoreException e) {
        throw new RuntimeException("Failed to get an instance of KeyStore", e);
    }

    try {
        mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/"
                + KeyProperties.ENCRYPTION_PADDING_PKCS7);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    } catch (NoSuchPaddingException e) {
        throw new RuntimeException("Failed to get an instance of Cipher", e);
    }
}

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

private void initCipher(int mode) {
    try {//from   w  w  w  .  j  av a2s .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.ja va2s.  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

@Nullable
@RequiresApi(api = Build.VERSION_CODES.M)
private Cipher createCipher(int mode) throws NoSuchPaddingException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, InvalidKeyException, InvalidAlgorithmParameterException {
    Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC
            + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);

    Key key = keyStore.getKey(KEYSTORE_ALIAS, null);
    if (key == null) {
        return null;
    }/*from  ww w. j av  a2  s  . c  o m*/
    if (mode == Cipher.ENCRYPT_MODE) {
        cipher.init(mode, key);
        byte[] iv = cipher.getIV();
        saveIv(iv);
    } else {
        byte[] lastIv = getLastIv();
        cipher.init(mode, key, new IvParameterSpec(lastIv));
    }
    return cipher;
}

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

public FingerPrintHelper(final Context context, final FingerPrintCallback fingerPrintCallback) {

    if (!isFingerprintSupported()) {
        // really not much to do when no fingerprint support found
        setInitOk(false);//w ww  . jav a  2 s. co  m
        return;
    }
    this.fingerprintManager = FingerprintManagerCompat.from(context);
    this.keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
    this.fingerPrintCallback = fingerPrintCallback;

    if (hasEnrolledFingerprints()) {
        try {
            this.keyStore = KeyStore.getInstance("AndroidKeyStore");
            this.keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
            this.cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
                    + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
            this.cryptoObject = new FingerprintManagerCompat.CryptoObject(cipher);
            setInitOk(true);
        } catch (final Exception e) {
            setInitOk(false);
            fingerPrintCallback.onException();
        }
    }
}