/**
   * Takes a GFIPM entity ID or a Java key store entry alias name and deletes its entry from the
   * Java key store. Writes out an error messages on an exception.
   *
   * @param entityid The GFIPM entity or key store alias to be deleted.
   * @return true on success, false otherwise.
   */
  public boolean deleteEntry(String entityid) {

    if (entityid == null) {
      System.err.println("ERROR: GFIPMKeystore.deleteEntry: No entityid or alias name. Aborted.");
      System.err.flush();
      return false;
    }
    String alias = makeEntityAliasName(entityid);

    try {
      if (keyStore.containsAlias(alias)) {
        if (verboseOut) {
          System.out.println("Key store: delete entry " + alias);
          System.out.flush();
        }
        keyStore.deleteEntry(alias);
        modifiedFlag = true;

      } else {
        if (verboseOut) {
          System.out.println("Key store: Entry to be delete not found with alias " + alias);
        }
      }

    } catch (KeyStoreException e) {
      System.err.println("ERROR: GFIPMKeystore.deleteEntry failed: ");
      System.err.println(e.toString());
      System.err.flush();
      return false;
    }

    return true;
  } // end deleteEntry
Exemple #2
0
 /**
  * Remove the key store entry at the given alias. If the alias does not exist, log that it does
  * not exist.
  *
  * @param alias the name of the entry in the keystore
  * @return true if entry is not in the keystore false otherwise
  */
 public boolean deleteEntry(String alias) {
   try {
     keyStore.deleteEntry(alias);
   } catch (KeyStoreException e) {
     LOGGER.info("Attempted to remove key named {} from keyStore. No such such key", alias);
   }
   return isKey(alias);
 }
 @DELETE
 @Path("{alias}")
 public String deleteKey(@PathParam("alias") String alias, @QueryParam("callback") String calback)
     throws Exception {
   keystore.deleteEntry(alias);
   save();
   return calback + "();";
 }
 public void clearCertificates() throws OpenAS2Exception {
   final KeyStore aKeyStore = getKeyStore();
   try {
     // Make a copy to be sure
     for (final String sAlias : CollectionHelper.newList(aKeyStore.aliases()))
       aKeyStore.deleteEntry(sAlias);
     save(getFilename(), getPassword());
   } catch (final GeneralSecurityException ex) {
     throw WrappedOpenAS2Exception.wrap(ex);
   }
 }
 private static void uninstallRootCAWindowsKeyStore() {
   try {
     final KeyStore ks = KeyStore.getInstance("Windows-ROOT"); // $NON-NLS-1$
     ks.load(null, null);
     ks.deleteEntry(ROOT_CA_ALIAS);
   } catch (final Exception e) {
     LOGGER.warning(
         "No se pudo desinstalar el certificado SSL raiz del almacen de Windows: "
             + e); //$NON-NLS-1$
   }
 }
 /**
  * Remove a key with the specified alias from the keystore.
  *
  * @param keyStore to remove from
  * @param alias of key to remove
  * @return true if the key alias was removed
  * @throws CryptoTokenOfflineException if the keystore was null
  * @throws KeyStoreException for keystore related errors
  * @throws SignServerException if the keystore did not contain a key with the specified alias
  */
 public static boolean removeKey(final KeyStore keyStore, final String alias)
     throws CryptoTokenOfflineException, KeyStoreException, SignServerException {
   if (keyStore == null) {
     throw new CryptoTokenOfflineException("Token offline");
   }
   if (!keyStore.containsAlias(alias)) {
     throw new SignServerException("No such alias in token: " + alias);
   }
   keyStore.deleteEntry(alias);
   return !keyStore.containsAlias(alias);
 }
