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.wso2.carbon.apimgt.impl.utils.CertificateMgtUtils.java

/**
 * Method to update the certificate which matches the given alias.
 *
 * @param certificate: The base64 encoded certificate string.
 * @param alias        : Alias of the certificate that should be retrieved.
 * @return ://from  ww w. j  a  v  a2s.c  o  m
 */
public ResponseCode updateCertificate(String certificate, String alias) throws CertificateManagementException {

    InputStream certificateStream = null;
    try {
        File trustStoreFile = new File(TRUST_STORE);
        localTrustStoreStream = new FileInputStream(trustStoreFile);
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(localTrustStoreStream, TRUST_STORE_PASSWORD);

        if (trustStore.getCertificate(alias) == null) {
            log.error("Could not update the certificate. The certificate for alias '" + alias + "' is not found"
                    + " in the trust store.");
            return ResponseCode.CERTIFICATE_NOT_FOUND;
        }

        //Generate the certificate from the input string.
        byte[] cert = (Base64.decodeBase64(certificate.getBytes(CHARSET_UTF_8)));
        certificateStream = new ByteArrayInputStream(cert);

        if (certificateStream.available() == 0) {
            log.error("Certificate is empty for the provided alias " + alias);
            return ResponseCode.INTERNAL_SERVER_ERROR;
        }

        CertificateFactory certificateFactory = CertificateFactory.getInstance(CERTIFICATE_TYPE);
        Certificate newCertificate = certificateFactory.generateCertificate(certificateStream);
        X509Certificate x509Certificate = (X509Certificate) newCertificate;

        if (x509Certificate.getNotAfter().getTime() <= System.currentTimeMillis()) {
            log.error("Could not update the certificate. The certificate expired.");
            return ResponseCode.CERTIFICATE_EXPIRED;
        }
        // If the certificate is not expired, delete the existing certificate and add the new cert.
        trustStore.deleteEntry(alias);
        //Store the certificate in the trust store.
        trustStore.setCertificateEntry(alias, newCertificate);
        fileOutputStream = new FileOutputStream(trustStoreFile);
        trustStore.store(fileOutputStream, TRUST_STORE_PASSWORD);
    } catch (IOException e) {
        throw new CertificateManagementException("Error updating certificate.", e);
    } catch (CertificateException e) {
        throw new CertificateManagementException("Error generating the certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateManagementException("Error loading the keystore.", e);
    } catch (KeyStoreException e) {
        throw new CertificateManagementException("Error updating the certificate in the keystore.", e);
    } finally {
        closeStreams(fileOutputStream, certificateStream, localTrustStoreStream);
    }
    return ResponseCode.SUCCESS;
}

From source file:com.cloud.bridge.service.EC2RestServlet.java

/**
 * The SOAP API for EC2 uses WS-Security to sign all client requests.  This requires that 
 * the client have a public/private key pair and the public key defined by a X509 certificate.
 * This REST call allows a Cloud.com account holder to remove a previouly "loaded" X509
 * certificate out of the EC2 service./*w  ww  . j a  v a  2s .  co  m*/
 * 
 * This is an unauthenticated REST call and as such must contain all the required REST parameters
 * including: Signature, Timestamp, Expires, etc.   The signature is calculated using the
 * Cloud.com account holder's API access and secret keys and the Amazon defined EC2 signature
 * algorithm.
 */
private void deleteCertificate(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Transaction txn = null;
    try {
        String[] accessKey = request.getParameterValues("AWSAccessKeyId");
        if (null == accessKey || 0 == accessKey.length) {
            response.sendError(530, "Missing AWSAccessKeyId parameter");
            return;
        }

        // -> delete the specified entry and save back to disk
        FileInputStream fsIn = new FileInputStream(pathToKeystore);
        KeyStore certStore = KeyStore.getInstance("JKS");
        certStore.load(fsIn, keystorePassword.toCharArray());

        if (certStore.containsAlias(accessKey[0])) {
            certStore.deleteEntry(accessKey[0]);
            FileOutputStream fsOut = new FileOutputStream(pathToKeystore);
            certStore.store(fsOut, keystorePassword.toCharArray());

            // -> dis-associate the cert's uniqueId with the Cloud API keys
            /*                UserCredentialsDao credentialDao = new UserCredentialsDao();
                            credentialDao.setCertificateId( accessKey[0], null );
                                    
            */ txn = Transaction.open(Transaction.AWSAPI_DB);
            UserCredentialsVO user = ucDao.getByAccessKey(accessKey[0]);
            user.setCertUniqueId(null);
            ucDao.update(user.getId(), user);
            response.setStatus(200);
            endResponse(response, "User certificate deleted successfully");
            txn.commit();
        } else
            response.setStatus(404);

    } catch (NoSuchObjectException e) {
        logger.error("SetCertificate exception " + e.getMessage(), e);
        response.sendError(404, "SetCertificate exception " + e.getMessage());

    } catch (Exception e) {
        logger.error("DeleteCertificate exception " + e.getMessage(), e);
        response.sendError(500, "DeleteCertificate exception " + e.getMessage());
    } finally {
        txn.close();
    }
}

From source file:be.fgov.kszbcss.rhq.websphere.connector.agent.ConnectorSubsystemComponent.java

public OperationResult invokeOperation(String name, Configuration parameters)
        throws InterruptedException, Exception {
    if (name.equals("importCertificateFromFile")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream in = new FileInputStream(parameters.getSimple("file").getStringValue());
        try {// w  w  w. j  av a2s  .  c om
            Iterator<? extends Certificate> it = cf.generateCertificates(in).iterator();
            if (it.hasNext()) {
                TrustStoreManager.getInstance().addCertificate(parameters.getSimple("alias").getStringValue(),
                        (X509Certificate) it.next());
            } else {
                throw new Exception("No certificate found");
            }
        } finally {
            in.close();
        }
        return null;
    } else if (name.equals("retrieveCellCertificate")) {
        DeploymentManager dm = new DeploymentManager(null, new ConfigurationBasedProcessLocator(parameters));
        String cell = dm.getCell();
        ConfigQueryExecutor configQueryExecutor = ConfigQueryServiceFactory.getInstance()
                .getConfigQueryExecutor(dm);
        try {
            X509Certificate cert = configQueryExecutor.query(CellRootCertificateQuery.INSTANCE);
            TrustStoreManager.getInstance().addCertificate("cell:" + cell, cert);
        } finally {
            configQueryExecutor.destroy();
        }
        return null;
    } else if (name.equals("retrieveCertificateFromPort")) {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(new KeyManager[0],
                new TrustManager[] {
                        new AutoImportTrustManager(parameters.getSimple("alias").getStringValue()) },
                new SecureRandom());
        SSLSocket socket = (SSLSocket) sslContext.getSocketFactory().createSocket(
                parameters.getSimple("host").getStringValue(), parameters.getSimple("port").getIntegerValue());
        try {
            socket.startHandshake();
        } finally {
            socket.close();
        }
        return null;
    } else if (name.equals("listCertificates")) {
        final PropertyList certificates = new PropertyList("certificates");
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                // Sort the aliases for convenience
                Set<String> aliases = new TreeSet<String>();
                for (Enumeration<String> e = truststore.aliases(); e.hasMoreElements();) {
                    aliases.add(e.nextElement());
                }
                for (String alias : aliases) {
                    X509Certificate cert = (X509Certificate) truststore.getCertificate(alias);
                    PropertyMap map = new PropertyMap("certificate");
                    map.put(new PropertySimple("alias", alias));
                    map.put(new PropertySimple("subject", cert.getSubjectDN().toString()));
                    MessageDigest md = MessageDigest.getInstance("SHA-1");
                    md.update(cert.getEncoded());
                    byte[] digest = md.digest();
                    StringBuilder fingerprint = new StringBuilder();
                    for (int i = 0; i < digest.length; i++) {
                        if (i > 0) {
                            fingerprint.append(':');
                        }
                        fingerprint.append(getHexDigit(((int) digest[i] & 0xf0) >> 4));
                        fingerprint.append(getHexDigit((int) digest[i] & 0x0f));
                    }
                    map.put(new PropertySimple("fingerprint", fingerprint.toString()));
                    certificates.add(map);
                }
            }
        }, true);
        if (log.isDebugEnabled()) {
            log.debug("certificates=" + certificates);
        }
        OperationResult result = new OperationResult();
        result.getComplexResults().put(certificates);
        return result;
    } else if (name.equals("removeCertificate")) {
        final String alias = parameters.getSimple("alias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                truststore.deleteEntry(alias);
            }
        }, false);
        return null;
    } else if (name.equals("renameCertificate")) {
        final String oldAlias = parameters.getSimple("oldAlias").getStringValue();
        final String newAlias = parameters.getSimple("newAlias").getStringValue();
        TrustStoreManager.getInstance().execute(new TrustStoreAction() {
            public void execute(KeyStore truststore) throws Exception {
                Certificate cert = truststore.getCertificate(oldAlias);
                truststore.setCertificateEntry(newAlias, cert);
                truststore.deleteEntry(oldAlias);
            }
        }, false);
        return null;
    } else {
        return null;
    }
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    log.trace(">exportCAKeyStore");
    try {//from  w w w  .  j a v  a2s.  c om
        final CA thisCa = caSession.getCAForEdit(admin, caname);
        // Make sure we are not trying to export a hard or invalid token
        CAToken thisCAToken = thisCa.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (!(cryptoToken instanceof SoftCryptoToken)) {
            throw new IllegalCryptoTokenException("Cannot export anything but a soft token.");
        }
        // Do not allow export without password protection
        if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) {
            throw new IllegalArgumentException("Cannot export a token without password protection.");
        }
        // Check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
            throw new AuthorizationDeniedException(msg);
        }
        // Fetch keys
        final char[] password = keystorepass.toCharArray();
        ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password);
        cryptoToken.activate(password);

        PrivateKey p12PrivateEncryptionKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PublicKey p12PublicEncryptionKey = cryptoToken
                .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PrivateKey p12PrivateCertSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        PrivateKey p12PrivateCRLSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
        if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) {
            throw new Exception("Assertion of equal signature keys failed.");
        }
        // Proceed with the export
        byte[] ret = null;
        String format = null;
        if (thisCa.getCAType() == CAInfo.CATYPE_CVC) {
            log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm()
                    + " of format: " + p12PrivateCertSignKey.getFormat());
            format = p12PrivateCertSignKey.getFormat();
            ret = p12PrivateCertSignKey.getEncoded();
        } else {
            log.debug("Exporting PKCS12 keystore");
            format = "PKCS12";
            KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(null, keystorepass.toCharArray());
            // Load keys into keystore
            Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain()
                    .toArray(new Certificate[0]);
            Certificate[] certificateChainEncryption = new Certificate[1];
            // certificateChainSignature[0].getSigAlgName(),
            // generate dummy certificate for encryption key.
            certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null,
                    p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true,
                    X509KeyUsage.keyEncipherment, true);
            log.debug("Exporting with sigAlgorithm "
                    + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm="
                    + thisCAToken.getEncryptionAlgorithm());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
            }

            keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(),
                    certificateChainSignature);
            keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(),
                    certificateChainEncryption);
            // Return KeyStore as byte array and clean up
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            keystore.store(baos, keystorepass.toCharArray());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                keystore.deleteEntry(privateSignatureKeyAlias);
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                keystore.deleteEntry(privateEncryptionKeyAlias);
            }
            ret = baos.toByteArray();
        }
        String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
        log.trace("<exportCAKeyStore");
        return ret;
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, details);
        throw new EJBException(e);
    }
}

