Example usage for java.security KeyStore deleteEntry

List of usage examples for java.security KeyStore deleteEntry

Introduction

In this page you can find the example usage for java.security KeyStore deleteEntry.

Prototype

public final void deleteEntry(String alias) throws KeyStoreException 

Source Link

Document

Deletes the entry identified by the given alias from this keystore.

Usage

From source file:org.sufficientlysecure.keychain.ui.SettingsSmartPGPAuthorityFragment.java

private boolean editAuthority(final String old_alias, final String new_alias, final int position,
        final String uri) {
    try {//from w w  w.  jav a  2  s  . co m
        final KeyStore ks = SettingsSmartPGPAuthoritiesActivity.readKeystore(getContext());

        if (ks == null) {
            throw new KeyStoreException("no keystore found");
        }

        Certificate old_cert = null;
        if (old_alias != null) {
            old_cert = ks.getCertificate(old_alias);
            ks.deleteEntry(old_alias);
            mAuthorities.remove(old_alias);
            mAdapter.notifyItemRemoved(position);
        }

        Certificate new_cert = null;
        if (uri == null) {
            new_cert = old_cert;
        } else {
            final InputStream fis = getContext().getContentResolver().openInputStream(Uri.parse(uri));

            final CertificateFactory cf = CertificateFactory.getInstance("X.509");
            new_cert = cf.generateCertificate(fis);
            if (!(new_cert instanceof X509Certificate)) {
                Notify.create(getActivity(), "Invalid certificate", Notify.LENGTH_LONG, Notify.Style.ERROR)
                        .show();
                return false;
            }

            fis.close();
        }

        if (new_alias == null || new_cert == null) {
            Notify.create(getActivity(), "Missing alias or certificate", Notify.LENGTH_LONG, Notify.Style.ERROR)
                    .show();
            return false;
        }

        final X509Certificate x509cert = (X509Certificate) new_cert;

        x509cert.checkValidity();

        ks.setCertificateEntry(new_alias, x509cert);

        SettingsSmartPGPAuthoritiesActivity.writeKeystore(getContext(), ks);

        mAuthorities.add(new_alias);
        mAdapter.notifyItemInserted(mAuthorities.size() - 1);

        return true;

    } catch (IOException e) {
        Notify.create(getActivity(), "failed to open certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    } catch (CertificateException e) {
        Notify.create(getActivity(), "invalid certificate (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    } catch (KeyStoreException e) {
        Notify.create(getActivity(), "invalid keystore (" + e.getMessage() + ")", Notify.LENGTH_LONG,
                Notify.Style.ERROR).show();
    }

    return false;
}

From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java

private String deleteInfrastructure(Integer id) {

    InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class);
    InfrastructureDataObject toDelete = dao.getInfrastructure(id);

    // there is a problem if the alias is null..
    if (toDelete.getAlias() == null) {
        dao.remove(id);/*from  ww  w  . ja  va  2  s.co  m*/
        return "delete";
    }

    //Preparing for the KeyStore containsAlias() test
    OscarProperties oscarProperties = OscarProperties.getInstance();
    String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE");
    String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE");
    String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD");
    String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD");

    String alias = toDelete.getAlias();

    KeyStore ks = null;
    KeyStore ts = null;

    try {

        ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray());
        ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray());

        if (ks.containsAlias(alias)) {
            ks.deleteEntry(alias);
            ts.deleteEntry(alias);
        }

        // save the keystore
        ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray());
        // save the truststore
        ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray());

    } catch (SslException ex) {
        LOGGER.info(ex);
    } catch (KeyStoreException ex) {
        LOGGER.info(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOGGER.info(ex);
    } catch (CertificateException ex) {
        LOGGER.info(ex);
    } catch (FileNotFoundException ex) {
        LOGGER.info(ex);
    } catch (IOException ex) {
        LOGGER.info(ex);
    }

    dao.remove(id);

    return "delete";

}

