Search in sources :

Example 11 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project cloudstack by apache.

the class ApiServer method start.

@Override
public boolean start() {
    Security.addProvider(new BouncyCastleProvider());
    // api port, null by default
    Integer apiPort = null;
    final SearchCriteria<ConfigurationVO> sc = configDao.createSearchCriteria();
    sc.addAnd("name", SearchCriteria.Op.EQ, Config.IntegrationAPIPort.key());
    final List<ConfigurationVO> values = configDao.search(sc, null);
    if ((values != null) && (values.size() > 0)) {
        final ConfigurationVO apiPortConfig = values.get(0);
        if (apiPortConfig.getValue() != null) {
            apiPort = Integer.parseInt(apiPortConfig.getValue());
        }
    }
    final Map<String, String> configs = configDao.getConfiguration();
    final String strSnapshotLimit = configs.get(Config.ConcurrentSnapshotsThresholdPerHost.key());
    if (strSnapshotLimit != null) {
        final Long snapshotLimit = NumbersUtil.parseLong(strSnapshotLimit, 1L);
        if (snapshotLimit.longValue() <= 0) {
            s_logger.debug("Global config parameter " + Config.ConcurrentSnapshotsThresholdPerHost.toString() + " is less or equal 0; defaulting to unlimited");
        } else {
            dispatcher.setCreateSnapshotQueueSizeLimit(snapshotLimit);
        }
    }
    final Set<Class<?>> cmdClasses = new HashSet<Class<?>>();
    for (final PluggableService pluggableService : pluggableServices) {
        cmdClasses.addAll(pluggableService.getCommands());
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Discovered plugin " + pluggableService.getClass().getSimpleName());
        }
    }
    for (final Class<?> cmdClass : cmdClasses) {
        final APICommand at = cmdClass.getAnnotation(APICommand.class);
        if (at == null) {
            throw new CloudRuntimeException(String.format("%s is claimed as a API command, but it doesn't have @APICommand annotation", cmdClass.getName()));
        }
        String apiName = at.name();
        List<Class<?>> apiCmdList = s_apiNameCmdClassMap.get(apiName);
        if (apiCmdList == null) {
            apiCmdList = new ArrayList<Class<?>>();
            s_apiNameCmdClassMap.put(apiName, apiCmdList);
        }
        apiCmdList.add(cmdClass);
    }
    setEncodeApiResponse(Boolean.valueOf(configDao.getValue(Config.EncodeApiResponse.key())));
    if (apiPort != null) {
        final ListenerThread listenerThread = new ListenerThread(this, apiPort);
        listenerThread.start();
    }
    return true;
}
Also used : PluggableService(com.cloud.utils.component.PluggableService) APICommand(org.apache.cloudstack.api.APICommand) ConfigurationVO(org.apache.cloudstack.framework.config.impl.ConfigurationVO) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) HashSet(java.util.HashSet)

Example 12 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project wildfly by wildfly.

the class BouncyCastleModuleTestCase method testBouncyCastleProviderIsUsableThroughJceApi.

@Test
public void testBouncyCastleProviderIsUsableThroughJceApi() throws Exception {
    BouncyCastleProvider bcProvider = null;
    try {
        bcProvider = new BouncyCastleProvider();
        useBouncyCastleProviderThroughJceApi(bcProvider);
    } catch (Exception e) {
        if (e instanceof SecurityException && e.getMessage().contains("JCE cannot authenticate the provider")) {
            String bcLocation = (bcProvider == null) ? "" : "(" + bcProvider.getClass().getResource("/") + ")";
            throw new Exception("Packaging with BouncyCastleProvider" + bcLocation + " is probably not properly signed for JCE usage, see server log for details.", e);
        } else {
            throw e;
        }
    }
}
Also used : BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) Test(org.junit.Test)

Example 13 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project wildfly by wildfly.

the class KerberosServerSetupTask method setup.

/**
     * Creates directory services, starts LDAP server and KDCServer
     *
     * @param managementClient
     * @param containerId
     * @throws Exception
     * @see org.jboss.as.arquillian.api.ServerSetupTask#setup(org.jboss.as.arquillian.container.ManagementClient,
     * java.lang.String)
     */