From source file:org.kse.gui.actions.ImportCaReplyFromFileAction.java

/**
 * Do action.// ww  w.j av  a2 s  .  c  o  m
 */
@Override
protected void doAction() {
    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStoreState newState = currentState.createBasisForNextState(this);

        KeyStore keyStore = newState.getKeyStore();
        KeyStoreType keyStoreType = KeyStoreType.resolveJce(keyStore.getType());

        Key privateKey = keyStore.getKey(alias, password.toCharArray());

        File caReplyFile = chooseCaFile();
        if (caReplyFile == null) {
            return;
        }

        X509Certificate[] certs = openCaReply(caReplyFile);

        if ((certs == null) || (certs.length == 0)) {
            return;
        }

        certs = X509CertUtil.orderX509CertChain(certs);

        X509Certificate[] exitingEntryCerts = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)));

        if (!exitingEntryCerts[0].getPublicKey().equals(certs[0].getPublicKey())) {
            JOptionPane.showMessageDialog(frame,
                    res.getString("ImportCaReplyFromFileAction.NoMatchPubKeyCaReply.message"),
                    res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        // Holds the new certificate chain for the entry should the import succeed
        X509Certificate[] newCertChain = null;

        if (!applicationSettings.getEnableImportCaReplyTrustCheck()) {
            newCertChain = certs;
        } else {
            KeyStore caCertificates = getCaCertificates();
            KeyStore windowsTrustedRootCertificates = getWindowsTrustedRootCertificates();

            // PKCS #7 reply - try and match the self-signed root with any
            // of the certificates in the CA Certificates or current KeyStore
            if (certs.length > 1) {
                X509Certificate rootCert = certs[certs.length - 1];
                String matchAlias = null;

                if (caCertificates != null) // Match against CA Certificates KeyStore
                {
                    matchAlias = X509CertUtil.matchCertificate(caCertificates, rootCert);
                }

                // Match against Windows Trusted Root Certificates KeyStore
                if ((windowsTrustedRootCertificates != null) && (matchAlias == null)) {
                    matchAlias = X509CertUtil.matchCertificate(windowsTrustedRootCertificates, rootCert);
                }

                if (matchAlias == null) // Match against current KeyStore
                {
                    matchAlias = X509CertUtil.matchCertificate(keyStore, rootCert);
                }

                if (matchAlias == null) {
                    // No match for the root certificate - display the certificate to the user for confirmation
                    JOptionPane.showMessageDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.NoMatchRootCertCaReplyConfirm.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.INFORMATION_MESSAGE);

                    DViewCertificate dViewCertificate = new DViewCertificate(frame,
                            MessageFormat.format(
                                    res.getString("ImportCaReplyFromFileAction.CertDetailsFile.Title"),
                                    caReplyFile.getName()),
                            new X509Certificate[] { rootCert }, null, DViewCertificate.NONE);
                    dViewCertificate.setLocationRelativeTo(frame);
                    dViewCertificate.setVisible(true);

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

                    newCertChain = certs;
                } else {
                    newCertChain = certs;
                }
            }
            // Single X.509 certificate reply - try and establish a chain of
            // trust from the certificate and ending with a root CA self-signed certificate
            else {
                // Establish trust against current KeyStore
                ArrayList<KeyStore> compKeyStores = new ArrayList<>();
                compKeyStores.add(keyStore);

                if (caCertificates != null) {
                    // Establish trust against CA Certificates KeyStore
                    compKeyStores.add(caCertificates);
                }

                if (windowsTrustedRootCertificates != null) {
                    // Establish trust against Windows Trusted Root Certificates KeyStore
                    compKeyStores.add(windowsTrustedRootCertificates);
                }

                X509Certificate[] trustChain = X509CertUtil.establishTrust(certs[0],
                        compKeyStores.toArray(new KeyStore[compKeyStores.size()]));

                if (trustChain != null) {
                    newCertChain = trustChain;
                } else {
                    // Cannot establish trust for the certificate - fail
                    JOptionPane.showMessageDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.NoTrustCaReply.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.WARNING_MESSAGE);
                    return;
                }
            }
        }

        if (keyStoreType.isFileBased()) {
            // TODO: why or when is delete actually necessary???
            keyStore.deleteEntry(alias);
            keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain);
        } else {
            keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain);
        }

        currentState.append(newState);

        kseFrame.updateControls(true);

        JOptionPane.showMessageDialog(frame,
                res.getString("ImportCaReplyFromFileAction.ImportCaReplySuccessful.message"),
                res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
        DError.displayError(frame, ex);
    }
}