From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

/** Extension request to sign specified cert and return the signed cert. */
@SuppressWarnings("static-access")
public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req,
        Map<?, ?> idToRepositoryItemMap) throws RegistryException {

    RegistryResponseHolder respHolder = null;
    RegistryResponseType ebRegistryResponseType = null;
    ServerRequestContext context = null;

    try {//  w  w w .j  av  a 2  s  . c om
        context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req);
        context.setUser(user);

        if (idToRepositoryItemMap.keySet().size() == 0) {
            throw new MissingRepositoryItemException(
                    ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound"));
        }

        String id = (String) idToRepositoryItemMap.keySet().iterator().next();

        Object obj = idToRepositoryItemMap.get(id);
        if (!(obj instanceof RepositoryItem)) {
            throw new InvalidContentException();
        }
        RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed            

        //Read original cert from keystore
        InputStream is = ri.getDataHandler().getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        is.close();
        X509Certificate cert = (X509Certificate) keyStore
                .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);

        //Sign the cert
        cert = signCertificate(cert);

        //Replace cert with signed cert in keystore
        keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert);

        //Add CA root cert (RegistryOPerator's cert) to keystore.
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate());

        Certificate[] certChain = new Certificate[2];
        certChain[0] = cert;
        certChain[1] = getCACertificate();
        validateChain(certChain);

        File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        fos.flush();
        fos.close();

        DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile));
        RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh);

        ebRegistryResponseType = bu.rsFac.createRegistryResponseType();
        ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>();
        respIdToRepositoryItemMap.put(id, riNew);

        respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap);

    } catch (RegistryException e) {
        context.rollback();
        throw e;
    } catch (Exception e) {
        context.rollback();
        throw new RegistryException(e);
    }

    context.commit();
    return respHolder;
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void deleteFromStore(String alias, String path, String pass, KeyStore store) {
    if (alias == null) {
        throw new IllegalArgumentException("Alias cannot be null.");
    }//from  w w w.j a  v a2s .  c  om
    File storeFile = new File(path);
    try (FileOutputStream fos = new FileOutputStream(storeFile)) {
        store.deleteEntry(alias);
        store.store(fos, pass.toCharArray());
    } catch (KeyStoreException | IOException | CertificateException | NoSuchAlgorithmException e) {
        LOGGER.error("Unable to remove entry {} from store", alias, e);
    }
}

From source file:nl.afas.cordova.plugin.secureLocalStorage.SecureLocalStorage.java

