Example usage for java.security KeyStore setKeyEntry

List of usage examples for java.security KeyStore setKeyEntry

Introduction

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

Prototype

public final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
        throws KeyStoreException 

Source Link

Document

Assigns the given key to the given alias, protecting it with the given password.

Usage

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

/**
 * Register to listen to HTTPS./*from ww w .  j  a v a  2s .c  om*/
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:org.apache.hadoop.gateway.services.security.impl.BaseKeystoreService.java

protected void addCredential(String alias, String value, KeyStore ks) {
    if (ks != null) {
        try {/*  w w w.j  ava2  s .c  o m*/
            final Key key = new SecretKeySpec(value.getBytes("UTF8"), "AES");
            ks.setKeyEntry(alias, key, masterService.getMasterSecret(), null);
        } catch (KeyStoreException e) {
            LOG.failedToAddCredential(e);
        } catch (IOException e) {
            LOG.failedToAddCredential(e);
        }
    }
}

From source file:org.jasig.portal.security.provider.saml.SSLSecurityImpl.java

private void setSSLClientCredentials(PrivateKey pk, Certificate cert) throws KeyStoreException,
        NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException {
    this.logger.info("Private key: [{}].", pk.toString());
    this.logger.info("Certificate: [{}].", cert.toString());
    KeyStore ks = KeyStore.getInstance("JKS", "SUN");
    ks.load(null, null);/*w w  w  . j a  va 2 s  .co  m*/
    Certificate[] certificates = new Certificate[1];
    certificates[0] = cert;
    String keystorePass = UUID.randomUUID().toString();
    ks.setKeyEntry("sp", pk, keystorePass.toCharArray(), certificates);
    this.keyStore = ks;
    this.keyStorePass = keystorePass;
}

From source file:com.evolveum.midpoint.init.ConfigurableProtectorFactory.java

public void init() {
    Configuration config = configuration.getConfiguration(PROTECTOR_CONFIGURATION);
    protectorConfig = new ProtectorConfiguration(config);

    //Extract file if not exists
    if (config.getString("midpoint.home") == null) {
        return;/*  w w  w  . j ava2s. c o m*/
    }

    File ks = new File(protectorConfig.getKeyStorePath());
    if (ks.exists()) {
        return;
    }

    //todo improve
    FileOutputStream fos = null;
    try {
        KeyStore keystore = KeyStore.getInstance("jceks");
        char[] password = "changeit".toCharArray();

        keystore.load(null, password);

        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);
        SecretKey secretKey = keyGen.generateKey();

        keystore.setKeyEntry("default", secretKey, "midpoint".toCharArray(), null);

        fos = new FileOutputStream(protectorConfig.getKeyStorePath());
        keystore.store(fos, password);
        fos.close();
    } catch (Exception ex) {
        throw new SystemException("Couldn't generate keystore, reason: " + ex.getMessage(), ex);
    } finally {
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java

public ProtocolStackLoopbackLoadStress(boolean nio, boolean ssl)
        throws IOException, NoSuchAlgorithmException, CertificateException, KeyStoreException,
        UnrecoverableKeyException, KeyManagementException, OperatorCreationException {
    KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
    gen.initialize(2048); // maximum supported by JVM with export restrictions
    keyPair = gen.generateKeyPair();//from   ww w.j av a  2s . c  om

    Date now = new Date();
    Date firstDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(10));
    Date lastDate = new Date(now.getTime() + TimeUnit.DAYS.toMillis(-10));

    SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(keyPair.getPublic().getEncoded());

    X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE);
    X500Name subject = nameBuilder.addRDN(BCStyle.CN, getClass().getSimpleName()).addRDN(BCStyle.C, "US")
            .build();

    X509v3CertificateBuilder certGen = new X509v3CertificateBuilder(subject, BigInteger.ONE, firstDate,
            lastDate, subject, subjectPublicKeyInfo);

    JcaX509ExtensionUtils instance = new JcaX509ExtensionUtils();

    certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
            instance.createSubjectKeyIdentifier(subjectPublicKeyInfo));

    ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(BOUNCY_CASTLE_PROVIDER)
            .build(keyPair.getPrivate());

    certificate = new JcaX509CertificateConverter().setProvider(BOUNCY_CASTLE_PROVIDER)
            .getCertificate(certGen.build(signer));

    char[] password = "password".toCharArray();

    KeyStore store = KeyStore.getInstance("jks");
    store.load(null, password);
    store.setKeyEntry("alias", keyPair.getPrivate(), password, new Certificate[] { certificate });

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(store, password);

    context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(),
            new TrustManager[] { new PublicKeyMatchingX509ExtendedTrustManager(keyPair.getPublic()) }, null);

    hub = IOHub.create(executorService);
    serverSocketChannel = ServerSocketChannel.open();
    acceptor = new Acceptor(serverSocketChannel, nio, ssl);
}

From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return//from w  ww . j  a v  a 2  s .co m
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Security.addProvider(new BouncyCastleProvider());
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifier(pubKey.getEncoded()));
        certGen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        KeyPurposeId[] eku = { KeyPurposeId.id_kp_serverAuth, KeyPurposeId.id_kp_clientAuth,
                KeyPurposeId.anyExtendedKeyUsage };
        certGen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, privKey, SslCertificateService.PASSPHRASE,
                new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:org.apache.ofbiz.base.util.KeyStoreUtil.java

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        Debug.logInfo("Single certificate; no chain", module);
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;//from www.  j a  v a  2 s .co m
    } else {
        Debug.logInfo("Certificate chain length : " + certCol.size(), module);
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is set to 'privateKey' and the private key password is
 * null.// w  w w.  j av  a2  s . c  o  m
 * 
 * @param alias
 *            the alias used for the key entry
 * @param privKey
 *            RSA private key
 * @param cert
 *            user certificate
 * @param cachain
 *            CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception
 *                if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O");
                    if (cafriendly == null) {
                        cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU");
                        if (cafriendly == null) {
                            cafriendly = "CA_unknown" + i;
                        } else {
                            cafriendly = cafriendly + i;
                        }
                    } else {
                        cafriendly = cafriendly + i;
                    }
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}

