Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:io.getlime.security.powerauth.app.server.service.behavior.ActivationServiceBehavior.java

/**
 * Init activation with given parameters
 *
 * @param applicationId             Application ID
 * @param userId                    User ID
 * @param maxFailedCount            Maximum failed attempt count (5)
 * @param activationExpireTimestamp Timestamp after which activation can no longer be completed
 * @param keyConversionUtilities    Utility class for key conversion
 * @return Response with activation initialization data
 * @throws GenericServiceException If invalid values are provided.
 * @throws InvalidKeySpecException If invalid key is provided
 * @throws InvalidKeyException     If invalid key is provided
 *///from   ww  w .ja  v  a2  s  .  co m
public InitActivationResponse initActivation(Long applicationId, String userId, Long maxFailedCount,
        Date activationExpireTimestamp, CryptoProviderUtil keyConversionUtilities)
        throws GenericServiceException, InvalidKeySpecException, InvalidKeyException {
    // Generate timestamp in advance
    Date timestamp = new Date();

    if (userId == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.NO_USER_ID);
    }

    if (applicationId == 0L) {
        throw localizationProvider.buildExceptionForCode(ServiceError.NO_APPLICATION_ID);
    }

    // Get number of max attempts from request or from constants, if not provided
    Long maxAttempt = maxFailedCount;
    if (maxAttempt == null) {
        maxAttempt = PowerAuthConfiguration.SIGNATURE_MAX_FAILED_ATTEMPTS;
    }

    // Get activation expiration date from request or from constants, if not provided
    Date timestampExpiration = activationExpireTimestamp;
    if (timestampExpiration == null) {
        timestampExpiration = new Date(
                timestamp.getTime() + PowerAuthConfiguration.ACTIVATION_VALIDITY_BEFORE_ACTIVE);
    }

    // Fetch the latest master private key
    MasterKeyPairEntity masterKeyPair = masterKeyPairRepository
            .findFirstByApplicationIdOrderByTimestampCreatedDesc(applicationId);
    if (masterKeyPair == null) {
        GenericServiceException ex = localizationProvider
                .buildExceptionForCode(ServiceError.NO_MASTER_SERVER_KEYPAIR);
        Logger.getLogger(PowerAuthServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        throw ex;
    }
    byte[] masterPrivateKeyBytes = BaseEncoding.base64().decode(masterKeyPair.getMasterKeyPrivateBase64());
    PrivateKey masterPrivateKey = keyConversionUtilities.convertBytesToPrivateKey(masterPrivateKeyBytes);
    if (masterPrivateKey == null) {
        GenericServiceException ex = localizationProvider
                .buildExceptionForCode(ServiceError.INCORRECT_MASTER_SERVER_KEYPAIR_PRIVATE);
        Logger.getLogger(PowerAuthServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
        throw ex;
    }

    // Generate new activation data, generate a unique activation ID
    String activationId = null;
    for (int i = 0; i < PowerAuthConfiguration.ACTIVATION_GENERATE_ACTIVATION_ID_ITERATIONS; i++) {
        String tmpActivationId = powerAuthServerActivation.generateActivationId();
        ActivationRecordEntity record = powerAuthRepository.findFirstByActivationId(tmpActivationId);
        if (record == null) {
            activationId = tmpActivationId;
            break;
        } // ... else this activation ID has a collision, reset it and try to find another one
    }
    if (activationId == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.UNABLE_TO_GENERATE_ACTIVATION_ID);
    }

    // Generate a unique short activation ID for created and OTP used states
    String activationIdShort = null;
    Set<io.getlime.security.powerauth.app.server.repository.model.ActivationStatus> states = ImmutableSet.of(
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED,
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.OTP_USED);
    for (int i = 0; i < PowerAuthConfiguration.ACTIVATION_GENERATE_ACTIVATION_SHORT_ID_ITERATIONS; i++) {
        String tmpActivationIdShort = powerAuthServerActivation.generateActivationIdShort();
        ActivationRecordEntity record = powerAuthRepository
                .findFirstByApplicationIdAndActivationIdShortAndActivationStatusInAndTimestampActivationExpireAfter(
                        applicationId, tmpActivationIdShort, states, timestamp);
        // this activation short ID has a collision, reset it and find
        // another one
        if (record == null) {
            activationIdShort = tmpActivationIdShort;
            break;
        }
    }
    if (activationIdShort == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.UNABLE_TO_GENERATE_SHORT_ACTIVATION_ID);
    }

    // Generate activation OTP
    String activationOtp = powerAuthServerActivation.generateActivationOTP();

    // Compute activation signature
    byte[] activationSignature = powerAuthServerActivation.generateActivationSignature(activationIdShort,
            activationOtp, masterPrivateKey);

    // Happens only when there is a crypto provider setup issue (SignatureException).
    if (activationSignature == null) {
        throw localizationProvider.buildExceptionForCode(ServiceError.UNABLE_TO_COMPUTE_SIGNATURE);
    }

    // Encode the signature
    String activationSignatureBase64 = BaseEncoding.base64().encode(activationSignature);

    // Generate server key pair
    KeyPair serverKeyPair = powerAuthServerActivation.generateServerKeyPair();
    byte[] serverKeyPrivateBytes = keyConversionUtilities.convertPrivateKeyToBytes(serverKeyPair.getPrivate());
    byte[] serverKeyPublicBytes = keyConversionUtilities.convertPublicKeyToBytes(serverKeyPair.getPublic());

    // Store the new activation
    ActivationRecordEntity activation = new ActivationRecordEntity();
    activation.setActivationId(activationId);
    activation.setActivationIdShort(activationIdShort);
    activation.setActivationName(null);
    activation.setActivationOTP(activationOtp);
    activation.setActivationStatus(
            io.getlime.security.powerauth.app.server.repository.model.ActivationStatus.CREATED);
    activation.setCounter(0L);
    activation.setDevicePublicKeyBase64(null);
    activation.setExtras(null);
    activation.setFailedAttempts(0L);
    activation.setApplication(masterKeyPair.getApplication());
    activation.setMasterKeyPair(masterKeyPair);
    activation.setMaxFailedAttempts(maxAttempt);
    activation.setServerPrivateKeyBase64(BaseEncoding.base64().encode(serverKeyPrivateBytes));
    activation.setServerPublicKeyBase64(BaseEncoding.base64().encode(serverKeyPublicBytes));
    activation.setTimestampActivationExpire(timestampExpiration);
    activation.setTimestampCreated(timestamp);
    activation.setTimestampLastUsed(timestamp);
    activation.setUserId(userId);
    powerAuthRepository.save(activation);
    callbackUrlBehavior.notifyCallbackListeners(activation.getApplication().getId(),
            activation.getActivationId());

    // Return the server response
    InitActivationResponse response = new InitActivationResponse();
    response.setActivationId(activationId);
    response.setActivationIdShort(activationIdShort);
    response.setUserId(userId);
    response.setActivationOTP(activationOtp);
    response.setActivationSignature(activationSignatureBase64);
    response.setApplicationId(activation.getApplication().getId());

    return response;
}

