android.security.KeyChain Java Examples

The following examples show how to use android.security.KeyChain. 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: ClientCertificatePreference.java    From PresencePublisher with MIT License 7 votes vote down vote up
public ClientCertificatePreference(Context context, Fragment fragment) {
    super(context);
    setKey(CLIENT_CERTIFICATE);
    setTitle(R.string.client_certificate_title);
    setSummaryProvider(new ExplanationSummaryProvider<>(R.string.client_certificate_summary, STRING));
    setIconSpaceReserved(false);
    setOnPreferenceClickListener(prefs -> {
        KeyChain.choosePrivateKeyAlias(
                fragment.requireActivity(),
                alias -> fragment.requireActivity().runOnUiThread(() -> setValue(alias)),
                null,
                null,
                null,
                -1,
                getPersistedString(null)
        );
        return true;
    });
}
 
Example #2
Source File: AndroidSslSocketFactoryFactory.java    From PresencePublisher with MIT License 6 votes vote down vote up
private KeyManager[] getClientKeyManagers(String clientCertAlias) {
    try {
        PrivateKey privateKey = KeyChain.getPrivateKey(context, clientCertAlias);
        X509Certificate[] certificateChain = KeyChain.getCertificateChain(context, clientCertAlias);
        KeyStore customKeyStore = KeyStore.getInstance("PKCS12");
        char[] pwdArray = Double.toString(Math.random()).toCharArray();
        customKeyStore.load(null, pwdArray);
        customKeyStore.setKeyEntry(clientCertAlias, privateKey, null, certificateChain);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(customKeyStore, pwdArray);
        return keyManagerFactory.getKeyManagers();
    } catch (Exception e) {
        HyperLog.w(TAG, "Unable to initialize client key store", e);
        return null;
    }
}
 
Example #3
Source File: CertificateInstallActivity.java    From NetBare with MIT License 6 votes vote down vote up
@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);
    try {
        startActivityForResult(intent, REQUEST_CODE_INSTALL);
    } catch (ActivityNotFoundException e) {
        NetBareLog.e("Unable to start certificate installer.");
        finish();
    }
}
 
