private PrivateKey fetchPrivateKey(Context context, String alias) throws KeyChainException, InterruptedException, MessagingException { PrivateKey privateKey = KeyChain.getPrivateKey(context, alias); if (privateKey == null) { throw new MessagingException("No private key found for: " + alias); } return privateKey; }
public void chooseCertificate() { // NOTE: keyTypes, issuers, hosts, port are not known before we actually // open a connection, thus we cannot set them here! KeyChain.choosePrivateKeyAlias(mActivity, new KeyChainAliasCallback() { @Override public void alias(String alias) { Timber.d("User has selected client certificate alias: %s", alias); setAlias(alias); } }, null, null, null, -1, getAlias()); }
/** * Returns whether it may be possible to load the given URIs based on the network security * policy's cleartext traffic permissions. * * @param uris A list of URIs that will be loaded. * @return Whether it may be possible to load the given URIs. */ @TargetApi(24) public static boolean checkCleartextTrafficPermitted(Uri... uris) { if (Util.SDK_INT < 24) { // We assume cleartext traffic is permitted. return true; } for (Uri uri : uris) { if ("http".equals(uri.getScheme()) && !NetworkSecurityPolicy.getInstance().isCleartextTrafficPermitted(uri.getHost())) { // The security policy prevents cleartext traffic. return false; } } return true; }
private AlgorithmParameterSpec getParameterSpec(String alias) { GregorianCalendar start = new GregorianCalendar(); GregorianCalendar end = new GregorianCalendar(); end.add(Calendar.YEAR, 5); return new KeyPairGeneratorSpec.Builder(context) .setAlias(alias) .setSubject(new X500Principal("CN=" + alias)) .setSerialNumber(KEY_SERIAL_NUMBER) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); }
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(); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(mContext) .setAlias(alias) .setSubject(new X500Principal("CN=Inspeckage, OU=ACPM, O=ACPM, C=BR")) .setSerialNumber(BigInteger.valueOf(12345)) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build();
@Override public void run() { try { byte[] keychainBytes; FileInputStream is = null; try { is = new FileInputStream(CERTIFICATE_RESOURCE); keychainBytes = new byte[is.available()]; is.read(keychainBytes); } finally { IOUtils.closeQuietly(is); } Intent intent = KeyChain.createInstallIntent(); intent.putExtra(KeyChain.EXTRA_CERTIFICATE, keychainBytes); intent.putExtra(KeyChain.EXTRA_NAME, "NetworkDiagnosis CA Certificate"); startActivityForResult(intent, 3); } catch (Exception e) { e.printStackTrace(); } } };
private X509Certificate[] fetchCertificateChain(Context context, String alias) throws KeyChainException, InterruptedException, MessagingException { X509Certificate[] chain = KeyChain.getCertificateChain(context, alias); if (chain == null || chain.length == 0) { throw new MessagingException("No certificate chain found for: " + alias); } try { for (X509Certificate certificate : chain) { certificate.checkValidity(); } } catch (CertificateException e) { throw new CertificateValidationException(e.getMessage(), Reason.Expired, alias); } return chain; }
/** * @param alias Must not be null nor empty * @throws MessagingException * Indicates an error in retrieving the certificate for the alias * (likely because the alias is invalid or the certificate was deleted) */ public KeyChainKeyManager(Context context, String alias) throws MessagingException { mAlias = alias; try { mChain = fetchCertificateChain(context, alias); mPrivateKey = fetchPrivateKey(context, alias); } catch (KeyChainException e) { // The certificate was possibly deleted. Notify user of error. throw new CertificateValidationException(e.getMessage(), RetrievalFailure, alias); } catch (InterruptedException e) { throw new CertificateValidationException(e.getMessage(), RetrievalFailure, alias); } }
return new MessageDigest(java.security.MessageDigest.getInstance(algorithm));
/** * Attempt to show the certificate selection dialog and shows the provided * CertSelectionFailureDialog if the platform's cert selection activity can't be found. */ @VisibleForTesting static void maybeShowCertSelection(KeyChainCertSelectionWrapper keyChain, KeyChainAliasCallback callback, CertSelectionFailureDialog failureDialog) { try { keyChain.choosePrivateKeyAlias(); } catch (ActivityNotFoundException e) { // This exception can be hit when a platform is missing the activity to select // a client certificate. It gets handled here to avoid a crash. // Complete the callback without selecting a certificate. callback.alias(null); // Show a dialog letting the user know that the system does not support // client certificate selection. failureDialog.show(); } }
private static KeyPair generateWrapperKey(Context context, String alias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { KeyPairGenerator generator = KeyPairGenerator.getInstance(WRAPPER_KEY_ALGORITHM, KEYSTORE_PROVIDER); Calendar startDate = Calendar.getInstance(); Calendar endDate = Calendar.getInstance(); endDate.add(Calendar.YEAR, 25); KeyPairGeneratorSpec.Builder builder = new KeyPairGeneratorSpec.Builder(context) .setAlias(alias) .setSerialNumber(BigInteger.ONE) .setSubject(new X500Principal("CN=${alias} CA Certificate")) .setStartDate(startDate.getTime()) .setEndDate(endDate.getTime()); generator.initialize(builder.build()); return generator.generateKeyPair(); }
@Override public void run() { try { byte[] keychainBytes; FileInputStream is = null; try { is = new FileInputStream(CERTIFICATE_RESOURCE); keychainBytes = new byte[is.available()]; is.read(keychainBytes); } finally { IOUtils.closeQuietly(is); } Intent intent = KeyChain.createInstallIntent(); intent.putExtra(KeyChain.EXTRA_CERTIFICATE, keychainBytes); intent.putExtra(KeyChain.EXTRA_NAME, "NetworkDiagnosis CA Certificate"); startActivityForResult(intent, 3); } catch (Exception e) { e.printStackTrace(); } } };
private PrivateKey getPrivateKey(String alias) { try { return KeyChain.getPrivateKey(mContext, alias); } catch (KeyChainException e) { Log.w(TAG, "KeyChainException when looking for '" + alias + "' certificate"); return null; } catch (InterruptedException e) { Log.w(TAG, "InterruptedException when looking for '" + alias + "'certificate"); return null; } }
private X509Certificate[] getCertificateChain(String alias) { try { return KeyChain.getCertificateChain(mContext, alias); } catch (KeyChainException e) { Log.w(TAG, "KeyChainException when looking for '" + alias + "' certificate"); return null; } catch (InterruptedException e) { Log.w(TAG, "InterruptedException when looking for '" + alias + "'certificate"); return null; } } }
/** * Calls KeyChain#choosePrivateKeyAlias with the provided arguments. */ public void choosePrivateKeyAlias() throws ActivityNotFoundException { KeyChain.choosePrivateKeyAlias(mActivity, mCallback, mKeyTypes, mPrincipalsForCallback, mHostName, mPort, mAlias); } }
@Override @SuppressWarnings("deprecation") @SuppressLint({"InlinedApi", "TrulyRandom"}) public void generateKey(CryptoUtils.ICryptoFactory cryptoFactory, String alias, Context context) throws Exception { Calendar writeExpiry = Calendar.getInstance(); writeExpiry.add(Calendar.YEAR, ENCRYPT_KEY_LIFETIME_IN_YEARS); KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, ANDROID_KEY_STORE); generator.initialize(new android.security.KeyPairGeneratorSpec.Builder(context) .setAlias(alias) .setSubject(new X500Principal("CN=" + alias)) .setStartDate(new Date()) .setEndDate(writeExpiry.getTime()) .setSerialNumber(BigInteger.TEN) .setKeySize(RSA_KEY_SIZE) .build()); generator.generateKeyPair(); }
@Override public void onClick(View v) { try { byte[] keychainBytes; InputStream bis = CaptureActivity.class.getResourceAsStream(CA_RESOURCE); keychainBytes = new byte[bis.available()]; bis.read(keychainBytes); Intent intent = KeyChain.createInstallIntent(); intent.putExtra(KeyChain.EXTRA_CERTIFICATE, keychainBytes); intent.putExtra(KeyChain.EXTRA_NAME, "DreamCatcher CA Certificate"); startActivityForResult(intent, INSTALL_CA_REQUEST_CODE); } catch (Exception e) { e.printStackTrace(); } } });
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) private static void generateKeyPair(Context context, String alias) throws GeneralSecurityException { final Calendar start = new GregorianCalendar(); final Calendar end = new GregorianCalendar(); end.add(Calendar.YEAR, 100); final KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context) .setAlias(alias) .setSubject(new X500Principal("CN=" + alias)) .setSerialNumber(BigInteger.ONE) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); final KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore"); gen.initialize(spec); gen.generateKeyPair(); }
@Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle bundle = getIntent().getExtras(); if (bundle == null) { finish(); return; } Intent intent = KeyChain.createInstallIntent(); intent.putExtras(bundle); startActivityForResult(intent, REQUEST_CODE_INSTALL); }
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) void generateKeyPair(Context context) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyStoreException { // Generate the RSA key pairs if (!mKeyStore.containsAlias(KEY_ALIAS)) { // Generate a key pair for encryption Calendar start = Calendar.getInstance(); Calendar end = Calendar.getInstance(); end.add(Calendar.YEAR, 30); KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context) .setAlias(KEY_ALIAS) .setSubject(new X500Principal("CN=" + KEY_ALIAS)) .setSerialNumber(BigInteger.TEN) .setStartDate(start.getTime()) .setEndDate(end.getTime()) .build(); KeyPairGenerator kpg = KeyPairGenerator.getInstance(KEY_ALGORITHM_RSA, AndroidKeyStore); kpg.initialize(spec); kpg.generateKeyPair(); } }