private void clear(File file, KeyStore keyStore) throws SecureLocalStorageException {
    if (file.exists()) {
        if (!file.delete()) {
            throw new SecureLocalStorageException("Could not delete storage file");
        }//from w w w .ja v a 2 s  .c om
    }
    try {
        if (keyStore.containsAlias(SECURELOCALSTORAGEALIAS)) {
            keyStore.deleteEntry(SECURELOCALSTORAGEALIAS);
        }
    } catch (Exception e) {
        throw new SecureLocalStorageException(e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

public void removeCertFromStore(String alias, String keyStoreName) throws SecurityConfigException {
    try {/*w  ww . ja v  a 2 s  . c o  m*/
        if (keyStoreName == null) {
            throw new SecurityConfigException("Key Store name can't be null");
        }

        KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
        KeyStore ks = keyMan.getKeyStore(keyStoreName);

        if (ks.getCertificate(alias) == null) {
            return;
        }

        ks.deleteEntry(alias);
        keyMan.updateKeyStore(keyStoreName, ks);
    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when removing cert from store";
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }
}

From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java

private boolean update(String keyStore) {
    // Load the keystore
    FileInputStream fis = null;// w w  w .  j  a  v a2s .co  m
    try {
        fis = new FileInputStream(keyStore);
    } catch (FileNotFoundException e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME);
        ks.load(fis, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to open the key store: " + e);
        return false;
    }

    try {
        // Create a certificate
        CertificateGenerator gen = new CertificateGenerator();
        KeyPair pair = gen.generateRSAKeyPair();
        X509Certificate cert = gen.generateCertificate(SslHelpers.DEFAULT_SUBJET_DN, pair);

        // Remove the old certificate if needed
        try {
            ks.deleteEntry(SslHelpers.DEFAULT_SUBJET_DN);
        } catch (KeyStoreException e) {
            // OK
        }

        // Add the certificate
        ks.setCertificateEntry(SslHelpers.DEFAULT_SUBJET_DN, cert);
        // Write the keystore
        FileOutputStream fos = new FileOutputStream(new File(keyStore));
        ks.store(fos, SslHelpers.DEFAULT_KS_PASSWD.toCharArray());
        fos.close();
        return true;
    } catch (Exception e) {
        System.err.println("Failed to update the keystore " + keyStore + ": " + e);
        return false;
    }
}

From source file:org.freebxml.omar.server.security.authentication.AuthenticationServiceImpl.java

/**
 * This method is used to remove a certificate from the server keystore.
 * This is called, for example, when a rim:User has been deleted and the 
 * User's credentials need to be cleared from the server keystore
 *
 * @param alias//from   ww w .ja va  2s. com
 *  A java.lang.String that contains the alias of the public key credential
 */
public void deleteUserCertificate(String alias) throws RegistryException {
    KeyStore keyStore = getKeyStore();
    java.io.FileOutputStream fos = null;
    try {
        String keystoreFile = getKeyStoreFileName();
        synchronized (keyStoreWriteLock) {
            fos = new java.io.FileOutputStream(keystoreFile);
            keyStore.deleteEntry(alias);
            String keystorePass = getKeyStorePassword();
            keyStore.store(fos, keystorePass.toCharArray());
            fos.flush();
            this.keyStore = null;
        }
    } catch (Throwable t) {
        throw new RegistryException(t);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException io) {
            }
        }
    }
}

From source file:it.cnr.icar.eric.server.security.authentication.AuthenticationServiceImpl.java

/**
 * This method is used to remove a certificate from the server keystore.
 * This is called, for example, when a rim:User has been deleted and the
 * User's credentials need to be cleared from the server keystore
 * //from  ww w  . j  av a  2 s . c  om
 * @param alias
 *            A java.lang.String that contains the alias of the public key
 *            credential
 */
public void deleteUserCertificate(String alias) throws RegistryException {
    KeyStore keyStore = getKeyStore();
    java.io.FileOutputStream fos = null;
    try {
        String keystoreFile = getKeyStoreFileName();
        synchronized (keyStoreWriteLock) {
            fos = new java.io.FileOutputStream(keystoreFile);
            keyStore.deleteEntry(alias);
            String keystorePass = getKeyStorePassword();
            keyStore.store(fos, keystorePass.toCharArray());
            fos.flush();
            this.keyStore = null;
        }
    } catch (Throwable t) {
        throw new RegistryException(t);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException io) {
                fos = null;
            }
        }
    }
}

From source file:org.mule.api.security.tls.TlsConfiguration.java

protected void checkKeyStoreContainsAlias(KeyStore keyStore) throws KeyStoreException {
    if (StringUtils.isNotBlank(keyAlias)) {
        boolean keyAliasFound = false;

        Enumeration<String> aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();

            if (alias.equals(keyAlias)) {
                // if alias is found all is valid but continue processing to strip out all
                // other (unwanted) keys
                keyAliasFound = true;//  www  . j  a  v  a 2  s  . c o  m
            } else {
                // if the current alias is not the one we are looking for, remove
                // it from the keystore
                keyStore.deleteEntry(alias);
            }
        }

        // if the alias was not found, throw an exception
        if (!keyAliasFound) {
            throw new IllegalStateException("Key with alias \"" + keyAlias + "\" was not found");
        }
    }
}