Code example for KeyStore

Methods: containsAlias, deleteEntry, setCertificateEntry, store

0
 
  private void store(KeyStore keyStore) {
    try { 
      FileOutputStream fos =
          mContext.openFileOutput(KEYSTORE_FILENAME, Context.MODE_PRIVATE);
      keyStore.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);
    } 
  } 
 
  /** 
   * Stores current state of key store. 
   */ 
  public synchronized void store() { 
    store(mKeyStore);
  } 
 
  /** 
   * 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 synchronized KeyManager[] getKeyManagers()
      throws GeneralSecurityException { 
    if (mKeyStore == null) {
      throw new NullPointerException("null mKeyStore");
    } 
    KeyManagerFactory factory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    factory.init(mKeyStore, "".toCharArray());
    return factory.getKeyManagers();
  } 
 
  /** 
   * @return trust managers loaded for this service. 
   */ 
  public synchronized TrustManager[] getTrustManagers()
      throws GeneralSecurityException { 
    // Build a new set of TrustManagers based on the KeyStore. 
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(mKeyStore);
    return tmf.getTrustManagers();
  } 
 
  public synchronized void storeCertificate(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(); 
    } catch (KeyStoreException e) {
      Log.e(LOG_TAG, "Storing cert failed", e);
    } 
  }