Example usage for java.security Security addProvider

List of usage examples for java.security Security addProvider

Introduction

In this page you can find the example usage for java.security Security addProvider.

Prototype

public static int addProvider(Provider provider) 

Source Link

Document

Adds a provider to the next position available.

Usage

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java

@Test
public void testPublish() throws Exception {
    // STS//from   w  w w  . ja v a  2s  .c o m
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox publication
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] message = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(message);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(message);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);
    LOG.debug("payload: " + publicationClient.getPayload());
}

From source file:jp.pigumer.mqtt.Client.java

Optional<TrustManager[]> initTrustManagers() {
    return loadKeyStore().map(keyStore -> {
        try {//  w  w w .  j  a  v a 2  s  . c  o  m
            Security.addProvider(new BouncyCastleProvider());
            TrustManagerFactory tmf = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(keyStore);
            return tmf.getTrustManagers();
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "failed load", e);
            return null;
        }
    });
}

From source file:org.apache.synapse.transport.certificatevalidation.pathvalidation.CertificatePathValidator.java

/**
 * Certificate Path Validation process/*from  ww w. ja v a  2s  .  c  om*/
 *
 * @throws CertificateVerificationException
 *          if validation process fails.
 */
public void validatePath() throws CertificateVerificationException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    CollectionCertStoreParameters params = new CollectionCertStoreParameters(fullCertChain);
    try {
        CertStore store = CertStore.getInstance("Collection", params, "BC");

        // create certificate path
        CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

        CertPath certPath = fact.generateCertPath(certChain);
        TrustAnchor trustAnchor = new TrustAnchor(fullCertChain.get(fullCertChain.size() - 1), null);
        Set<TrustAnchor> trust = Collections.singleton(trustAnchor);

        // perform validation
        CertPathValidator validator = CertPathValidator.getInstance("PKIX", "BC");
        PKIXParameters param = new PKIXParameters(trust);

        param.addCertPathChecker(pathChecker);
        param.setRevocationEnabled(false);
        param.addCertStore(store);
        param.setDate(new Date());

        validator.validate(certPath, param);

        log.info("Certificate path validated");
    } catch (CertPathValidatorException e) {
        throw new CertificateVerificationException("Certificate Path Validation failed on certificate number "
                + e.getIndex() + ", details: " + e.getMessage(), e);
    } catch (Exception e) {
        throw new CertificateVerificationException("Certificate Path Validation failed", e);
    }
}

From source file:test.integ.be.e_contract.mycarenet.cxf.EHealthSTSClientTest.java

@Test
public void testClient() throws Exception {
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// www  . java2  s. c om
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element assertionElement = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertionElement);

    LOG.debug("assertion: " + toString(assertionElement));

    LOG.debug("not after: " + client.getNotAfter(assertionElement));
}

From source file:io.milton.grizzly.GrizzlyLoadBalancer.java

public boolean start(int httpPort, Integer sslPort) throws IOException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    ConfigurableApplicationContext ctx = initSpringApplicationContext();
    if (ctx == null) {
        log.warn("Failed to initialise spring");
        return false;
    }//w  w w . j  a  v  a  2  s  .  c o m

    complexAppExecutorService = GrizzlyExecutorService
            .createInstance(ThreadPoolConfig.defaultConfig().copy().setCorePoolSize(5).setMaxPoolSize(5));

    String host = getPropertyOrDefault("host", null);

    int port = getPropertyOrDefaultInt("port", 8080);

    int secureHttpPort = getPropertyOrDefaultInt(MiltonSNIService.SYS_SECURE_PORT,
            MiltonSNIService.SECURE_PORT);

    if (host == null) {
        httpServer = HttpServer.createSimpleServer(null, port);
    } else {
        httpServer = HttpServer.createSimpleServer(null, host, port);
    }

    { // Start the Kademi SNI SSL service
        MiltonSNICertificateStore store = null; // TODO: allow injection
        MiltonSNICertificateManager sniCerManager = new MiltonSNICertificateManager(store);
        SSLEngineConfigurator sniConfig = sniCerManager.createEngineConfigurator();
        this.kademiSNIService = new MiltonSNIService(secureHttpPort, sniConfig);

        this.kademiSNIService.startOn(httpServer);
    }

    httpServer.getServerConfiguration().addHttpHandler(new HttpHandler() {
        @Override
        public void service(final Request request, final Response response) throws Exception {
            log.trace("service");
            response.suspend();
            complexAppExecutorService.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        forwardToCluster(request, response);
                    } finally {
                        response.resume();
                    }

                }

            });
        }
    }, "/");

    httpServer.start();

    running = true;
    return true;
}