public void setup(ManagementClient managementClient, String containerId) throws Exception {
    try {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
            removeBouncyCastle = true;
        }
    } catch (SecurityException ex) {
        LOGGER.warn("Cannot register BouncyCastleProvider", ex);
    }
    final String hostname = Utils.getHost(managementClient);
    createLdap1(managementClient, hostname);
}
Also used : BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 14 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project oxTrust by GluuFederation.

the class UpdateTrustRelationshipAction method getCertForGeneratedSP.

/**
	 * If there is no certificate selected, or certificate is invalid -
	 * generates one.
	 * 
	 * @author �Oleksiy Tataryn�
	 * @return certificate for generated SP
	 * @throws CertificateEncodingException
	 */
public String getCertForGeneratedSP() {
    X509Certificate cert = null;
    try {
        cert = sslService.getPEMCertificate(certWrapper.getStream());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    if (cert == null) {
        facesMessages.add(FacesMessage.SEVERITY_INFO, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
        try {
            KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", "BC");
            keyPairGen.initialize(2048);
            KeyPair pair = keyPairGen.generateKeyPair();
            StringWriter keyWriter = new StringWriter();
            PEMWriter pemFormatWriter = new PEMWriter(keyWriter);
            pemFormatWriter.writeObject(pair.getPrivate());
            pemFormatWriter.close();
            String url = trustRelationship.getUrl().replaceFirst(".*//", "");
            X509v3CertificateBuilder v3CertGen = new JcaX509v3CertificateBuilder(new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), BigInteger.valueOf(new SecureRandom().nextInt()), new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30), new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)), new X500Name("CN=" + url + ", OU=None, O=None L=None, C=None"), pair.getPublic());
            cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(v3CertGen.build(new JcaContentSignerBuilder("MD5withRSA").setProvider("BC").build(pair.getPrivate())));
            org.apache.commons.codec.binary.Base64 encoder = new org.apache.commons.codec.binary.Base64(64);
            byte[] derCert = cert.getEncoded();
            String pemCertPre = new String(encoder.encode(derCert));
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_START_LINE);
            log.debug(pemCertPre);
            log.debug(Shibboleth3ConfService.PUBLIC_CERTIFICATE_END_LINE);
            saveCert(trustRelationship, pemCertPre);
            saveKey(trustRelationship, keyWriter.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    //			String certName = appConfiguration.getCertDir() + File.separator + StringHelper.removePunctuation(appConfiguration.getOrgInum())
    //					+ "-shib.crt";
    //			File certFile = new File(certName);
    //			if (certFile.exists()) {
    //				cert = SSLService.instance().getPEMCertificate(certName);
    //			}
    }
    String certificate = null;
    if (cert != null) {
        try {
            certificate = new String(Base64.encode(cert.getEncoded()));
            log.info("##### certificate = " + certificate);
        } catch (CertificateEncodingException e) {
            certificate = null;
            facesMessages.add(FacesMessage.SEVERITY_ERROR, "Failed to encode provided certificate. Please notify Gluu support about this.");
            log.error("Failed to encode certificate to DER", e);
        }
    } else {
        facesMessages.add(FacesMessage.SEVERITY_INFO, "Certificate were not provided, or was incorrect. Appliance will create a self-signed certificate.");
    }
    return certificate;
}
Also used : KeyPair(java.security.KeyPair) Base64(org.bouncycastle.util.encoders.Base64) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) SecureRandom(java.security.SecureRandom) PEMWriter(org.bouncycastle.openssl.PEMWriter) CertificateEncodingException(java.security.cert.CertificateEncodingException) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) X509Certificate(java.security.cert.X509Certificate) LdapMappingException(org.gluu.site.ldap.persistence.exception.LdapMappingException) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) Date(java.util.Date) StringWriter(java.io.StringWriter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) X509v3CertificateBuilder(org.bouncycastle.cert.X509v3CertificateBuilder) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) JcaX509v3CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 15 with BouncyCastleProvider

use of org.bouncycastle.jce.provider.BouncyCastleProvider in project tomee by apache.

the class SslTomEETest method test.