From source file:org.metaeffekt.dcc.commons.pki.CertificateManager.java

protected void persist(final KeyPair systemKeyPair, File privateKeyFile, File publicKeyFile)
        throws IOException {
    ensureParentDirExists(privateKeyFile);
    ensureParentDirExists(publicKeyFile);

    persistKey(privateKeyFile, systemKeyPair.getPrivate());
    persistKey(publicKeyFile, systemKeyPair.getPublic());
}

From source file:org.limewire.mojito.Context.java

/**
 * Returns the master public key//from  w w  w  .ja  v a2  s.co  m
 */
public PublicKey getPublicKey() {
    KeyPair keyPair = this.keyPair;
    if (keyPair != null) {
        return keyPair.getPublic();
    }
    return null;
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

@Override
public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    signer = (signingKey == null ? signer : subjectDn);
    signingKey = (signingKey == null ? keys.getPrivate() : signingKey);
    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);/*  w  w  w .j  a va 2 s .c o m*/
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keys.getPublic()));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(keys.getPublic());
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:org.nuxeo.ecm.platform.signature.core.pki.CertServiceImpl.java

protected CertificationRequest generateCSR(KeyPair keyPair, UserInfo userInfo) throws CertException {

    CertificationRequest csr;/*from   w  w  w. j av a  2 s.c o m*/

    GeneralNames subjectAltName = new GeneralNames(
            new GeneralName(GeneralName.rfc822Name, userInfo.getUserFields().get(CNField.Email)));

    Vector<DERObjectIdentifier> objectIdentifiers = new Vector<DERObjectIdentifier>();
    Vector<X509Extension> extensionValues = new Vector<X509Extension>();

    objectIdentifiers.add(X509Extensions.SubjectAlternativeName);
    extensionValues.add(new X509Extension(false, new DEROctetString(subjectAltName)));

    X509Extensions extensions = new X509Extensions(objectIdentifiers, extensionValues);

    Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
            new DERSet(extensions));
    try {
        csr = new PKCS10CertificationRequest(CERT_SIGNATURE_ALGORITHM, userInfo.getX500Principal(),
                keyPair.getPublic(), new DERSet(attribute), keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        throw new CertException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertException(e);
    } catch (NoSuchProviderException e) {
        throw new CertException(e);
    } catch (java.security.SignatureException e) {
        throw new CertException(e);
    } catch (Exception e) {
        throw new CertException(e);
    }
    return csr;
}

