Code example for KeyStore

Methods: containsAlias, deleteEntry, setCertificateEntry, store

0
    } 
 
    private synchronized void store() { 
        try { 
            FileOutputStream fos = mContext.openFileOutput(KEYSTORE_FILENAME, Context.MODE_PRIVATE);
            mKeyStore.store(fos, KEYSTORE_PASSWORD);
            fos.close();
        } catch (IOException e) {
            throw new IllegalStateException("Unable to store keyStore", e);
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException("Unable to store keyStore", e);
        } 
    } 
 
    /** 
     * Returns the name that should be used in a new certificate. 
     * <p> 
     * The format is: "CN=anymote/PRODUCT/DEVICE/MODEL/unique identifier" 
     */ 
    private static final String getCertificateName(String id) {
        return "CN=anymote/" + Build.PRODUCT + "/" + Build.DEVICE + "/" + Build.MODEL + "/" + id;
    } 
 
    /** 
     * @return key managers loaded for this service. 
     */ 
    public KeyManager[] getKeyManagers() {
        return mKeyManagers;
    } 
 
    /** 
     * @throws GeneralSecurityException 
     */ 
    private synchronized void collectKeyManagers() throws GeneralSecurityException { 
        if (mKeyStore == null) {
            throw new NullPointerException("null mKeyStore");
        } 
        KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory
                .getDefaultAlgorithm());
        factory.init(mKeyStore, "".toCharArray());
        mKeyManagers = factory.getKeyManagers();
    } 
 
    /** 
     * @return trust managers loaded for this service. 
     */ 
    public TrustManager[] getTrustManagers() {
        return mTrustManagers;
    } 
 
    /** 
     * @throws GeneralSecurityException 
     */ 
    private synchronized void collectTrustManagers() throws GeneralSecurityException { 
        // Build a new set of TrustManagers based on the KeyStore. 
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory
                .getDefaultAlgorithm());
        tmf.init(mKeyStore);
        mTrustManagers = tmf.getTrustManagers();
    } 
 
    /** 
     * Stores the remote device certificate in keystore. 
     * @param peerCert 
     */ 
    synchronized void storeCertificate(final Certificate peerCert) {
        try { 
            String alias = String.format(KeyStoreManager.REMOTE_IDENTITY_ALIAS_PATTERN,
                    peerCert.hashCode());
            if (mKeyStore.containsAlias(alias)) {
                Log.w(LOG_TAG, "Deleting existing entry for " + alias);
                mKeyStore.deleteEntry(alias);
            } 
            Log.i(LOG_TAG, "Adding cert to keystore: " + alias);
            mKeyStore.setCertificateEntry(alias, peerCert);
            store(); 
 
            try { 
                collectTrustManagers(); 
            } catch (GeneralSecurityException e) {