Example #4
Source File: AndroidNetworkLibrary.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Stores the key pair through the CertInstaller activity.
 * @param context: current application context.
 * @param public_key: The public key bytes as DER-encoded SubjectPublicKeyInfo (X.509)
 * @param private_key: The private key as DER-encoded PrivateKeyInfo (PKCS#8).
 * @return: true on success, false on failure.
 *
 * Note that failure means that the function could not launch the CertInstaller
 * activity. Whether the keys are valid or properly installed will be indicated
 * by the CertInstaller UI itself.
 */
@CalledByNative
static public boolean storeKeyPair(Context context, byte[] public_key, byte[] private_key) {
    // TODO(digit): Use KeyChain official extra values to pass the public and private
    // keys when they're available. The "KEY" and "PKEY" hard-coded constants were taken
    // from the platform sources, since there are no official KeyChain.EXTRA_XXX definitions
    // for them. b/5859651
    try {
        Intent intent = KeyChain.createInstallIntent();
        intent.putExtra("PKEY", private_key);
        intent.putExtra("KEY", public_key);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        Log.w(TAG, "could not store key pair: " + e);
    }
    return false;
}
 
Example #5
Source File: DConnectService.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * ルート証明書を「信頼できる証明書」としてインストールする.
 *
 * <p>
 * インストール前にユーザーに対して、認可ダイアログが表示される.
 * 認可されない場合は、インストールされない.
 * </p>
 */
public void installRootCertificate() {
    String ipAddress = DConnectUtil.getIPAddress(getApplicationContext());
    mManager.requestKeyStore(ipAddress, new KeyStoreCallback() {
        @Override
        public void onSuccess(final KeyStore keyStore, final Certificate cert, final Certificate rootCert) {
            try {
                Intent installIntent = KeyChain.createInstallIntent();
                installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                installIntent.putExtra(KeyChain.EXTRA_NAME, "Device Connect Root CA");
                installIntent.putExtra(KeyChain.EXTRA_CERTIFICATE, rootCert.getEncoded());
                startActivity(installIntent);
            } catch (Exception e) {
                mLogger.log(Level.SEVERE, "Failed to encode server certificate.", e);
            }
        }

        @Override
        public void onError(final KeyStoreError error) {
            mLogger.severe("Failed to encode server certificate: " + error.name());
        }
    });
}
 
Example #6
Source File: AndroidNetworkLibrary.java    From android-chromium with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Stores the key pair through the CertInstaller activity.
 * @param context: current application context.
 * @param public_key: The public key bytes as DER-encoded SubjectPublicKeyInfo (X.509)
 * @param private_key: The private key as DER-encoded PrivateKeyInfo (PKCS#8).
 * @return: true on success, false on failure.
 *
 * Note that failure means that the function could not launch the CertInstaller
 * activity. Whether the keys are valid or properly installed will be indicated
 * by the CertInstaller UI itself.
 */
@CalledByNative
static public boolean storeKeyPair(Context context, byte[] public_key, byte[] private_key) {
    // TODO(digit): Use KeyChain official extra values to pass the public and private
    // keys when they're available. The "KEY" and "PKEY" hard-coded constants were taken
    // from the platform sources, since there are no official KeyChain.EXTRA_XXX definitions
    // for them. b/5859651
    try {
        Intent intent = KeyChain.createInstallIntent();
        intent.putExtra("PKEY", private_key);
        intent.putExtra("KEY", public_key);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        Log.w(TAG, "could not store key pair: " + e);
    }
    return false;
}
 
Example #7
Source File: AndroidNetworkLibrary.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
 * Stores the key pair through the CertInstaller activity.
 * @param publicKey The public key bytes as DER-encoded SubjectPublicKeyInfo (X.509)
 * @param privateKey The private key as DER-encoded PrivateKeyInfo (PKCS#8).
 * @return: true on success, false on failure.
 *
 * Note that failure means that the function could not launch the CertInstaller
 * activity. Whether the keys are valid or properly installed will be indicated
 * by the CertInstaller UI itself.
 */
@CalledByNative
public static boolean storeKeyPair(byte[] publicKey, byte[] privateKey) {
    // TODO(digit): Use KeyChain official extra values to pass the public and private
    // keys when they're available. The "KEY" and "PKEY" hard-coded constants were taken
    // from the platform sources, since there are no official KeyChain.EXTRA_XXX definitions
    // for them. b/5859651
    try {
        Intent intent = KeyChain.createInstallIntent();
        intent.putExtra("PKEY", privateKey);
        intent.putExtra("KEY", publicKey);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ContextUtils.getApplicationContext().startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        Log.w(TAG, "could not store key pair: " + e);
    }
    return false;
}
 
Example #8
Source File: X509Util.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Ensures that the trust managers and certificate factory are initialized.
 */
private static void ensureInitialized() throws CertificateException,
        KeyStoreException, NoSuchAlgorithmException {
    synchronized(sLock) {
        if (sCertificateFactory == null) {
            sCertificateFactory = CertificateFactory.getInstance("X.509");
        }
        if (sDefaultTrustManager == null) {
            sDefaultTrustManager = X509Util.createTrustManager(null);
        }
        if (sTestKeyStore == null) {
            sTestKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            try {
                sTestKeyStore.load(null);
            } catch(IOException e) {}  // No IO operation is attempted.
        }
        if (sTestTrustManager == null) {
            sTestTrustManager = X509Util.createTrustManager(sTestKeyStore);
        }
        if (!sDisableCertificateObservationForTest &&
                sTrustStorageListener == null) {
            sTrustStorageListener = new TrustStorageListener();
            nativeGetApplicationContext().registerReceiver(sTrustStorageListener,
                    new IntentFilter(KeyChain.ACTION_STORAGE_CHANGED));
        }
    }
}
 
Example #9
Source File: AndroidNetworkLibrary.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
  * Adds a cryptographic file (User certificate, a CA certificate or
  * PKCS#12 keychain) through the system's CertInstaller activity.
  *
  * @param context: current application context.
  * @param cert_type: cryptographic file type. E.g. CertificateMimeType.X509_USER_CERT
  * @param data: certificate/keychain data bytes.
  * @return true on success, false on failure.
  *
  * Note that failure only indicates that the function couldn't launch the
  * CertInstaller activity, not that the certificate/keychain was properly
  * installed to the keystore.
  */
@CalledByNative
static public boolean storeCertificate(Context context, int cert_type, byte[] data) {
    try {
        Intent intent = KeyChain.createInstallIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        switch (cert_type) {
          case CertificateMimeType.X509_USER_CERT:
          case CertificateMimeType.X509_CA_CERT:
            intent.putExtra(KeyChain.EXTRA_CERTIFICATE, data);
            break;

          case CertificateMimeType.PKCS12_ARCHIVE:
            intent.putExtra(KeyChain.EXTRA_PKCS12, data);
            break;

          default:
            Log.w(TAG, "invalid certificate type: " + cert_type);
            return false;
        }
        context.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        Log.w(TAG, "could not store crypto file: " + e);
    }
    return false;
}
 
Example #10
Source File: SSLClientCertificateRequest.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Create a new asynchronous request to select a client certificate.
 *
 * @param nativePtr The native object responsible for this request.
 * @param keyTypes The list of supported key exchange types.
 * @param encodedPrincipals The list of CA DistinguishedNames.
 * @param host_name The server host name is available (empty otherwise).
 * @param port The server port if available (0 otherwise).
 * @return true on success.
 * Note that nativeOnSystemRequestComplete will be called iff this method returns true.
 */
@CalledByNative
static private boolean selectClientCertificate(
        int nativePtr, String[] keyTypes, byte[][] encodedPrincipals, String hostName,
        int port) {
    ThreadUtils.assertOnUiThread();

    Activity activity = ActivityStatus.getActivity();
    if (activity == null) {
        Log.w(TAG, "No active Chromium main activity!?");
        return false;
    }

    // Build the list of principals from encoded versions.
    Principal[] principals = null;
    if (encodedPrincipals.length > 0) {
        principals = new X500Principal[encodedPrincipals.length];
        try {
            for (int n = 0; n < encodedPrincipals.length; n++) {
                principals[n] = new X500Principal(encodedPrincipals[n]);
            }
        } catch (Exception e) {
            // Bail on error.
            Log.w(TAG, "Exception while decoding issuers list: " + e);
            return false;
        }
    }

    // All good, create new request, add it to our list and launch the certificate selection
    // activity.
    SSLClientCertificateRequest request = new SSLClientCertificateRequest(nativePtr);

    KeyChain.choosePrivateKeyAlias(
            activity, request, keyTypes, principals, hostName, port, null);
    return true;
}
 
Example #11
Source File: X509Util.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Ensures that the trust managers and certificate factory are initialized.
 */
private static void ensureInitialized() throws CertificateException,
        KeyStoreException, NoSuchAlgorithmException {
    synchronized(sLock) {
        if (sCertificateFactory == null) {
            sCertificateFactory = CertificateFactory.getInstance("X.509");
        }
        if (sDefaultTrustManager == null) {
            sDefaultTrustManager = X509Util.createTrustManager(null);
        }
        if (sTestKeyStore == null) {
            sTestKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            try {
                sTestKeyStore.load(null);
            } catch(IOException e) {}  // No IO operation is attempted.
        }
        if (sTestTrustManager == null) {
            sTestTrustManager = X509Util.createTrustManager(sTestKeyStore);
        }
        if (!sDisableCertificateObservationForTest &&
                sTrustStorageListener == null) {
            sTrustStorageListener = new TrustStorageListener();
            nativeGetApplicationContext().registerReceiver(sTrustStorageListener,
                    new IntentFilter(KeyChain.ACTION_STORAGE_CHANGED));
        }
    }
}
 
Example #12
Source File: AndroidNetworkLibrary.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
  * Adds a cryptographic file (User certificate, a CA certificate or
  * PKCS#12 keychain) through the system's CertInstaller activity.
  *
  * @param context: current application context.
  * @param cert_type: cryptographic file type. E.g. CertificateMimeType.X509_USER_CERT
  * @param data: certificate/keychain data bytes.
  * @return true on success, false on failure.
  *
  * Note that failure only indicates that the function couldn't launch the
  * CertInstaller activity, not that the certificate/keychain was properly
  * installed to the keystore.
  */
@CalledByNative
static public boolean storeCertificate(Context context, int cert_type, byte[] data) {
    try {
        Intent intent = KeyChain.createInstallIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        switch (cert_type) {
          case CertificateMimeType.X509_USER_CERT:
          case CertificateMimeType.X509_CA_CERT:
            intent.putExtra(KeyChain.EXTRA_CERTIFICATE, data);
            break;

          case CertificateMimeType.PKCS12_ARCHIVE:
            intent.putExtra(KeyChain.EXTRA_PKCS12, data);
            break;

          default:
            Log.w(TAG, "invalid certificate type: " + cert_type);
            return false;
        }
        context.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException e) {
        Log.w(TAG, "could not store crypto file: " + e);
    }
    return false;
}
 
Example #13
Source File: SSLClientCertificateRequest.java    From android-chromium with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Create a new asynchronous request to select a client certificate.
 *
 * @param nativePtr The native object responsible for this request.
 * @param keyTypes The list of supported key exchange types.
 * @param encodedPrincipals The list of CA DistinguishedNames.
 * @param host_name The server host name is available (empty otherwise).
 * @param port The server port if available (0 otherwise).
 * @return true on success.
 * Note that nativeOnSystemRequestComplete will be called iff this method returns true.
 */
@CalledByNative
static private boolean selectClientCertificate(
        int nativePtr, String[] keyTypes, byte[][] encodedPrincipals, String hostName,
        int port) {
    ThreadUtils.assertOnUiThread();

    Activity activity = ActivityStatus.getActivity();
    if (activity == null) {
        Log.w(TAG, "No active Chromium main activity!?");
        return false;
    }

    // Build the list of principals from encoded versions.
    Principal[] principals = null;
    if (encodedPrincipals.length > 0) {
        principals = new X500Principal[encodedPrincipals.length];
        try {
            for (int n = 0; n < encodedPrincipals.length; n++) {
                principals[n] = new X500Principal(encodedPrincipals[n]);
            }
        } catch (Exception e) {
            // Bail on error.
            Log.w(TAG, "Exception while decoding issuers list: " + e);
            return false;
        }
    }

    // All good, create new request, add it to our list and launch the certificate selection
    // activity.
    SSLClientCertificateRequest request = new SSLClientCertificateRequest(nativePtr);

    KeyChain.choosePrivateKeyAlias(
            activity, request, keyTypes, principals, hostName, port, null);
    return true;
}
 
Example #14
Source File: VpnProfile.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
private X509Certificate[] getKeyStoreCertificates(Context context) throws KeyChainException, InterruptedException {
    PrivateKey privateKey = KeyChain.getPrivateKey(context, mAlias);
    mPrivateKey = privateKey;


    X509Certificate[] caChain = KeyChain.getCertificateChain(context, mAlias);
    return caChain;
}
 
Example #15
Source File: ManageAccountActivity.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
private void addAccountFromKey() {
    try {
        KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.device_does_not_support_certificates, Toast.LENGTH_LONG).show();
    }
}
 
Example #16
Source File: WelcomeActivity.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
private void addAccountFromKey() {
    try {
        KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.device_does_not_support_certificates, Toast.LENGTH_LONG).show();
    }
}
 
Example #17
Source File: XmppConnection.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@Override
public PrivateKey getPrivateKey(String alias) {
    try {
        return KeyChain.getPrivateKey(mXmppConnectionService, alias);
    } catch (Exception e) {
        return null;
    }
}
 
Example #18
Source File: XmppConnection.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(String alias) {
    Log.d(Config.LOGTAG, "getting certificate chain");
    try {
        return KeyChain.getCertificateChain(mXmppConnectionService, alias);
    } catch (Exception e) {
        Log.d(Config.LOGTAG, e.getMessage());
        return new X509Certificate[0];
    }
}
 
Example #19
Source File: XmppConnection.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
@Override
public PrivateKey getPrivateKey(String alias) {
    try {
        return KeyChain.getPrivateKey(mXmppConnectionService, alias);
    } catch (Exception e) {
        return null;
    }
}
 
Example #20
Source File: XmppConnection.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
@Override
public X509Certificate[] getCertificateChain(String alias) {
    Log.d(Config.LOGTAG, "getting certificate chain");
    try {
        return KeyChain.getCertificateChain(mXmppConnectionService, alias);
    } catch (Exception e) {
        Log.d(Config.LOGTAG, e.getMessage());
        return new X509Certificate[0];
    }
}
 
Example #21
Source File: ManageAccountActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private void addAccountFromKey() {
    try {
        KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
    } catch (ActivityNotFoundException e) {
        ToastCompat.makeText(this, R.string.device_does_not_support_certificates, Toast.LENGTH_LONG).show();
    }
}
 
Example #22
Source File: WelcomeActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private void addAccountFromKey() {
    try {
        KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(this, R.string.device_does_not_support_certificates, Toast.LENGTH_LONG).show();
    }
}
 
Example #23
Source File: MainActivity.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public void onProxyStarted() {
    if (!mBinder.isProxyStarted()) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Snackbar.make(getWindow().getDecorView(),"端口被占用或其他异常,启动失败!",Snackbar.LENGTH_SHORT).show();
            }
        });
        return;
    }
    if (!SPUtil.getBoolean(this,SPUtil.KEY_IS_INSTALL_CER,false)) {
        byte[] cerBytes = mBinder.getCerBytes();
        if (cerBytes != null) {
            Intent intent = KeyChain.createInstallIntent();
            intent.putExtra(KeyChain.EXTRA_CERTIFICATE, cerBytes);
            intent.putExtra(KeyChain.EXTRA_NAME, "CapturePacket CA Certificate");
            startActivityForResult(intent, REQUEST_INSTALL_CER);
        }
    }
    boolean result = ProxyUtil.setProxy(this, CaptureService.PROXY_PORT);
    final String text = result ? "Set proxy host success !!!" : "Set proxy host failure ~~~";

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Snackbar.make(getWindow().getDecorView(),text,Snackbar.LENGTH_SHORT).show();
        }
    });

    if (result) {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(CaptureListFragment.TAG);
        if (fragment instanceof CaptureListFragment) {
            ((CaptureListFragment) fragment).onProxyStarted(mBinder);
        }
    }
}
 