From source file:org.apache.hadoop.security.ssl.TestCRLValidator.java

@Test
public void testValidator() throws Exception {
    Path caTruststore = Paths.get(BASE_DIR, "ca.truststore.jks");
    Path crlPath = Paths.get(BASE_DIR, "crl.pem");

    // Generate CA keypair
    KeyPair cakeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm);
    X509Certificate caCert = KeyStoreTestUtil.generateCertificate("CN=rootCA", cakeyPair, 60,
            signatureAlgorithm);// w  w  w. ja v  a  2s. c om

    // Generate CA truststore
    KeyStoreTestUtil.createTrustStore(caTruststore.toString(), password, "rootca", caCert);

    // Generate client keypair
    KeyPair clientKeyPair = KeyStoreTestUtil.generateKeyPair(keyAlgorithm);
    X509Certificate clientCert = KeyStoreTestUtil.generateSignedCertificate("CN=client", clientKeyPair, 30,
            signatureAlgorithm, cakeyPair.getPrivate(), caCert);
    /*X509Certificate clientCert = KeyStoreTestUtil.generateCertificate("CN=client", clientKeyPair, 30,
        signatureAlgorithm);*/

    // Verify client certificate is signed by CA
    clientCert.verify(cakeyPair.getPublic());

    // Generate CRL
    X509CRL crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, null, null);
    writeCRLToFile(crl, crlPath);

    // Validate should pass
    conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER,
            FileBasedKeyStoresFactory.SSL_TRUSTSTORE_LOCATION_TPL_KEY), caTruststore.toString());
    conf.set(FileBasedKeyStoresFactory.resolvePropertyName(SSLFactory.Mode.SERVER,
            FileBasedKeyStoresFactory.SSL_TRUSTSTORE_PASSWORD_TPL_KEY), password);
    conf.set(CommonConfigurationKeys.HOPS_CRL_OUTPUT_FILE_KEY, crlPath.toString());

    CRLValidator validator = CRLValidatorFactory.getInstance().getValidator(CRLValidatorFactory.TYPE.TESTING,
            conf, conf);

    Certificate[] chain = new Certificate[2];
    chain[0] = clientCert;
    chain[1] = caCert;

    // At this point the validation should pass
    validator.validate(chain);

    // Revoke client certificate and regenerate CRL
    crl = KeyStoreTestUtil.generateCRL(caCert, cakeyPair.getPrivate(), signatureAlgorithm, crl,
            clientCert.getSerialNumber());
    TimeUnit.SECONDS.sleep(1);
    writeCRLToFile(crl, crlPath);

    TimeUnit.SECONDS.sleep(validator.getReloadInterval() * 2);

    // This time validation should fail
    rule.expect(CertificateException.class);
    validator.validate(chain);
}

From source file:mitm.common.security.certificate.GenerateSSLCertificate.java

