Example usage for java.security KeyStore containsAlias

List of usage examples for java.security KeyStore containsAlias

Introduction

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

Prototype

public final boolean containsAlias(String alias) throws KeyStoreException 

Source Link

Document

Checks if the given alias exists in this keystore.

Usage

From source file:com.mirth.connect.server.controllers.DefaultConfigurationController.java

/**
 * Checks for an existing certificate to use for secure communication between the server and
 * client. If no certficate exists, this will generate a new one.
 * /*www.j  av  a 2 s . c  om*/
 */
private void generateDefaultCertificate(Provider provider, KeyStore keyStore, char[] keyPassword)
        throws Exception {
    final String certificateAlias = "mirthconnect";

    if (!keyStore.containsAlias(certificateAlias)) {
        // Common CA and SSL cert attributes
        Date startDate = new Date(); // time from which certificate is valid
        Date expiryDate = DateUtils.addYears(startDate, 50); // time after which certificate is not valid
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", provider);
        keyPairGenerator.initialize(2048);

        KeyPair caKeyPair = keyPairGenerator.generateKeyPair();
        logger.debug("generated new key pair for CA cert using provider: " + provider.getName());

        // Generate CA cert
        X500Name caSubjectName = new X500Name("CN=Mirth Connect Certificate Authority");
        SubjectPublicKeyInfo caSubjectKey = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(caKeyPair.getPublic().getEncoded()));
        X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(caSubjectName, BigInteger.ONE,
                startDate, expiryDate, caSubjectName, caSubjectKey);
        certBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.basicConstraints, true,
                new BasicConstraints(0));
        ContentSigner sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider)
                .build(caKeyPair.getPrivate());
        Certificate caCert = new JcaX509CertificateConverter().setProvider(provider)
                .getCertificate(certBuilder.build(sigGen));

        // Generate SSL cert
        KeyPair sslKeyPair = keyPairGenerator.generateKeyPair();
        logger.debug("generated new key pair for SSL cert using provider: " + provider.getName());

        X500Name sslSubjectName = new X500Name("CN=mirth-connect");
        SubjectPublicKeyInfo sslSubjectKey = new SubjectPublicKeyInfo(
                ASN1Sequence.getInstance(sslKeyPair.getPublic().getEncoded()));
        X509v3CertificateBuilder sslCertBuilder = new X509v3CertificateBuilder(caSubjectName,
                new BigInteger(50, new SecureRandom()), startDate, expiryDate, sslSubjectName, sslSubjectKey);
        sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(caCert.getEncoded()));
        sslCertBuilder.addExtension(org.bouncycastle.asn1.x509.Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(sslKeyPair.getPublic().getEncoded()));

        sigGen = new JcaContentSignerBuilder("SHA256withRSA").setProvider(provider)
                .build(caKeyPair.getPrivate());
        Certificate sslCert = new JcaX509CertificateConverter().setProvider(provider)
                .getCertificate(sslCertBuilder.build(sigGen));

        logger.debug("generated new certificate with serial number: "
                + ((X509Certificate) sslCert).getSerialNumber());

        // add the generated SSL cert to the keystore using the key password
        keyStore.setKeyEntry(certificateAlias, sslKeyPair.getPrivate(), keyPassword,
                new Certificate[] { sslCert });
    } else {
        logger.debug("found certificate in keystore");
    }
}

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./* ww w. java 2s  . c  om*/
 * 
 * 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:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java

/**
 * Set the identity for the communications to the XMLRPC controller. Eventually
 * we may talk to several controller with different identities. For now only
 * one is configured./*from   w w  w  .  j a  v a2  s  .  c  o m*/
 */
