List of usage examples for android.security.keystore KeyProperties KEY_ALGORITHM_AES
String KEY_ALGORITHM_AES
To view the source code for android.security.keystore KeyProperties KEY_ALGORITHM_AES.
Click Source Link
From source file:de.schildbach.wallet.util.FingerprintHelper.java
@RequiresApi(api = Build.VERSION_CODES.M) private boolean initKeyStore() { try {/*from www . j av a2 s .c o m*/ keyStore = KeyStore.getInstance("AndroidKeyStore"); KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); keyStore.load(null); if (getLastIv() == null) { KeyGenParameterSpec keyGeneratorSpec = createKeyGenParameterSpec(); keyGenerator.init(keyGeneratorSpec); keyGenerator.generateKey(); } } catch (Throwable t) { log.info("Failed init of keyStore & keyGenerator: " + t.getMessage()); return false; } return true; }
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 . ja v a 2 s . com 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 {/*from w w w . jav a 2 s . 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.example.android.fingerprintdialog.MainActivity.java
/** * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()} * method.// ww w . j a va2 s . c o m * * @return {@code true} if initialization is successful, {@code false} if the lock screen has * been disabled or reset after the key was generated, or if a fingerprint got enrolled after * the key was generated. */ @TargetApi(VERSION_CODES.M) private boolean initCipher() { try { if (mKeyStore == null) { createKey(); } mKeyStore.load(null); SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null); mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); mCipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) { throw new RuntimeException("Failed to init Cipher", e); } }
From source file:com.owncloud.android.ui.activity.FingerprintActivity.java
@TargetApi(Build.VERSION_CODES.M) public boolean cipherInit() { try {//from w w w. jav a 2 s . c o m cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { return false; } try { keyStore.load(null); SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME, null); cipher.init(Cipher.ENCRYPT_MODE, key); return true; } catch (KeyPermanentlyInvalidatedException e) { return false; } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) { return false; } }
From source file:com.jefftharris.passwdsafe.SavedPasswordsMgr.java
/** * Get the cipher for the key protecting the saved password for a file *//* ww w .jav a 2 s .c o m*/ @TargetApi(Build.VERSION_CODES.M) private Cipher getKeyCipher(Uri fileUri, boolean encrypt) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, UnrecoverableKeyException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException { String keyName = getPrefsKey(fileUri); KeyStore keystore = getKeystore(); Key key = keystore.getKey(keyName, null); if (key == null) { throw new IOException(itsContext.getString(R.string.key_not_found, fileUri)); } Cipher ciph = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); if (encrypt) { ciph.init(Cipher.ENCRYPT_MODE, key); } else { SharedPreferences prefs = getPrefs(); String ivStr = prefs.getString(getIvPrefsKey(keyName), null); if (TextUtils.isEmpty(ivStr)) { throw new IOException("Key IV not found for " + fileUri); } byte[] iv = Base64.decode(ivStr, Base64.NO_WRAP); ciph.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); } return ciph; }
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 .j av a2 s. co m*/ */ @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.rnd.snapsplit.view.OwedFragment.java
@Nullable @Override/* w w w. ja v a2s . c o m*/ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //super.onCreate(savedInstanceState); view = inflater.inflate(R.layout.activity_owed, container, false); activity = getActivity(); profile = new Profile(getContext()); ((Toolbar) getActivity().findViewById(R.id.tool_bar_hamburger)).setVisibility(View.VISIBLE); mProgressBar = (ProgressBar) view.findViewById(R.id.progressBar); mMessageRecyclerView = (RecyclerView) view.findViewById(R.id.messageRecyclerView); mLinearLayoutManager = new LinearLayoutManager(getContext()); //mLinearLayoutManager.setStackFromEnd(true); mFirebaseDatabaseReference = FirebaseDatabase.getInstance().getReference().child("requests"); mFirebaseAdapter = new FirebaseRecyclerAdapter<PaymentRequest, MessageViewHolder>(PaymentRequest.class, R.layout.list_owed, MessageViewHolder.class, mFirebaseDatabaseReference.orderByChild("requestEpochDate")) { @Override protected PaymentRequest parseSnapshot(DataSnapshot snapshot) { PaymentRequest pr = super.parseSnapshot(snapshot); if (pr != null) { pr.setId(snapshot.getKey()); return pr; } return null; } @Override protected void populateViewHolder(final MessageViewHolder viewHolder, PaymentRequest pr, int position) { mProgressBar.setVisibility(ProgressBar.INVISIBLE); if (pr != null && pr.getReceipientPhoneNo().equals(profile.getPhoneNumber())) { if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) { String encodedReceipt = pr.getStrReceiptPic(); byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT); Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); viewHolder.receiptIcon.setImageBitmap(bitmap); } viewHolder.pr = pr; viewHolder.id = pr.getId(); viewHolder.description.setText(pr.getDescription()); viewHolder.from.setText( "Request sent by: " + pr.getRequestorName() + " - " + pr.getRequestorPhoneNumber()); viewHolder.share.setText("Your Share: HKD" + String.format("%.2f", pr.getShareAmount())); viewHolder.splitAmount .setText("Total Amount: HKD" + String.format("%.2f", pr.getTotalAmount())); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy' 'HH:mm:ss"); String date = null; Date temp = new Date(Long.parseLong(pr.getRequestEpochDate()) * (-1)); date = simpleDateFormat.format(temp); viewHolder.date.setText(date); } else { ViewGroup.LayoutParams params = viewHolder.item.getLayoutParams(); params.height = 0; viewHolder.item.setLayoutParams(params); } // log a view action on it //FirebaseUserActions.getInstance().end(getMessageViewAction(fd)); } @Override public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { MessageViewHolder viewHolder = super.onCreateViewHolder(parent, viewType); viewHolder.setOnLongClickListener(new MessageViewHolder.LongClickListener() { @Override public void onLongClick(View view, int position, String id, PaymentRequest pr) { AlertDialog.Builder ImageDialog = new AlertDialog.Builder(getActivity()); ImageDialog.setTitle("Receipt Preview - " + pr.getDescription()); ImageView showImage = new ImageView(getActivity()); Bitmap bitmap = null; if (pr.getStrReceiptPic() != null && !pr.getStrReceiptPic().equals("")) { String encodedReceipt = pr.getStrReceiptPic(); byte[] encodeByte = Base64.decode(encodedReceipt, Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length); } if (bitmap != null) { showImage.setImageBitmap(bitmap); } ImageDialog.setView(showImage); ImageDialog.setNegativeButton("Close Preview", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { } }); ImageDialog.show(); } }); viewHolder.setOnClickListener(new MessageViewHolder.ClickListener() { @Override public void onItemClick(View view, int position, String id, PaymentRequest pr) { //Toast.makeText(getActivity(), "Item clicked at " + position, Toast.LENGTH_SHORT).show(); Bundle bundle = new Bundle(); bundle.putSerializable("pr", pr); if (initCipher(mCipher, DEFAULT_KEY_NAME)) { // Show the fingerprint dialog. The user has the option to use the fingerprint with // crypto, or you can fall back to using a server-side verified password. DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication(); fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher)); boolean useFingerprintPreference = mSharedPreferences .getBoolean(getString(R.string.use_fingerprint_to_authenticate_key), true); if (useFingerprintPreference) { fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.FINGERPRINT); } else { fragment.setStage(DialogFragmentFingerprintAuthentication.Stage.PASSWORD); } fragment.setArguments(bundle); fragment.setTargetFragment(mFragment, 0); fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG); } else { // This happens if the lock screen has been disabled or or a fingerprint got // enrolled. Thus show the dialog to authenticate with their password first // and ask the user if they want to authenticate with fingerprints in the // future DialogFragmentFingerprintAuthentication fragment = new DialogFragmentFingerprintAuthentication(); fragment.setCryptoObject(new FingerprintManager.CryptoObject(mCipher)); fragment.setStage( DialogFragmentFingerprintAuthentication.Stage.NEW_FINGERPRINT_ENROLLED); fragment.setArguments(bundle); fragment.setTargetFragment(mFragment, 0); fragment.show(getFragmentManager(), DIALOG_FRAGMENT_TAG); } } }); return viewHolder; } }; mFirebaseAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() { @Override public void onItemRangeInserted(int positionStart, int itemCount) { super.onItemRangeInserted(positionStart, itemCount); int friendlyMessageCount = mFirebaseAdapter.getItemCount(); int lastVisiblePosition = mLinearLayoutManager.findLastCompletelyVisibleItemPosition(); // If the recycler view is initially being loaded or the user is at the bottom of the list, scroll // to the bottom of the list to show the newly added message. if (lastVisiblePosition == -1 || (positionStart >= (friendlyMessageCount - 1) && lastVisiblePosition == (positionStart - 1))) { mMessageRecyclerView.scrollToPosition(positionStart); } } }); mMessageRecyclerView.setLayoutManager(mLinearLayoutManager); mMessageRecyclerView.setAdapter(mFirebaseAdapter); try { mKeyStore = KeyStore.getInstance("AndroidKeyStore"); } catch (KeyStoreException e) { throw new RuntimeException("Failed to get an instance of KeyStore", e); } try { mKeyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { throw new RuntimeException("Failed to get an instance of KeyGenerator", e); } //Cipher defaultCipher; Cipher cipherNotInvalidated; try { mCipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); cipherNotInvalidated = 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); } mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext()); KeyguardManager keyguardManager = getActivity().getSystemService(KeyguardManager.class); FingerprintManager fingerprintManager = getActivity().getSystemService(FingerprintManager.class); if (!keyguardManager.isKeyguardSecure()) { // Show a message that the user hasn't set up a fingerprint or lock screen. Toast.makeText(getActivity(), "Secure lock screen hasn't set up.\n" + "Go to 'Settings -> Security -> Fingerprint' to set up a fingerprint", Toast.LENGTH_LONG).show(); //return; } // Now the protection level of USE_FINGERPRINT permission is normal instead of dangerous. // See http://developer.android.com/reference/android/Manifest.permission.html#USE_FINGERPRINT // The line below prevents the false positive inspection from Android Studio // noinspection ResourceType if (!fingerprintManager.hasEnrolledFingerprints()) { // This happens when no fingerprints are registered. Toast.makeText(getActivity(), "Go to 'Settings -> Security -> Fingerprint' and register at least one fingerprint", Toast.LENGTH_LONG).show(); //return; } createKey(DEFAULT_KEY_NAME, true); createKey(KEY_NAME_NOT_INVALIDATED, false); return view; }