private void generateSSLCertificate() throws Exception {
    X509CertificateBuilder certificateBuilder = securityFactory.createX509CertificateBuilder();

    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    SecureRandom randomSource = securityFactory.createSecureRandom();

    keyPairGenerator.initialize(1024, randomSource);

    KeyPair keyPair = keyPairGenerator.generateKeyPair();

    X500PrincipalBuilder subjectBuilder = new X500PrincipalBuilder();

    subjectBuilder.setCommonName("www.example.com");
    subjectBuilder.setCountryCode("NL");
    subjectBuilder.setLocality("Amsterdam");
    subjectBuilder.setState("NH");

    X500Principal subject = subjectBuilder.buildPrincipal();

    Set<ExtendedKeyUsageType> extendedKeyUsage = new TreeSet<ExtendedKeyUsageType>();

    extendedKeyUsage.add(ExtendedKeyUsageType.CLIENTAUTH);
    extendedKeyUsage.add(ExtendedKeyUsageType.EMAILPROTECTION);
    extendedKeyUsage.add(ExtendedKeyUsageType.SERVERAUTH);

    SerialNumberGenerator sng = new StandardSerialNumberGenerator();

    BigInteger serialNumber = sng.generate();

    Date now = new Date();

    certificateBuilder.setSubject(subject);
    certificateBuilder.setIssuer(subject);
    certificateBuilder.setExtendedKeyUsage(extendedKeyUsage, false);
    certificateBuilder.setNotBefore(DateUtils.addDays(now, -20));
    certificateBuilder.setNotAfter(DateUtils.addYears(now, 20));
    certificateBuilder.setPublicKey(keyPair.getPublic());
    certificateBuilder.setSerialNumber(serialNumber);
    certificateBuilder.setSignatureAlgorithm("SHA1WithRSAEncryption");

    X509Certificate certificate = certificateBuilder.generateCertificate(keyPair.getPrivate(), null);

    assertNotNull(certificate);//  w  w w.ja  v  a2 s . c o  m

    certificates.add(certificate);

    Certificate[] chain = new Certificate[] { certificate };

    keyStore.setKeyEntry("djigzo", keyPair.getPrivate(), null, chain);
}

From source file:org.apache.drill.exec.server.rest.WebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings
 * they will be used else a self-signed certificate is generated and used.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connectios.
 * @throws Exception//from w w  w .  j  av a  2 s .com
 */
private ServerConnector createHttpsConnector() throws Exception {
    logger.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH)
            && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) {
        logger.info("Using configured SSL settings for web server");
        sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
        sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));

        // TrustStore and TrustStore password are optional
        if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
            sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
            if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
                sslContextFactory
                        .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
            }
        }
    } else {
        logger.info("Using generated self-signed SSL settings for web server");
        final SecureRandom random = new SecureRandom();

        // Generate a private-public key pair
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024, random);
        final KeyPair keyPair = keyPairGenerator.generateKeyPair();

        final DateTime now = DateTime.now();

        // Create builder for certificate attributes
        final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
                .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
                .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)")
                .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress());

        final Date notBefore = now.minusMinutes(1).toDate();
        final Date notAfter = now.plusYears(5).toDate();
        final BigInteger serialNumber = new BigInteger(128, random);

        // Create a certificate valid for 5years from now.
        final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
                serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

        // Sign the certificate using the private key
        final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
                .build(keyPair.getPrivate());
        final X509Certificate certificate = new JcaX509CertificateConverter()
                .getCertificate(certificateBuilder.build(contentSigner));

        // Check the validity
        certificate.checkValidity(now.toDate());

        // Make sure the certificate is self-signed.
        certificate.verify(certificate.getPublicKey());

        // Generate a random password for keystore protection
        final String keyStorePasswd = RandomStringUtils.random(20);
        final KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);
        keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        sslContextFactory.setKeyStore(keyStore);
        sslContextFactory.setKeyStorePassword(keyStorePasswd);
    }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(embeddedJetty,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT));

    return sslConnector;
}

From source file:com.cws.esolutions.security.dao.keymgmt.impl.FileKeyManager.java

/**
 * @see com.cws.esolutions.security.dao.keymgmt.interfaces.KeyManager#createKeys(java.lang.String)
 *//*from   ww  w .  j a v  a  2 s  .c o  m*/
