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:org.roda.common.certification.ODFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String ks, String alias, String password,
        String fileFormat) throws Exception {

    Security.addProvider(new BouncyCastleProvider());
    Path output = Files.createTempFile("odfsigned", "." + fileFormat);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream storeStream = new FileInputStream(ks);
    keystore.load(storeStream, password.toCharArray());
    X509Certificate certificate = (X509Certificate) keystore.getCertificate(keystore.aliases().nextElement());
    Key key = keystore.getKey(alias, password.toCharArray());
    IOUtils.closeQuietly(storeStream);/*ww  w.  j  a  v  a 2 s.  c  om*/

    ByteArrayInputStream bais = createSignature(input.toString(), certificate, key);
    File file = output.toFile();
    if (file != null) {
        byte[] buffer = new byte[2048];
        int length = 0;
        FileOutputStream fos = new FileOutputStream(file);
        while ((length = bais.read(buffer)) >= 0) {
            fos.write(buffer, 0, length);
        }
        IOUtils.closeQuietly(fos);
    }

    return output;
}

From source file:org.wso2.carbon.certificate.mgt.core.impl.CertificateGenerator.java

public X509Certificate generateX509Certificate() throws KeystoreException {

    CommonUtil commonUtil = new CommonUtil();
    Date validityBeginDate = commonUtil.getValidityStartDate();
    Date validityEndDate = commonUtil.getValidityEndDate();

    Security.addProvider(new BouncyCastleProvider());

    try {//from w  w w  .j a va  2  s  .c o m
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(CertificateManagementConstants.RSA,
                CertificateManagementConstants.PROVIDER);
        keyPairGenerator.initialize(CertificateManagementConstants.RSA_KEY_LENGTH, new SecureRandom());
        KeyPair pair = keyPairGenerator.generateKeyPair();
        X500Principal principal = new X500Principal(CertificateManagementConstants.DEFAULT_PRINCIPAL);

        X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(principal,
                CommonUtil.generateSerialNumber(), validityBeginDate, validityEndDate, principal,
                pair.getPublic());
        ContentSigner contentSigner = new JcaContentSignerBuilder(CertificateManagementConstants.SHA256_RSA)
                .setProvider(CertificateManagementConstants.PROVIDER).build(pair.getPrivate());
        X509Certificate certificate = new JcaX509CertificateConverter()
                .setProvider(CertificateManagementConstants.PROVIDER)
                .getCertificate(certificateBuilder.build(contentSigner));

        // cert.checkValidity();

        certificate.verify(certificate.getPublicKey());

        List<org.wso2.carbon.certificate.mgt.core.bean.Certificate> certificates = new ArrayList<>();
        org.wso2.carbon.certificate.mgt.core.bean.Certificate certificateToStore = new org.wso2.carbon.certificate.mgt.core.bean.Certificate();
        certificateToStore.setTenantId(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId());
        certificateToStore.setCertificate(certificate);
        certificates.add(certificateToStore);
        saveCertInKeyStore(certificates);

        return certificate;
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "No such algorithm found when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (NoSuchProviderException e) {
        String errorMsg = "No such provider found when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (OperatorCreationException e) {
        String errorMsg = "Issue in operator creation when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateExpiredException e) {
        String errorMsg = "Certificate expired after generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateNotYetValidException e) {
        String errorMsg = "Certificate not yet valid when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Certificate issue occurred when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (InvalidKeyException e) {
        String errorMsg = "Invalid key used when generating certificate";
        throw new KeystoreException(errorMsg, e);
    } catch (SignatureException e) {
        String errorMsg = "Signature related issue occurred when generating certificate";
        throw new KeystoreException(errorMsg, e);
    }
}

From source file:it.eng.spagobi.tools.scheduler.dispatcher.DistributionListDocumentDispatchChannel.java

