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.fedict.commons.eid.client.JCATest.java

@Test
public void testAuthenticationSignatures() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from w  ww.j  a  v a2 s.  c  o  m*/
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA224withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD128withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD160withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD256withRSA", authnPrivateKey, authnCertificate.getPublicKey());
}

From source file:hudson.plugins.vcloud.VCloudDirector.java

private void fixTrustManager() {
    /* Install the all-trusting trust manager */
    Security.addProvider(new DummyTrustProvider());
    Security.setProperty("ssl.TrustManagerFactory.algorithm", "TrustAllCertificates");
}

From source file:org.collectionspace.chain.csp.persistence.file.TestGeneral.java

/**
 * Sets up and sends email message providing you have set up the email address to send to
 */// www .j a  va2 s .  c o m
@Test
public void testEmail() {
    Boolean doIreallyWantToSpam = false; // set to true when you have configured the email addresses
    /* please personalises these emails before sending - I don't want your spam. */
    String from = "admin@collectionspace.org";
    String[] recipients = { "" };

    String SMTP_HOST_NAME = "localhost";
    String SMTP_PORT = "25";
    String message = "Hi, Test Message Contents";
    String subject = "A test from collectionspace test suite";
    String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //REM - Replace.  This is pre-JDK 1.4 code, from the days when JSSE was a separate download.  Fix the imports so they refer to the classes in javax.net.ssl If you really want to get hold of a specific instance, you can use Security.getProvider(name). You'll find the appropriate names in the providers documentation. 
    boolean debug = true;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    //props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.auth", "false");
    props.put("mail.debug", "true");
    props.put("mail.smtp.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.port", SMTP_PORT);
    props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
    props.put("mail.smtp.socketFactory.fallback", "false");

    Session session = Session.getDefaultInstance(props);

    session.setDebug(debug);
    if (doIreallyWantToSpam) {

        Message msg = new MimeMessage(session);
        InternetAddress addressFrom;
        try {
            addressFrom = new InternetAddress(from);
            msg.setFrom(addressFrom);

            InternetAddress[] addressTo = new InternetAddress[recipients.length];
            for (int i = 0; i < recipients.length; i++) {
                addressTo[i] = new InternetAddress(recipients[i]);
            }
            msg.setRecipients(Message.RecipientType.TO, addressTo);

            // Setting the Subject and Content Type
            msg.setSubject(subject);
            msg.setContent(message, "text/plain");
            if (doIreallyWantToSpam) {
                Transport.send(msg);
                assertTrue(doIreallyWantToSpam);
            }
        } catch (AddressException e) {
            log.debug(e.getMessage());
            assertTrue(false);
        } catch (MessagingException e) {
            log.debug(e.getMessage());
            assertTrue(false);
        }
    }
    //assertTrue(doIreallyWantToSpam);
}

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

@Test
public void testGetMessageWithAttachments() throws Exception {
    // STS//ww  w .  j  av  a2s .c om
    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
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);
    eHealthBoxClient.getBoxInfo();

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        String request = "<ehbox:GetFullMessageRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\">"
                + "<Source>INBOX</Source>" + "<MessageId>" + messageId + "</MessageId>"
                + "</ehbox:GetFullMessageRequest>";
        String response = eHealthBoxClient.invoke(request);
        LOG.debug("response message: " + response);

        JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        AttachmentUnmarshaller attachmentUnmarshaller = new SOAPAttachmentUnmarshaller(
                eHealthBoxClient.getMessageAttachments());
        unmarshaller.setAttachmentUnmarshaller(attachmentUnmarshaller);
        JAXBElement<GetFullMessageResponseType> getFullMessageResponseElement = (JAXBElement<GetFullMessageResponseType>) unmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = getFullMessageResponseElement.getValue();
        DataHandler dataHandler = getFullMessageResponse.getMessage().getContentContext().getContent()
                .getDocument().getEncryptableBinaryContent();
        LOG.debug("has data handler: " + (null != dataHandler));
        byte[] data = IOUtils.toByteArray(dataHandler.getInputStream());
        LOG.debug("data: " + new String(data));
    }
}