Exemple #7
0
  /**
   * Erases the specified id from the keystore.
   *
   * @param id The ID of the key or certificate to be deleted.
   * @throws KeyStoreException When the wrong keystore password has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public void erase(ID id) throws KeyStoreException, IOException {
    String alias = id.toString();

    synchronized (keystore_manager) {
      KeyStore store = keystore_manager.loadKeyStore(keystore_password);

      store.deleteEntry(alias);

      keystore_manager.saveKeyStore(store, keystore_password);
    }
  }
  public void removeCertificate(@Nullable final String sAlias) throws OpenAS2Exception {
    final KeyStore aKeyStore = getKeyStore();
    try {
      if (aKeyStore.getCertificate(sAlias) == null)
        throw new CertificateNotFoundException(null, sAlias);

      aKeyStore.deleteEntry(sAlias);
      save(getFilename(), getPassword());
    } catch (final GeneralSecurityException ex) {
      throw WrappedOpenAS2Exception.wrap(ex);
    }
  }
 private void clearKeyStore() {
   try {
     for (Enumeration<String> e = mKeyStore.aliases(); e.hasMoreElements(); ) {
       final String alias = e.nextElement();
       LogUtils.v("Deleting alias: " + alias);
       mKeyStore.deleteEntry(alias);
     }
   } catch (KeyStoreException e) {
     LogUtils.e("Clearing certificates failed", e);
   }
   store();
 }
  /** java.security.KeyStore#deleteEntry(String) */
  public void test_deleteEntry() throws Exception {
    try {
      KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
      keyTest.load(null, null);
      keyTest.deleteEntry(null);
      fail();
    } catch (NullPointerException expected) {
    }

    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, "password".toCharArray());

    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(pssWord);
    Certificate[] chain = {
      new MyCertificate("DSA", testEncoding), new MyCertificate("DSA", testEncoding)
    };
    KeyStore.PrivateKeyEntry pkEntry = new KeyStore.PrivateKeyEntry(getPrivateKey(), chain);

    keyTest.setEntry("symKey", pkEntry, pp);

    keyTest.deleteEntry("symKey");
  }