Example #24
Source File: EditAccountActivity.java    From Conversations with GNU General Public License v3.0 4 votes vote down vote up
private void renewCertificate() {
    KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
}
 
Example #25
Source File: SSLClientCertificateRequest.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * Calls KeyChain#choosePrivateKeyAlias with the provided arguments.
 */
public void choosePrivateKeyAlias() throws ActivityNotFoundException {
    KeyChain.choosePrivateKeyAlias(mActivity, mCallback, mKeyTypes, mPrincipalsForCallback,
            mHostName, mPort, mAlias);
}
 
Example #26
Source File: EditAccountActivity.java    From Pix-Art-Messenger with GNU General Public License v3.0 4 votes vote down vote up
private void renewCertificate() {
    KeyChain.choosePrivateKeyAlias(this, this, null, null, null, -1, null);
}
 
Example #27
Source File: SSLClientCertificateRequest.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * Calls KeyChain#choosePrivateKeyAlias with the provided arguments.
 */
public void choosePrivateKeyAlias() throws ActivityNotFoundException {
    KeyChain.choosePrivateKeyAlias(mActivity, mCallback, mKeyTypes, mPrincipalsForCallback,
            mHostName, mPort, mAlias);
}
 
Example #28
Source File: SSLClientCertificateRequest.java    From delion with Apache License 2.0 4 votes vote down vote up
/**
 * Calls KeyChain#choosePrivateKeyAlias with the provided arguments.
 */
public void choosePrivateKeyAlias() throws ActivityNotFoundException {
    KeyChain.choosePrivateKeyAlias(mActivity, mCallback, mKeyTypes, mPrincipalsForCallback,
            mHostName, mPort, mAlias);
}