From source file:org.xwiki.test.sso.LDAPStatus.java

public boolean open(String ldapHost, int ldapPort, String loginDN, String password, String pathToKeys,
        boolean ssl) throws UnsupportedEncodingException, LDAPException, ClassNotFoundException,
        InstantiationException, IllegalAccessException {

    int port = ldapPort;
    LDAPConnection connection = null;//from   ww w . j ava  2s. co  m
    if (port <= 0) {
        port = ssl ? LDAPConnection.DEFAULT_SSL_PORT : LDAPConnection.DEFAULT_PORT;
    }

    try {
        if (ssl) {

            // Dynamically set JSSE as a security provider
            Provider provider;

            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            String className = conf.getString("xwiki.authentication.ldap.ssl.secure_provider",
                    "com.sun.net.ssl.internal.ssl.Provider");

            provider = (java.security.Provider) cl.loadClass(className).newInstance();

            Security.addProvider(provider);

            if (pathToKeys != null && pathToKeys.length() > 0) {
                // Dynamically set the property that JSSE uses to identify
                // the keystore that holds trusted root certificates

                System.setProperty("javax.net.ssl.trustStore", pathToKeys);
                // obviously unnecessary: sun default pwd = "changeit"
                // System.setProperty("javax.net.ssl.trustStorePassword", sslpwd);
            }

            LDAPSocketFactory ssf = new LDAPJSSESecureSocketFactory();

            // Set the socket factory as the default for all future connections
            // LDAPConnection.setSocketFactory(ssf);
            // Note: the socket factory can also be passed in as a parameter
            // to the constructor to set it for this connection only.
            connection = new LDAPConnection(ssf);
        } else {
            connection = new LDAPConnection();
        }

        log.log(Level.FINER, "Connection to LDAP server [{0}:{1}]", new Object[] { ldapHost, port });

        // connect to the server
        connection.connect(ldapHost, port);

        // set referral following
        LDAPSearchConstraints constraints = new LDAPSearchConstraints(connection.getConstraints());
        constraints.setTimeLimit(conf.getInt("xwiki.authentication.ldap.timeout", 500));
        constraints.setMaxResults(conf.getInt("xwiki.authentication.ldap.maxresults", 10));
        connection.setConstraints(constraints);

        // bind
        log.log(Level.FINER, "Binding to LDAP server with credentials login=[{}]", new Object[] { loginDN });

        // authenticate to the server
        connection.bind(LDAPConnection.LDAP_V3, loginDN, password.getBytes("UTF8"));

    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (LDAPException e) {
        throw e;
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return true;
}

From source file:org.apache.cloudstack.utils.auth.SAMLUtils.java

public static KeyFactory getKeyFactory() {
    KeyFactory keyFactory = null;
    try {/*from w  ww .  ja  v  a 2 s .  c o  m*/
        Security.addProvider(new BouncyCastleProvider());
        keyFactory = KeyFactory.getInstance("RSA", "BC");
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        s_logger.error("Unable to create KeyFactory:" + e.getMessage());
    }
    return keyFactory;
}

From source file:org.kuali.rice.ksb.security.admin.service.impl.JavaSecurityManagementServiceImpl.java

protected Certificate generateCertificate(KeyPair keyPair, String alias) throws GeneralSecurityException {

    //test that Bouncy Castle provider is present and add it if it's not
    if (Security.getProvider(org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME) == null) {
        Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    }// w  w w . j  av  a  2s  .  c o  m
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    //      X509Name nameInfo = new X509Name(false,"CN=" + alias);
    certificateGenerator.setSignatureAlgorithm("MD5WithRSA");
    certificateGenerator.setSerialNumber(new java.math.BigInteger("1"));
    X509Principal nameInfo = new X509Principal("CN=" + alias);
    certificateGenerator.setIssuerDN(nameInfo);
    certificateGenerator.setSubjectDN(nameInfo); // note: same as issuer for self signed
    certificateGenerator.setNotBefore(new Date());
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, CLIENT_CERT_EXPIRATION_DAYS);
    certificateGenerator.setNotAfter(c.getTime());
    certificateGenerator.setPublicKey(keyPair.getPublic());
    return certificateGenerator.generate(keyPair.getPrivate(),
            org.bouncycastle.jce.provider.BouncyCastleProvider.PROVIDER_NAME);
}

From source file:org.apache.nifi.properties.NiFiPropertiesLoader.java

/**
 * Returns an instance of {@link NiFiProperties} loaded from the provided
 * {@link File}. If any properties are protected, will attempt to use the
 * appropriate {@link SensitivePropertyProvider} to unprotect them
 * transparently.//from  w ww.j a  va2 s .co m
 *
 * @param file the File containing the serialized properties
 * @return the NiFiProperties instance
 */
public NiFiProperties load(File file) {
    ProtectedNiFiProperties protectedNiFiProperties = readProtectedPropertiesFromDisk(file);
    if (protectedNiFiProperties.hasProtectedKeys()) {
        Security.addProvider(new BouncyCastleProvider());
        protectedNiFiProperties.addSensitivePropertyProvider(getSensitivePropertyProvider());
    }

    return protectedNiFiProperties.getUnprotectedProperties();
}

From source file:com.indivica.olis.Driver.java

public static String signData2(String data) {
    X509Certificate cert = null;/*from www . j  a  v a 2s. com*/
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = OscarProperties.getInstance().getProperty("olis_ssl_keystore_password", "changeit");
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("JKS");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        //Enumeration e = keystore.aliases();
        String name = "olis";

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());

        FileInputStream is = new FileInputStream(
                OscarProperties.getInstance().getProperty("olis_returned_cert"));
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(is);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:eu.europa.ejusticeportal.dss.controller.signature.PdfUtils.java

/**
 * Signs the PDF using the given token.// ww w  . j a v  a 2 s .c  o  m
 * 
 * @param bytes the PDF to sign
 * @param token the token to sign with
 * @return the sealed PDF
 * @throws KeyStoreException
 * @throws IOException
 * @throws NoSuchAlgorithmException
 */
public static byte[] sealPdf(final byte[] bytes, final SignatureTokenConnection token)
        throws KeyStoreException, IOException, NoSuchAlgorithmException {
    InputStream is = null;
    try {
        Security.addProvider(new BouncyCastleProvider());
        CommonCertificateVerifier certificateVerifier = new CommonCertificateVerifier();
        final PAdESService service = new PAdESService(certificateVerifier) {
            // TODO fix this
            @Override
            protected void assertSigningDateInCertificateValidityRange(
                    eu.europa.ec.markt.dss.parameter.SignatureParameters parameters) {
                // TODO Auto-generated method stub
                // super.assertSigningDateInCertificateValidityRange(parameters);
            }
        };
        final DSSPrivateKeyEntry key = token.getKeys().get(0);
        final DigestAlgorithm digestAlgorithm = DigestAlgorithm.SHA512;

        final SignatureParameters parameters = new SignatureParameters();
        parameters.setPrivateKeyEntry(key);// Must be set before the certificate. Otherwise -->
                                           // UnsupportOperationException.
        parameters.setSigningCertificate(key.getCertificate());
        parameters.setCertificateChain(key.getCertificateChain());
        parameters.setSignatureLevel(SignatureLevel.PAdES_BASELINE_B);
        parameters.setSignaturePackaging(SignaturePackaging.ENVELOPED);
        parameters.bLevel().setSigningDate(new Date());
        parameters.setDigestAlgorithm(digestAlgorithm);
        parameters.setSigningToken(token);
        final DSSDocument document = new InMemoryDocument(bytes);
        final DSSDocument doc = service.signDocument(document, parameters);
        is = doc.openStream();
        return IOUtils.toByteArray(is);
    } finally {
        IOUtils.closeQuietly(is);
    }
}