public boolean dispatch(BIObject document, byte[] executionOutput) {

    String contentType;//from  ww w .  j av a2  s  .  co  m
    String fileExtension;
    String nameSuffix;
    JobExecutionContext jobExecutionContext;

    logger.debug("IN");

    try {

        contentType = dispatchContext.getContentType();
        fileExtension = dispatchContext.getFileExtension();
        nameSuffix = dispatchContext.getNameSuffix();
        jobExecutionContext = dispatchContext.getJobExecutionContext();

        //Custom Trusted Store Certificate Options
        String trustedStorePath = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.file");
        String trustedStorePassword = SingletonConfig.getInstance()
                .getConfigValue("MAIL.PROFILES.trustedStore.password");

        String smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost");
        String smtpport = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport");
        String smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL");
        logger.debug(smtphost + " " + smtpport + " use SSL: " + smtpssl);

        if ((smtphost == null) || smtphost.trim().equals(""))
            throw new Exception("Smtp host not configured");
        String from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from");
        if ((from == null) || from.trim().equals(""))
            from = "spagobi.scheduler@eng.it";

        int smptPort = 25;

        if ((smtpport == null) || smtpport.trim().equals("")) {
            throw new Exception("Smtp host not configured");
        } else {
            smptPort = Integer.parseInt(smtpport);
        }

        String user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user");
        String pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password");

        /*
        if( (user==null) || user.trim().equals(""))
           throw new Exception("Smtp user not configured");
                
        if( (pass==null) || pass.trim().equals(""))
           throw new Exception("Smtp password not configured");
        */

        String mailTos = "";
        List dlIds = dispatchContext.getDlIds();
        Iterator it = dlIds.iterator();
        while (it.hasNext()) {

            Integer dlId = (Integer) it.next();
            DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);

            List emails = new ArrayList();
            emails = dl.getEmails();
            Iterator j = emails.iterator();
            while (j.hasNext()) {
                Email e = (Email) j.next();
                String email = e.getEmail();
                String userTemp = e.getUserId();
                IEngUserProfile userProfile = GeneralUtilities.createNewUserProfile(userTemp);
                if (ObjectsAccessVerifier.canSee(document, userProfile)) {
                    if (j.hasNext()) {
                        mailTos = mailTos + email + ",";
                    } else {
                        mailTos = mailTos + email;
                    }
                }

            }
        }

        if ((mailTos == null) || mailTos.trim().equals("")) {
            throw new Exception("No recipient address found");
        }

        String[] recipients = mailTos.split(",");
        //Set the host smtp address
        Properties props = new Properties();
        props.put("mail.smtp.host", smtphost);
        props.put("mail.smtp.port", Integer.toString(smptPort));

        Session session = null;

        if (StringUtilities.isEmpty(user) || StringUtilities.isEmpty(pass)) {
            props.put("mail.smtp.auth", "false");
            session = Session.getInstance(props);
            logger.debug("Connecting to mail server without authentication");
        } else {
            props.put("mail.smtp.auth", "true");
            Authenticator auth = new SMTPAuthenticator(user, pass);
            //SSL Connection
            if (smtpssl.equals("true")) {
                Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
                //props.put("mail.smtp.debug", "true");          
                props.put("mail.smtps.auth", "true");
                props.put("mail.smtps.socketFactory.port", Integer.toString(smptPort));
                if ((!StringUtilities.isEmpty(trustedStorePath))) {
                    /* Dynamic configuration of trustedstore for CA
                     * Using Custom SSLSocketFactory to inject certificates directly from specified files
                     */
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY);

                } else {
                    //System.setProperty("java.security.debug","certpath");
                    //System.setProperty("javax.net.debug","ssl ");
                    props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY);
                }
                props.put("mail.smtp.socketFactory.fallback", "false");
            }
            session = Session.getInstance(props, auth);
            logger.debug("Connecting to mail server with authentication");
        }

        // create a message
        Message msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress 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
        IMessageBuilder msgBuilder = MessageBuilderFactory.getMessageBuilder();
        String subject = document.getName() + nameSuffix;
        msg.setSubject(subject);
        // create and fill the first message part
        //MimeBodyPart mbp1 = new MimeBodyPart();
        //mbp1.setText(mailTxt);
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
        SchedulerDataSource sds = new SchedulerDataSource(executionOutput, contentType,
                document.getName() + nameSuffix + fileExtension);
        mbp2.setDataHandler(new DataHandler(sds));
        mbp2.setFileName(sds.getName());
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        //mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send message
        if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) {
            //USE SSL Transport comunication with SMTPS
            Transport transport = session.getTransport("smtps");
            transport.connect(smtphost, smptPort, user, pass);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } else {
            //Use normal SMTP
            Transport.send(msg);
        }

        if (jobExecutionContext.getNextFireTime() == null) {
            String triggername = jobExecutionContext.getTrigger().getName();
            dlIds = dispatchContext.getDlIds();
            it = dlIds.iterator();
            while (it.hasNext()) {
                Integer dlId = (Integer) it.next();
                DistributionList dl = DAOFactory.getDistributionListDAO().loadDistributionListById(dlId);
                DAOFactory.getDistributionListDAO().eraseDistributionListObjects(dl,
                        (document.getId()).intValue(), triggername);
            }
        }
    } catch (Exception e) {
        logger.error("Error while sending schedule result mail", e);
        return false;
    } finally {
        logger.debug("OUT");
    }

    return true;
}