@Test
public void test() throws Exception {
    final File keystore = new File("target/keystore");
    {
        // generate keystore/trustore
        if (keystore.exists()) {
            Files.delete(keystore);
        }
        keystore.getParentFile().mkdirs();
        try (final FileOutputStream fos = new FileOutputStream(keystore)) {
            final KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
            keyGenerator.initialize(1024);
            final KeyPair pair = keyGenerator.generateKeyPair();
            final boolean addBc = Security.getProvider("BC") == null;
            if (addBc) {
                Security.addProvider(new BouncyCastleProvider());
            }
            try {
                final X509v1CertificateBuilder x509v1CertificateBuilder = new JcaX509v1CertificateBuilder(new X500Name("cn=serveralias"), BigInteger.valueOf(1), new Date(System.currentTimeMillis() - TimeUnit.DAYS.toMillis(1)), new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1)), new X500Name("cn=serveralias"), pair.getPublic());
                final X509CertificateHolder certHldr = x509v1CertificateBuilder.build(new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(pair.getPrivate()));
                final X509Certificate cert = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHldr);
                final KeyStore ks = KeyStore.getInstance("JKS");
                ks.load(null, "changeit".toCharArray());
                ks.setKeyEntry("serveralias", pair.getPrivate(), "changeit".toCharArray(), new Certificate[] { cert });
                ks.store(fos, "changeit".toCharArray());
            } finally {
                if (addBc) {
                    Security.removeProvider("BC");
                }
            }
        } catch (final Exception e) {
            Assert.fail(e.getMessage());
        }
    }
    final Configuration configuration = new Configuration();
    configuration.setSsl(true);
    configuration.setKeystoreFile(keystore.getAbsolutePath());
    configuration.setKeystorePass("changeit");
    configuration.setKeyAlias("serveralias");
    final Container container = new Container();
    container.setup(configuration);
    container.start();
    try {
        assertEquals(8443, ManagementFactory.getPlatformMBeanServer().getAttribute(new ObjectName("Tomcat:type=ProtocolHandler,port=8443"), "port"));
    } finally {
        container.stop();
    }
    // ensure it is not always started
    configuration.setSsl(false);
    container.setup(configuration);
    container.start();
    try {
        assertFalse(ManagementFactory.getPlatformMBeanServer().isRegistered(new ObjectName("Tomcat:type=ProtocolHandler,port=8443")));
    } finally {
        container.close();
    }
}
Also used : KeyPair(java.security.KeyPair) JcaContentSignerBuilder(org.bouncycastle.operator.jcajce.JcaContentSignerBuilder) KeyPairGenerator(java.security.KeyPairGenerator) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStore(java.security.KeyStore) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) Date(java.util.Date) X509Certificate(java.security.cert.X509Certificate) ObjectName(javax.management.ObjectName) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) FileOutputStream(java.io.FileOutputStream) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) X509v1CertificateBuilder(org.bouncycastle.cert.X509v1CertificateBuilder) JcaX509v1CertificateBuilder(org.bouncycastle.cert.jcajce.JcaX509v1CertificateBuilder) File(java.io.File) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) Test(org.junit.Test)

Aggregations

BouncyCastleProvider (org.bouncycastle.jce.provider.BouncyCastleProvider)34 IOException (java.io.IOException)12 KeyPair (java.security.KeyPair)9 X509Certificate (java.security.cert.X509Certificate)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 KeyPairGenerator (java.security.KeyPairGenerator)6 KeyStore (java.security.KeyStore)6 SecureRandom (java.security.SecureRandom)5 Date (java.util.Date)5 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)5 File (java.io.File)4 FileOutputStream (java.io.FileOutputStream)4 SecretKey (javax.crypto.SecretKey)4 JcaContentSignerBuilder (org.bouncycastle.operator.jcajce.JcaContentSignerBuilder)4 Before (org.junit.Before)4 KeyStoreException (java.security.KeyStoreException)3 NoSuchProviderException (java.security.NoSuchProviderException)3 CertificateException (java.security.cert.CertificateException)3 X500Name (org.bouncycastle.asn1.x500.X500Name)3 Test (org.junit.Test)3