private void setSSLIdentity() throws Exception {

    //if (sslIdentitySet)
    //   return;

    //System.out.println("In setSSLIdentity()");

    try {
        // create multikeymanager
        mkm = new MultiKeyManager();
        //TODO
        //URL ctrlrUrl = new URL(GUI.getInstance().getSelectedController());
        URL ctrlrUrl = new URL(CONTROLLER_URL);
        // TODO

        // register a new protocol
        ContextualSSLProtocolSocketFactory regSslFact = new ContextualSSLProtocolSocketFactory();

        // add this multikey context factory for the controller host/port
        regSslFact.addHostContextFactory(new MultiKeySSLContextFactory(mkm, trustAllCerts), ctrlrUrl.getHost(),
                ctrlrUrl.getPort());

        if (rmProperties == null) {
            System.out.println("ERROR ... Property File with user credentials not supplied...");
            return;
        }

        KeyStore ks = null;

        //File keyStorePath = loadUserFile("/Users/anirban/Misc/tmp/renci-openvpn/flukes.jks");
        //File certFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        //File certKeyFilePath = loadUserFile("/Users/anirban/.ssl/geni-anirban.pem");
        File keyStorePath = null;
        File certFilePath = null;
        File certKeyFilePath = null;

        if (rmProperties.getProperty(USER_KEYSTORE_PATH_PROP) != null) {
            keyStorePath = loadUserFile(rmProperties.getProperty(USER_KEYSTORE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTFILE_PATH_PROP) != null) {
            certFilePath = loadUserFile(rmProperties.getProperty(USER_CERTFILE_PATH_PROP));
        }
        if (rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP) != null) {
            certKeyFilePath = loadUserFile(rmProperties.getProperty(USER_CERTKEYFILE_PATH_PROP));
        }

        String keyAlias = null, keyPassword = null;
        if (keyStorePath != null && keyStorePath.exists()) {
            // load keystore and get the right cert from it
            System.out.println("Reading auth details from keystore");
            //TODO
            keyAlias = rmProperties.getProperty(USER_KEYSTORE_KEYALIAS_PROP);
            keyPassword = rmProperties.getProperty(USER_KEYSTORE_KEYPASS_PROP);
            //TODO
            FileInputStream jksIS = new FileInputStream(keyStorePath);
            ks = loadJKSData(jksIS, keyAlias, keyPassword);
            jksIS.close();
        } else if (certFilePath != null && certKeyFilePath != null && certFilePath.exists()
                && certKeyFilePath.exists()) {
            System.out.println("Reading auth details from cert file and certkeyfile");
            FileInputStream certIS = new FileInputStream(certFilePath);
            FileInputStream keyIS = new FileInputStream(certKeyFilePath);
            keyAlias = "x509convert";
            //TODO
            keyPassword = rmProperties.getProperty(USER_KEYPASS_PROP);
            //TODO
            ks = loadX509Data(certIS, keyIS, keyAlias, keyPassword);
            certIS.close();
            keyIS.close();
        }

        if (ks == null)
            throw new Exception("Was unable to find either: " + keyStorePath.getCanonicalPath()
                    + " or the pair of: " + certFilePath.getCanonicalPath() + " and "
                    + certKeyFilePath.getCanonicalPath() + " as specified.");

        // check that the spelling of key alias is proper
        Enumeration<String> as = ks.aliases();
        while (as.hasMoreElements()) {
            String a = as.nextElement();
            if (keyAlias.toLowerCase().equals(a.toLowerCase())) {
                keyAlias = a;
                break;
            }
        }

        // alias has to exist and have a key and cert present
        if (!ks.containsAlias(keyAlias)) {
            throw new Exception("Alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getKey(keyAlias, keyPassword.toCharArray()) == null)
            throw new Exception(
                    "Key with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");

        if (ks.getCertificate(keyAlias) == null) {
            throw new Exception(
                    "Certificate with alias " + keyAlias + " does not exist in keystore " + keyStorePath + ".");
        }

        if (ks.getCertificate(keyAlias).getType().equals("X.509")) {
            X509Certificate x509Cert = (X509Certificate) ks.getCertificate(keyAlias);
            try {
                x509Cert.checkValidity();
            } catch (Exception e) {
                throw new Exception("Certificate with alias " + keyAlias + " is not yet valid or has expired.");
            }
        }

        // add the identity into it
        mkm.addPrivateKey(keyAlias, (PrivateKey) ks.getKey(keyAlias, keyPassword.toCharArray()),
                ks.getCertificate(keyAlias));

        // before we do SSL to this controller, set our identity
        mkm.setCurrentGuid(keyAlias);

        // register the protocol (Note: All xmlrpc clients must use XmlRpcCommonsTransportFactory
        // for this to work). See ContextualSSLProtocolSocketFactory.
        Protocol reghhttps = new Protocol("https", (ProtocolSocketFactory) regSslFact, 443);
        Protocol.registerProtocol("https", reghhttps);

        sslIdentitySet = true;
    } catch (Exception e) {
        e.printStackTrace();
        throw new Exception("Unable to load user private key and certificate from the keystore: " + e);
    }

    //System.out.println("Exiting setSSLIdentity");

}