From source file:org.computerist.ssltools.zap.ZapSslCertificateUtils.java

/**
 * Creates a new Root CA certificate and returns private and public key as
 * {@link KeyStore}. The {@link KeyStore#getDefaultType()} is used.
 *
 * @return/*  w  ww  .  ja  v a2s.  c o m*/
 * @throws NoSuchAlgorithmException If no providers are found
 * for 'RSA' key pair generator
 * or 'SHA1PRNG' Secure random number generator
 * @throws IllegalStateException in case of errors during assembling {@link KeyStore}
 */
public static final KeyStore createRootCA() throws NoSuchAlgorithmException {
    final Date startDate = Calendar.getInstance().getTime();
    final Date expireDate = new Date(startDate.getTime() + (DEFAULT_VALID_DAYS * 24L * 60L * 60L * 1000L));

    final KeyPairGenerator g = KeyPairGenerator.getInstance("RSA");
    g.initialize(2048, SecureRandom.getInstance("SHA1PRNG"));
    final KeyPair keypair = g.genKeyPair();
    final PrivateKey privKey = keypair.getPrivate();
    final PublicKey pubKey = keypair.getPublic();
    Random rnd = new Random();

    // using the hash code of the user's name and home path, keeps anonymity
    // but also gives user a chance to distinguish between each other
    X500NameBuilder namebld = new X500NameBuilder(BCStyle.INSTANCE);
    namebld.addRDN(BCStyle.CN, "OWASP Zed Attack Proxy Root CA");
    namebld.addRDN(BCStyle.L, Integer.toHexString(System.getProperty("user.name").hashCode())
            + Integer.toHexString(System.getProperty("user.home").hashCode()));
    namebld.addRDN(BCStyle.O, "OWASP Root CA");
    namebld.addRDN(BCStyle.OU, "OWASP ZAP Root CA");
    namebld.addRDN(BCStyle.C, "xx");

    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(namebld.build(),
            BigInteger.valueOf(rnd.nextInt()), startDate, expireDate, namebld.build(), pubKey);

    KeyStore ks = null;
    try {
        certGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(pubKey));
        certGen.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(true));
        certGen.addExtension(X509Extension.keyUsage, false,
                new KeyUsage(KeyUsage.keyCertSign | KeyUsage.digitalSignature | KeyUsage.keyEncipherment
                        | KeyUsage.dataEncipherment | KeyUsage.cRLSign));

        Vector<DERObject> eku = new Vector<>(3, 1);
        eku.add(KeyPurposeId.id_kp_serverAuth);
        eku.add(KeyPurposeId.id_kp_clientAuth);
        eku.add(KeyPurposeId.anyExtendedKeyUsage);
        certGen.addExtension(X509Extension.extendedKeyUsage, false, new ExtendedKeyUsage(eku));

        final ContentSigner sigGen = new JcaContentSignerBuilder("SHA1WithRSAEncryption").setProvider("BC")
                .build(privKey);
        final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certGen.build(sigGen));

        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        ks.setKeyEntry(FixedSslCertificateService.ZAPROXY_JKS_ALIAS, privKey,
                FixedSslCertificateService.PASSPHRASE, new Certificate[] { cert });
    } catch (final Exception e) {
        throw new IllegalStateException("Errors during assembling root CA.", e);
    }
    return ks;
}

From source file:com.brienwheeler.apps.tomcat.TomcatBean.java

private void configureNetwork() throws Exception {
    if (port > 0) {
        tomcat.setPort(port);/* w w  w .  java2s.  co  m*/
    } else {
        tomcat.getService().removeConnector(tomcat.getConnector());
    }

    if (sslPort > 0) {
        StringBuffer randomPass = new StringBuffer();
        for (int i = 0; i < 10; i++)
            randomPass.append(characters.charAt((int) (characters.length() * Math.random())));
        String keystorePass = randomPass.toString();

        RSAPrivateKey privateKey = readKeyFile();
        log.info("successfully read SSL private key from " + sslKeyFile.getAbsolutePath());
        X509Certificate certificate = readCertFile();
        log.info("successfully read SSL certificate from " + sslCertFile.getAbsolutePath());

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);
        keyStore.setCertificateEntry("cert-alias", certificate);
        keyStore.setKeyEntry("key-alias", privateKey, keystorePass.toCharArray(),
                new Certificate[] { certificate });
        File keyStoreFile = new File("tcks");
        keyStore.store(new FileOutputStream(keyStoreFile), keystorePass.toCharArray());

        Connector sslConnector = new Connector();
        sslConnector.setPort(sslPort);
        sslConnector.setSecure(true);
        sslConnector.setScheme("https");
        sslConnector.setAttribute("keystoreFile", keyStoreFile.getAbsolutePath());
        sslConnector.setAttribute("keystorePass", keystorePass);
        sslConnector.setAttribute("clientAuth", "false");
        sslConnector.setAttribute("sslProtocol", "TLS");
        sslConnector.setAttribute("SSLEnabled", true);
        tomcat.getService().addConnector(sslConnector);
    }
}