Exemple #11
0
  /**
   * Adds a trusted certificate with the specified id to the key store. The certificate replaces any
   * existing certificate or private key stored at this ID.
   *
   * @param id The ID under which the certificate will be stored.
   * @param cert Certificate for the specified ID.
   * @throws KeyStoreException When the wrong keystore has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public void setTrustedCertificate(ID id, X509Certificate cert)
      throws KeyStoreException, IOException {
    String alias = id.toString();

    synchronized (keystore_manager) {
      KeyStore store = keystore_manager.loadKeyStore(keystore_password);

      store.deleteEntry(alias);

      store.setCertificateEntry(alias, cert);

      keystore_manager.saveKeyStore(store, keystore_password);
    }
  }
 public synchronized void storeCertificate(Certificate peerCert) {
   try {
     String alias =
         String.format(KeyStoreManager.REMOTE_IDENTITY_ALIAS_PATTERN, peerCert.hashCode());
     if (mKeyStore.containsAlias(alias)) {
       LogUtils.w("Deleting existing entry for " + alias);
       mKeyStore.deleteEntry(alias);
     }
     LogUtils.i("Adding cert to keystore: " + alias);
     mKeyStore.setCertificateEntry(alias, peerCert);
     store();
   } catch (KeyStoreException e) {
     LogUtils.e("Storing cert failed", e);
   }
 }
Exemple #13
0
  /**
   * Adds a private key to the PSE using the specified ID. The key replaces any existing certificate
   * or private key stored at this ID. The key is stored using the provided key passphrase.
   *
   * @param id The ID under which the certificate chain and private key will be stored.
   * @param certchain The certificate chain matching the private key.
   * @param key The private key to be stored in the kestore.
   * @param key_password The passphrase associated with the private key or {@code null} if the key
   *     has no passphrase.
   * @throws KeyStoreException When the wrong keystore key has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public void setKey(ID id, Certificate[] certchain, PrivateKey key, char[] key_password)
      throws KeyStoreException, IOException {

    String alias = id.toString();

    synchronized (keystore_manager) {
      KeyStore store = keystore_manager.loadKeyStore(keystore_password);

      // Remove any existing entry.
      if (store.isKeyEntry(alias)) store.deleteEntry(alias);

      store.setKeyEntry(alias, key, key_password, certchain);

      keystore_manager.saveKeyStore(store, keystore_password);
    }
  }
  /**
   * Deletes all Java key store certificates that are associated with the GFIPM trust fabric. These
   * are identified by the alias name prefix "GFIPMcert" or other configured aliasPrefix. Writes
   * error messages on exceptions.
   *
   * @return true if successful; false otherwise
   */
  public boolean deleteAllGFIPMEntries() {

    if ((aliasPrefix == null) || (aliasPrefix.trim().length() == 0)) {
      System.err.println(
          "ERROR: GFIPMKeystore.deleteAllGFIPMEntries: Attempting to delete all key store entries. Aborted.");
      System.err.flush();
      return false;
    }

    try {
      String alias = null;
      int count = 0;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        if (alias.startsWith(aliasPrefix)) {
          if (verboseOut) {
            System.out.println("Key store: delete entry " + alias);
            System.out.flush();
          }
          keyStore.deleteEntry(alias);
          count++;
          modifiedFlag = true;
        }
      }
      if (verboseOut) {
        System.out.println("Key store: deleteall: # entries deleted: " + count);
      }
    } catch (KeyStoreException e) {
      System.err.println("ERROR: GFIPMKeystore.deleteAllGFIPMEntries failed: ");
      System.err.println(e.toString());
      System.err.flush();
      return false;
    }

    return true;
  } // end deleteAllGFIPMEntitries
    @Override
    protected Void doInBackground(String... params) {
      final String alias = params[0];
      try {

        /*
         * Deletes a previously generated or stored entry in the
         * KeyStore.
         */
        KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);
        ks.deleteEntry(alias);

      } catch (NoSuchAlgorithmException e) {
        Log.w(TAG, "Could not generate key", e);
      } catch (KeyStoreException e) {
        Log.w(TAG, "Could not generate key", e);
      } catch (CertificateException e) {
        Log.w(TAG, "Could not generate key", e);
      } catch (IOException e) {
        Log.w(TAG, "Could not generate key", e);
      }
      return null;
    }
  private static void cleanWindowsMyKeyStore() throws GeneralSecurityException, IOException {

    final KeyStore ks = KeyStore.getInstance("Windows-MY"); // $NON-NLS-1$
    ks.load(null, null);
    ks.deleteEntry(CERT_ALIAS);
  }
 /**
  * Removes the given certificate from MTMs key store.
  *
  * <p><b>WARNING</b>: this does not immediately invalidate the certificate. It is well possible
  * that (a) data is transmitted over still existing connections or (b) new connections are created
  * using TLS renegotiation, without a new cert check.
  *
  * @param alias the certificate's alias as returned by {@link #getCertificates()}.
  * @throws KeyStoreException if the certificate could not be deleted.
  */
 public void deleteCertificate(String alias) throws KeyStoreException {
   appKeyStore.deleteEntry(alias);
   keyStoreUpdated();
 }
  /** Do action. */
  @Override
  protected void doAction() {
    try {
      KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();

      KeyStoreState currentState = history.getCurrentState();
      KeyStoreState newState = currentState.createBasisForNextState(this);

      KeyStore keyStore = newState.getKeyStore();
      String alias = kseFrame.getSelectedEntryAlias();

      DGetAlias dGetAlias =
          new DGetAlias(
              frame, res.getString("RenameTrustedCertificateAction.NewEntryAlias.Title"), alias);
      dGetAlias.setLocationRelativeTo(frame);
      dGetAlias.setVisible(true);
      String newAlias = dGetAlias.getAlias();

      if (newAlias == null) {
        return;
      }

      if (newAlias.equalsIgnoreCase(alias)) {
        JOptionPane.showMessageDialog(
            frame,
            MessageFormat.format(
                res.getString("RenameTrustedCertificateAction.RenameAliasIdentical.message"),
                alias),
            res.getString("RenameTrustedCertificateAction.RenameEntry.Title"),
            JOptionPane.WARNING_MESSAGE);
        return;
      }

      if (keyStore.containsAlias(newAlias)) {
        String message =
            MessageFormat.format(
                res.getString("RenameTrustedCertificateAction.OverWriteEntry.message"), newAlias);

        int selected =
            JOptionPane.showConfirmDialog(
                frame,
                message,
                res.getString("RenameTrustedCertificateAction.RenameEntry.Title"),
                JOptionPane.YES_NO_OPTION);
        if (selected != JOptionPane.YES_OPTION) {
          return;
        }

        keyStore.deleteEntry(newAlias);
        newState.removeEntryPassword(newAlias);
      }

      Certificate cert = keyStore.getCertificate(alias);
      keyStore.setCertificateEntry(newAlias, cert);

      keyStore.deleteEntry(alias);

      currentState.append(newState);

      kseFrame.updateControls(true);
    } catch (Exception ex) {
      DError.displayError(frame, ex);
    }
  }
 public void remove(Certificate certificate) throws KeyStoreException {
   String alias = keyStore.getCertificateAlias(certificate);
   if (alias != null) {
     keyStore.deleteEntry(alias);
   }
 }
 public void test_deleteEmptyEntryBogusAlias() throws Exception {
   KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
   keyTest.load(null, null);
   keyTest.deleteEntry("bogus");
 }
  /** Generate a secret key in the currently opened KeyStore. */
  public void generateSecret() {
    try {
      int secretKeySize = applicationSettings.getGenerateSecretKeySize();
      SecretKeyType secretKeyType = applicationSettings.getGenerateSecretKeyType();

      DGenerateSecretKey dGenerateSecretKey =
          new DGenerateSecretKey(frame, secretKeyType, secretKeySize);
      dGenerateSecretKey.setLocationRelativeTo(frame);
      dGenerateSecretKey.setVisible(true);

      if (!dGenerateSecretKey.isSuccessful()) {
        return;
      }

      secretKeySize = dGenerateSecretKey.getSecretKeySize();
      secretKeyType = dGenerateSecretKey.getSecretKeyType();

      applicationSettings.setGenerateSecretKeySize(secretKeySize);
      applicationSettings.setGenerateSecretKeyType(secretKeyType);

      SecretKey secretKey = SecretKeyUtil.generateSecretKey(secretKeyType, secretKeySize);

      KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();

      KeyStoreState currentState = history.getCurrentState();
      KeyStoreState newState = currentState.createBasisForNextState(this);

      KeyStore keyStore = newState.getKeyStore();

      DGetAlias dGetAlias =
          new DGetAlias(
              frame, res.getString("GenerateSecretKeyAction.NewSecretKeyEntryAlias.Title"), null);
      dGetAlias.setLocationRelativeTo(frame);
      dGetAlias.setVisible(true);
      String alias = dGetAlias.getAlias();

      if (alias == null) {
        return;
      }

      if (keyStore.containsAlias(alias)) {
        String message =
            MessageFormat.format(
                res.getString("GenerateSecretKeyAction.OverWriteEntry.message"), alias);

        int selected =
            JOptionPane.showConfirmDialog(
                frame,
                message,
                res.getString("GenerateSecretKeyAction.NewSecretKeyEntryAlias.Title"),
                JOptionPane.YES_NO_OPTION);
        if (selected != JOptionPane.YES_OPTION) {
          return;
        }
      }

      Password password = new Password((char[]) null);
      KeyStoreType type = KeyStoreType.resolveJce(keyStore.getType());

      if (type.hasEntryPasswords()) {
        DGetNewPassword dGetNewPassword =
            new DGetNewPassword(
                frame,
                res.getString("GenerateSecretKeyAction.NewSecretKeyEntryPassword.Title"),
                applicationSettings.getPasswordQualityConfig());
        dGetNewPassword.setLocationRelativeTo(frame);
        dGetNewPassword.setVisible(true);
        password = dGetNewPassword.getPassword();

        if (password == null) {
          return;
        }
      }

      if (keyStore.containsAlias(alias)) {
        keyStore.deleteEntry(alias);
        newState.removeEntryPassword(alias);
      }

      keyStore.setKeyEntry(alias, secretKey, password.toCharArray(), null);
      newState.setEntryPassword(alias, password);

      currentState.append(newState);

      kseFrame.updateControls(true);

      JOptionPane.showMessageDialog(
          frame,
          res.getString("GenerateSecretKeyAction.SecretKeyGenerationSuccessful.message"),
          res.getString("GenerateSecretKeyAction.GenerateSecretKey.Title"),
          JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
      DError.displayError(frame, ex);
    }
  }
  public void runTest(String provider) throws Exception {

    // load private key
    // all keystore types should support private keys
    KeySpec spec =
        new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(PRIVATE_KEY_PKCS8_BASE64));
    PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(spec);

    // load x509 certificate
    Certificate cert;
    try (InputStream is =
        new BufferedInputStream(new ByteArrayInputStream(CERTIFICATE.getBytes()))) {
      cert = CertificateFactory.getInstance("X.509").generateCertificate(is);
    }

    int numEntries = 5;
    String type = null;
    for (int i = 0; i < PROVIDERS.length; i++) {
      if (provider.compareTo(PROVIDERS[i]) == 0) {
        type = KS_Type[i];
        break;
      }
    }

    System.out.printf("Test %s provider and %s keystore%n", provider, type);
    KeyStore ks = KeyStore.getInstance(type, provider);
    KeyStore ks2 = KeyStore.getInstance(type, ks.getProvider().getName());

    // create an empty key store
    ks.load(null, null);

    // store the secret keys
    for (int j = 0; j < numEntries; j++) {
      ks.setKeyEntry(ALIAS_HEAD + j, privateKey, PASSWDK, new Certificate[] {cert});
    }

    // initialize the 2nd key store object with the 1st one
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ks.store(baos, PASSWDK);
    byte[] bArr = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(bArr);
    ks2.load(bais, null);

    // check 2nd key store type
    checkType(ks2, type);
    // check the existing aliases for the 2nd key store
    checkAlias(ks2, numEntries);

    // compare the creation date of the 2 key stores for all aliases
    compareCreationDate(ks, ks2, numEntries);
    // remove the last entry from the 2nd key store
    numEntries--;
    ks2.deleteEntry(ALIAS_HEAD + numEntries);

    // re-initialize the 1st key store with the 2nd key store
    baos.reset();
    ks2.store(baos, PASSWD2);
    bais = new ByteArrayInputStream(baos.toByteArray());
    try {
      // expect an exception since the password is incorrect
      ks.load(bais, PASSWDK);
      throw new RuntimeException("ERROR: passed the loading with incorrect password");
    } catch (IOException ex) {
      System.out.println("Expected exception: " + ex);
      if (!causedBy(ex, UnrecoverableKeyException.class)) {
        ex.printStackTrace(System.out);
        throw new RuntimeException("Unexpected cause");
      }
      System.out.println("Expected cause: " + UnrecoverableKeyException.class.getName());

      bais.reset();
      ks.load(bais, PASSWD2);
      bais.reset();
      ks.load(bais, null);
    }

    // check key store type
    checkType(ks, type);

    // check the existing aliases
    checkAlias(ks, numEntries);

    // compare the creation date of the 2 key stores for all aliases
    compareCreationDate(ks, ks2, numEntries);
  }