public synchronized boolean createKeys(final String guid) throws KeyManagementException {
    final String methodName = FileKeyManager.CNAME
            + "#createKeys(final String guid) throws KeyManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", guid);
    }

    boolean isComplete = false;
    OutputStream publicStream = null;
    OutputStream privateStream = null;

    final File keyDirectory = FileUtils.getFile(keyConfig.getKeyDirectory() + "/" + guid);

    try {
        if (!(keyDirectory.exists())) {
            if (!(keyDirectory.mkdirs())) {
                throw new KeyManagementException(
                        "Configured key directory does not exist and unable to create it");
            }
        }

        keyDirectory.setExecutable(true, true);

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(keyConfig.getKeyAlgorithm());
        keyGenerator.initialize(keyConfig.getKeySize(), random);
        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (keyPair != null) {
            File privateFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);
            File publicFile = FileUtils
                    .getFile(keyDirectory + "/" + guid + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

            if (!(privateFile.createNewFile())) {
                throw new IOException("Failed to store private key file");
            }

            if (!(publicFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            privateFile.setWritable(true, true);
            publicFile.setWritable(true, true);

            privateStream = new FileOutputStream(privateFile);
            publicStream = new FileOutputStream(publicFile);

            IOUtils.write(keyPair.getPrivate().getEncoded(), privateStream);
            IOUtils.write(keyPair.getPublic().getEncoded(), publicStream);

            // assume success, as we'll get an IOException if the write failed
            isComplete = true;
        } else {
            throw new KeyManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new KeyManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new KeyManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new KeyManagementException(nsax.getMessage(), nsax);
    } finally {
        if (publicStream != null) {
            IOUtils.closeQuietly(publicStream);
        }

        if (privateStream != null) {
            IOUtils.closeQuietly(privateStream);
        }
    }

    return isComplete;
}

From source file:org.apache.drill.yarn.appMaster.http.WebServer.java

/**
 * Create an HTTPS connector for given jetty server instance. If the admin has
 * specified keystore/truststore settings they will be used else a self-signed
 * certificate is generated and used./*w  w  w . j a  v a  2  s.co m*/
 * <p>
 * This is a shameless copy of
 * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}.
 * The two should be merged at some point. The primary issue is that the Drill
 * version is tightly coupled to Drillbit configuration.
 *
 * @return Initialized {@link ServerConnector} for HTTPS connections.
 * @throws Exception
 */

private ServerConnector createHttpsConnector(Config config) throws Exception {
    LOG.info("Setting up HTTPS connector for web server");

    final SslContextFactory sslContextFactory = new SslContextFactory();

    // if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) &&
    // !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)))
    // {
    // LOG.info("Using configured SSL settings for web server");
    // sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH));
    // sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD));
    //
    // // TrustStore and TrustStore password are optional
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) {
    // sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH));
    // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) {
    // sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD));
    // }
    // }
    // } else {
    LOG.info("Using generated self-signed SSL settings for web server");
    final SecureRandom random = new SecureRandom();

    // Generate a private-public key pair
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024, random);
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final DateTime now = DateTime.now();

    // Create builder for certificate attributes
    final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE)
            .addRDN(BCStyle.OU, "Apache Drill (auth-generated)")
            .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM");

    final Date notBefore = now.minusMinutes(1).toDate();
    final Date notAfter = now.plusYears(5).toDate();
    final BigInteger serialNumber = new BigInteger(128, random);

    // Create a certificate valid for 5years from now.
    final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes
            serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic());

    // Sign the certificate using the private key
    final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
            .build(keyPair.getPrivate());
    final X509Certificate certificate = new JcaX509CertificateConverter()
            .getCertificate(certificateBuilder.build(contentSigner));

    // Check the validity
    certificate.checkValidity(now.toDate());

    // Make sure the certificate is self-signed.
    certificate.verify(certificate.getPublicKey());

    // Generate a random password for keystore protection
    final String keyStorePasswd = RandomStringUtils.random(20);
    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(null, null);
    keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(),
            new java.security.cert.Certificate[] { certificate });

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePasswd);
    // }

    final HttpConfiguration httpsConfig = new HttpConfiguration();
    httpsConfig.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    final ServerConnector sslConnector = new ServerConnector(jettyServer,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(httpsConfig));
    sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT));

    return sslConnector;
}