From source file:org.apache.gobblin.crypto.GPGFileEncryptor.java

/**
 * Taking in an input {@link OutputStream} and a passPhrase, return an {@link OutputStream} that can be used to output
 * encrypted output to the input {@link OutputStream}.
 * @param outputStream the output stream to hold the ciphertext {@link OutputStream}
 * @param passPhrase pass phrase/*  w w w.  j av  a 2  s .co m*/
 * @param cipher the symmetric cipher to use for encryption. If null or empty then a default cipher is used.
 * @return {@link OutputStream} to write content to for encryption
 * @throws IOException
 */
public OutputStream encryptFile(OutputStream outputStream, String passPhrase, String cipher)
        throws IOException {
    try {
        if (Security.getProvider(PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(
                new JcePGPDataEncryptorBuilder(symmetricKeyAlgorithmNameToTag(cipher))
                        .setSecureRandom(new SecureRandom()).setProvider(PROVIDER_NAME));
        cPk.addMethod(
                new JcePBEKeyEncryptionMethodGenerator(passPhrase.toCharArray()).setProvider(PROVIDER_NAME));

        OutputStream cOut = cPk.open(outputStream, new byte[BUFFER_SIZE]);

        PGPLiteralDataGenerator literalGen = new PGPLiteralDataGenerator();
        OutputStream _literalOut = literalGen.open(cOut, PGPLiteralDataGenerator.BINARY, PAYLOAD_NAME,
                new Date(), new byte[BUFFER_SIZE]);

        return new ClosingWrapperOutputStream(_literalOut, cOut, outputStream);
    } catch (PGPException e) {
        throw new IOException(e);
    }
}

From source file:edu.wisc.bnsemail.dao.SmtpBusinessEmailUpdateNotifier.java

@Override
public void afterPropertiesSet() throws Exception {
    if (this.keystore == null) {
        this.logger.warn("No S/MIME KeyStore configured. Email update notifications will NOT be signed");
    } else {/* w w w.j a  v  a  2  s.  c o m*/
        Security.addProvider(new BouncyCastleProvider());

        final KeyStore signingKeyStore = KeyStore.getInstance("JKS");

        final InputStream keyStoreStream = this.keystore.getInputStream();
        try {
            signingKeyStore.load(keyStoreStream, this.keystorePassword.toCharArray());
        } finally {
            IOUtils.closeQuietly(keyStoreStream);
        }

        final List<Certificate> certList = new ArrayList<Certificate>(1);
        for (final Enumeration<String> aliasesEnum = signingKeyStore.aliases(); aliasesEnum
                .hasMoreElements();) {
            final String alias = aliasesEnum.nextElement();
            final Certificate cert = signingKeyStore.getCertificate(alias);
            if (cert != null) {
                certList.add(cert);
            }
        }

        final PrivateKey signingKey = (PrivateKey) signingKeyStore.getKey(this.certificateAlias,
                this.keystorePassword.toCharArray());
        final X509Certificate signingCert = (X509Certificate) signingKeyStore
                .getCertificate(this.certificateAlias);

        // create a CertStore containing the certificates we want carried
        // in the signature
        final CertStore certsAndcrls = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(certList), "BC");

        // create the generator for creating an smime/signed message
        smimeSignedGenerator = new SMIMESignedGenerator();

        // add a signer to the generator - this specifies we are using SHA1 and
        // adding the smime attributes above to the signed attributes that
        // will be generated as part of the signature. The encryption algorithm
        // used is taken from the key - in this RSA with PKCS1Padding
        smimeSignedGenerator.addSigner(signingKey, signingCert, SMIMESignedGenerator.DIGEST_SHA1);

        // add our pool of certs and cerls (if any) to go with the signature
        smimeSignedGenerator.addCertificatesAndCRLs(certsAndcrls);
    }
}

From source file:org.apache.nifi.provenance.AESProvenanceEventEncryptor.java

/**
 * Initializes the encryptor with a {@link KeyProvider}.
 *
 * @param keyProvider the key provider which will be responsible for accessing keys
 * @throws KeyManagementException if there is an issue configuring the key provider
 *//*from  ww w. java2  s . c  o  m*/
@Override
public void initialize(KeyProvider keyProvider) throws KeyManagementException {
    this.keyProvider = keyProvider;

    if (this.aesKeyedCipherProvider == null) {
        this.aesKeyedCipherProvider = new AESKeyedCipherProvider();
    }

    if (Security.getProvider("BC") == null) {
        Security.addProvider(new BouncyCastleProvider());
    }
}

From source file:test.integ.be.fedict.hsm.client.HSMProxyClientTest.java

@Test
public void testGetAliases() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);/*from  w  w  w .ja  v  a2 s  . c o  m*/
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    HSMProxyClient client = new HSMProxyClient("http://localhost:8080/hsm-proxy-ws/dss", authnPrivateKey,
            authnCert);

    Set<String> aliases = client.getAliases();
    assertNotNull(aliases);
    LOG.debug("aliases: " + aliases);
    assertFalse(aliases.isEmpty());
}