From source file:test.unit.be.fedict.eid.applet.service.AppletServiceServletTest.java

@Before
public void setUp() throws Exception {
    this.servletTester = new ServletTester();
    this.servletTester.addServlet(AppletServiceServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);
    this.servletTester.getContext().getServer().addConnector(sslSocketConnector);
    this.sslLocation = "https://localhost:" + sslPort + "/";

    this.servletTester.start();
    this.location = this.servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);
}

From source file:test.integ.be.e_contract.mycarenet.genins.GenericInsurabilityClientTest.java

@Test
public void testInvoke() 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);//from  www.  j a  va  2 s .c o  m
    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:ehealth:1.0:doctor:nihii11"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:doctor:boolean"));

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

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // String location =
    // "https://services-int.ehealth.fgov.be/GenericInsurability/v1";
    String location = "https://services-acpt.ehealth.fgov.be/GenericInsurability/v1";
    GenericInsurabilityClient genInsClient = new GenericInsurabilityClient(location);
    genInsClient.setCredentials(eHealthPrivateKey, assertionString);

    ObjectFactory objectFactory = new ObjectFactory();
    GetInsurabilityAsXmlOrFlatRequestType body = objectFactory.createGetInsurabilityAsXmlOrFlatRequestType();

    be.e_contract.mycarenet.genins.jaxb.core.ObjectFactory coreObjectFactory = new be.e_contract.mycarenet.genins.jaxb.core.ObjectFactory();
    CommonInputType commonInput = coreObjectFactory.createCommonInputType();
    body.setCommonInput(commonInput);

    RequestType request = coreObjectFactory.createRequestType();
    request.setIsTest(true);
    commonInput.setRequest(request);

    OriginType origin = coreObjectFactory.createOriginType();
    commonInput.setOrigin(origin);
    PackageType packageObject = coreObjectFactory.createPackageType();
    origin.setPackage(packageObject);
    LicenseType license = coreObjectFactory.createLicenseType();
    packageObject.setLicense(license);
    PackageLicenseKey packageLicenseKey = this.config.getPackageLicenseKey();
    license.setUsername(packageLicenseKey.getUsername());
    license.setPassword(packageLicenseKey.getPassword());

    Element namespaceElement = assertion.getOwnerDocument().createElement("ns");
    namespaceElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml",
            "urn:oasis:names:tc:SAML:1.0:assertion");
    Node nihiiNode = XPathAPI.selectSingleNode(assertion,
            "saml:AttributeStatement/saml:Attribute[@AttributeName='urn:be:fgov:person:ssin:ehealth:1.0:doctor:nihii11']/saml:AttributeValue/text()",
            namespaceElement);
    String myNihii = nihiiNode.getTextContent();
    LOG.debug("NIHII: " + myNihii);
    Node ssinNode = XPathAPI.selectSingleNode(assertion,
            "saml:AttributeStatement/saml:Attribute[@AttributeName='urn:be:fgov:person:ssin']/saml:AttributeValue/text()",
            namespaceElement);
    String mySsin = ssinNode.getTextContent();

    CareProviderType careProvider = coreObjectFactory.createCareProviderType();
    origin.setCareProvider(careProvider);
    NihiiType nihii = coreObjectFactory.createNihiiType();
    careProvider.setNihii(nihii);
    nihii.setQuality("doctor");
    ValueRefString nihiiValue = coreObjectFactory.createValueRefString();
    nihii.setValue(nihiiValue);
    nihiiValue.setValue(myNihii);
    IdType physicalPerson = coreObjectFactory.createIdType();
    careProvider.setPhysicalPerson(physicalPerson);
    ValueRefString ssinValue = coreObjectFactory.createValueRefString();
    physicalPerson.setSsin(ssinValue);
    ssinValue.setValue(mySsin);

    commonInput.setInputReference("PRIG1234567890");
    RecordCommonInputType recordCommonInput = coreObjectFactory.createRecordCommonInputType();
    body.setRecordCommonInput(recordCommonInput);
    recordCommonInput.setInputReference(new BigDecimal("1234567890123"));

    SingleInsurabilityRequestType singleInsurabilityRequest = coreObjectFactory
            .createSingleInsurabilityRequestType();
    body.setRequest(singleInsurabilityRequest);
    CareReceiverIdType careReceiverId = coreObjectFactory.createCareReceiverIdType();
    singleInsurabilityRequest.setCareReceiverId(careReceiverId);
    careReceiverId.setInss(mySsin);
    InsurabilityRequestDetailType insurabilityRequestDetail = coreObjectFactory
            .createInsurabilityRequestDetailType();
    singleInsurabilityRequest.setInsurabilityRequestDetail(insurabilityRequestDetail);
    InsurabilityRequestTypeType insurabilityRequestType = InsurabilityRequestTypeType.INFORMATION;
    insurabilityRequestDetail.setInsurabilityRequestType(insurabilityRequestType);
    PeriodType period = coreObjectFactory.createPeriodType();
    insurabilityRequestDetail.setPeriod(period);
    DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
    GregorianCalendar periodStartCal = new GregorianCalendar();
    DateTime periodStartDateTime = new DateTime();
    periodStartCal.setTime(periodStartDateTime.toDate());
    XMLGregorianCalendar periodStart = datatypeFactory.newXMLGregorianCalendar(periodStartCal);
    period.setPeriodStart(periodStart);
    DateTime periodEndDateTime = periodStartDateTime;
    GregorianCalendar periodEndCal = new GregorianCalendar();
    periodEndCal.setTime(periodEndDateTime.toDate());
    XMLGregorianCalendar periodEnd = datatypeFactory.newXMLGregorianCalendar(periodEndCal);
    period.setPeriodEnd(periodEnd);
    insurabilityRequestDetail.setInsurabilityContactType(InsurabilityContactTypeType.HOSPITALIZED_FOR_DAY);

    genInsClient.getInsurability(body);
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyStore generateKeyStore() throws CryptoException {
    try {/*from www  .j  av  a2s .  c  o m*/
        logger.debug("Generating a new key store.");

        /* Add BC to the jdk security manager to be able to use it as a provider */
        Security.addProvider(new BouncyCastleProvider());

        /* Create and init an empty key store */
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null, null);

        /*
         * Populate all new key stores with the key data of the local resolver, generally this is for metadata
         * purposes to ensure that all systems in the authentication network can correctly validate the signed
         * metadata document
         */
        X509Certificate localCertificate = (X509Certificate) localResolver.getLocalCertificate();
        Calendar before = new GregorianCalendar();
        Calendar expiry = new GregorianCalendar();
        before.setTime(localCertificate.getNotBefore());
        expiry.setTime(localCertificate.getNotAfter());

        addPublicKey(keyStore,
                new KeyPair(this.localResolver.getLocalPublicKey(), this.localResolver.getLocalPrivateKey()),
                this.localResolver.getLocalKeyAlias(), this.certIssuerDN, before, expiry);

        return keyStore;
    } catch (KeyStoreException e) {
        this.logger.error("KeyStoreException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        this.logger.error("NoSuchAlgorithmException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (CertificateException e) {
        this.logger.error("CertificateException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    } catch (IOException e) {
        this.logger.error("IOException thrown, " + e.getLocalizedMessage());
        this.logger.debug(e.toString());
        throw new CryptoException(e.getLocalizedMessage(), e);
    }
}

From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java

public static Path runDigitalSignatureSign(Path input, String ks, String alias, String password,
        String fileFormat) throws IOException, GeneralSecurityException, DocumentException {

    Security.addProvider(new BouncyCastleProvider());
    Path output = Files.createTempFile("odfsigned", "." + fileFormat);

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

    try (InputStream storeStream = new FileInputStream(ks)) {
        keystore.load(storeStream, password.toCharArray());

        X509Certificate certificate = (X509Certificate) keystore
                .getCertificate(keystore.aliases().nextElement());
        Key key = keystore.getKey(alias, password.toCharArray());

        try (ByteArrayInputStream bais = createSignature(input.toString(), certificate, key)) {
            File file = output.toFile();
            if (file != null && bais != null) {
                byte[] buffer = new byte[2048];
                int length = 0;
                try (FileOutputStream fos = new FileOutputStream(file)) {
                    while ((length = bais.read(buffer)) >= 0) {
                        fos.write(buffer, 0, length);
                    }//from   w  w w .  j ava  2  s. c o  m
                }
            }
        }
    }

    return output;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testRRNCertificate() throws Exception {
    // setup/*  w  w  w.  j av a  2s  . c o  m*/
    Security.addProvider(new BeIDProvider());
    final KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);

    // operate
    assertTrue(keyStore.containsAlias("RRN"));
    Entry entry = keyStore.getEntry("RRN", null);
    assertNotNull(entry);
    assertTrue(entry instanceof TrustedCertificateEntry);
    TrustedCertificateEntry trustedCertificateEntry = (TrustedCertificateEntry) entry;
    assertNotNull(trustedCertificateEntry.getTrustedCertificate());
    assertTrue(((X509Certificate) trustedCertificateEntry.getTrustedCertificate()).getSubjectX500Principal()
            .toString().contains("RRN"));
    assertNotNull(keyStore.getCertificate("RRN"));
    Certificate[] certificateChain = keyStore.getCertificateChain("RRN");
    assertNotNull(certificateChain);
    assertEquals(2, certificateChain.length);
    LOG.debug("RRN subject: " + ((X509Certificate) certificateChain[0]).getSubjectX500Principal());
    LOG.debug("RRN issuer: " + ((X509Certificate) certificateChain[0]).getIssuerX500Principal());
    LOG.debug("root subject: " + ((X509Certificate) certificateChain[1]).getSubjectX500Principal());
    LOG.debug("root issuer: " + ((X509Certificate) certificateChain[1]).getIssuerX500Principal());
}

From source file:net.cbtltd.rest.yandex.A_Handler.java

/**
 * Gets the connection to the nextpax server and executes the specified request.
 * /*from w ww  .  j  a  va  2s.c  om*/
 * @param url the connection URL.
 * @param rq the request object.
 * @return the XML string returned by the message.
 * @throws Throwable the exception thrown by the operation.
 */
private static final String getConnection(String rq) throws Throwable {
    String xmlString = "";
    CustomHttpConnection connection = new CustomHttpConnection();

    LOG.debug("NEXTPAX is using: " + RazorConfig.getNextPaxRequestURL());
    BASE64Encoder enc = new sun.misc.BASE64Encoder();
    Security.addProvider(new BouncyCastleProvider());
    String userpassword = "bookingnet" + ":" + "BAD5PqtE";
    String encodedAuthorization = enc.encode(userpassword.getBytes());
    xmlString = connection.createPostRequest(RazorConfig.getNextPaxRequestURL(), encodedAuthorization,
            "application/xml", rq);
    return xmlString;
}

From source file:test.be.fedict.eid.applet.ControllerTest.java

@Before
public void setUp() throws Exception {
    this.servletTester = new ServletTester();
    this.servletHolder = this.servletTester.addServlet(AppletServiceServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    this.certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), this.certificate, "secret".toCharArray(),
            "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);
    this.servletTester.getContext().getServer().addConnector(sslSocketConnector);
    this.sslLocation = "https://localhost:" + sslPort + "/";

    this.servletTester.start();

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(this.certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);
}