From source file:org.proteomecommons.tranche.proxy.UploadThread.java

public void run() {
    try {//from   w  w w  .j  a va  2  s  .c o m
        ServerUtil.waitForStartup();

        // set the password of the user zip file
        uzf.setPassphrase(uzfPassphrase);

        // register the bouncy castle code
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
        aft = new AddFileTool(uzf.getCertificate(), uzf.getPrivateKey());

        // should it upload as a directory as a single file?
        aft.setExplodeBeforeUpload(uploadAsDirectory);

        // set the parameters
        aft.setTitle(title);
        aft.setDescription(description);
        aft.setUseRemoteReplication(useRemoteRep);
        aft.setSkipExistingChunk(skipExistingChunks);

        if (passphrase != null && !passphrase.equals("")) {
            aft.setPassphrase(passphrase);
        }

        if (servers != null && servers.size() > 0) {
            for (String server : servers) {
                aft.addServerURL(server);
            }
        }

        status = STATUS_UPLOADING;

        // there should only be one file - either a file or a directory
        hash = aft.addFile(uploadedFile);

        // register the upload with proteomecommons if desired
        if (register) {
            status = STATUS_REGISTERING;
            try {
                // flag for registered
                boolean registered = false;
                // try to register
                for (int registerAttempt = 0; registerAttempt < 3; registerAttempt++) {
                    // keep track of the status code
                    final int[] statusCode = new int[1];

                    // spawn registration in a thread so it can be timed out
                    Thread t = new Thread() {

                        public void run() {
                            try {
                                // if the passphrase is null, save it as ""
                                String p = passphrase;
                                if (p == null) {
                                    p = ""; // make a new client
                                }
                                HttpClient c = new HttpClient();

                                // make a post method
                                PostMethod pm = new PostMethod(
                                        "http://www.proteomecommons.org/dev/tranche/register.jsp");
                                NameValuePair b = new NameValuePair("hash", hash.toString());
                                NameValuePair a = new NameValuePair("passphrase", p);
                                // set the values
                                pm.setRequestBody(new NameValuePair[] { a, b });

                                // execute the method
                                statusCode[0] = c.executeMethod(pm);

                                // release the connection
                                pm.releaseConnection();
                            } catch (Exception e) {
                                // do nothing
                            }
                        }
                    };
                    t.start();

                    // wait for up to 45 seconds
                    t.join(45 * 1000);
                    // pitch an exception
                    if (t.isAlive() || statusCode[0] != 200) {
                        throw new Exception("Can't register upload on ProteomeCommons.org");
                    }
                    break;
                }
            } catch (Exception e) {
                // do nothing
            }
        }

        status = STATUS_COMPLETED;
    } catch (Exception e) {
        exception = e;
        status = STATUS_FAILED;
    }
}