Example usage for java.security KeyStore aliases

List of usage examples for java.security KeyStore aliases

Introduction

In this page you can find the example usage for java.security KeyStore aliases.

Prototype

public final Enumeration<String> aliases() throws KeyStoreException 

Source Link

Document

Lists all the alias names of this keystore.

Usage

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*from   w  w w  . j a  va  2s  .  c om*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreID != null) {
            KeyStore keystore = createKeyStore(this.keystoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        logger.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                logger.debug(" Certificate " + (c + 1) + ":");
                                logger.debug("  Subject DN: " + cert.getSubjectDN());
                                logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                logger.debug("  Valid from: " + cert.getNotBefore());
                                logger.debug("  Valid until: " + cert.getNotAfter());
                                logger.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keyPassword);
        }
        if (this.truststoreID != null) {
            KeyStore keystore = createKeyStore(this.truststoreID);
            if (logger.isDebugEnabled()) {
                Enumeration<String> aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = aliases.nextElement();
                    logger.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslctx = SSLContext.getInstance("SSL");
        sslctx.init(keymanagers, trustmanagers, null);
        return sslctx;
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        throw new AuthSSLInitializationError("Error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testGetCertificateAuthnCertCredential() throws Exception {
    LOG.debug("sign");
    // operate/*from ww  w. j  a va  2 s  .  c  o  m*/
    Security.addProvider(new BeIDProvider());
    KeyStore beidKeyStore = KeyStore.getInstance("BeID");
    beidKeyStore.load(null);
    X509Certificate authnCert = (X509Certificate) beidKeyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) beidKeyStore.getKey("Authentication", null);

    Security.addProvider(new HSMProxyProvider());
    KeyStore hsmProxyKeyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(authnPrivateKey, authnCert,
            // "https://www.e-contract.be/hsm-proxy-ws/dss",
            "http://localhost/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    hsmProxyKeyStore.load(keyStoreParameter);

    Enumeration<String> aliasesEnum = hsmProxyKeyStore.aliases();
    assertNotNull(aliasesEnum);
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) hsmProxyKeyStore.getCertificate(alias);
        assertNotNull(certificate);
        LOG.debug("certificate: " + certificate);
        assertTrue(hsmProxyKeyStore.containsAlias(alias));
        Certificate[] certificateChain = hsmProxyKeyStore.getCertificateChain(alias);
        assertNotNull(certificateChain);
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) hsmProxyKeyStore.getEntry(alias, null);
        assertNotNull(privateKeyEntry);
    }
}

From source file:com.stargame.ad.util.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*ww w  .  jav a  2s  . c  om*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LogUtil.d(AuthSSLProtocolSocketFactory.class, " Certificate " + (c + 1) + ":");
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        LogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:mitm.application.djigzo.workflow.impl.KeyAndCertificateWorkflowImpl.java

private int importKeyStoreTransacted(KeyStore keyStore, MissingKey missingKey) throws KeyStoreException {
    Check.notNull(keyStore, "keyStore");
    Check.notNull(missingKey, "missingKey");

    int importedEntries = 0;

    Enumeration<String> aliases = keyStore.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        logger.debug("Alias: " + alias);

        Certificate certificate = keyStore.getCertificate(alias);

        if (!(certificate instanceof X509Certificate)) {
            /*/*ww w . j a va 2 s.c om*/
             * only X509Certificates are supported
             */
            continue;
        }

        try {
            Key key = keyStore.getKey(alias, null);

            if (!(key instanceof PrivateKey)) {
                key = null;
            }

            if (key == null && missingKey == MissingKey.SKIP_CERTIFICATE) {
                logger.debug("Certificate found but missing Private key. Skipping certificate");

                continue;
            }

            KeyAndCertificate keyAndCertificate = new KeyAndCertificateImpl((PrivateKey) key,
                    (X509Certificate) certificate);

            if (keyAndCertStore.addKeyAndCertificate(keyAndCertificate)) {
                importedEntries++;
            }

            Certificate[] chain = keyStore.getCertificateChain(alias);

            importedEntries += importChain(chain);
        } catch (UnrecoverableKeyException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (NoSuchAlgorithmException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (KeyStoreException e) {
            logger.error("Unable to retrieve the key.", e);
        } catch (CertStoreException e) {
            logger.error("Unable to retrieve the key.", e);
        }
    }

    return importedEntries;
}

From source file:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {//ww  w . j av a  2s .  c om
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (AbLogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        " Certificate " + (c + 1) + ":");
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Subject DN: " + cert.getSubjectDN());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Signature Algorithm: " + cert.getSigAlgName());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid from: " + cert.getNotBefore());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Valid until: " + cert.getNotAfter());
                                AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                        "  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (AbLogUtil.D) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Subject DN: " + cert.getSubjectDN());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class,
                                "  Signature Algorithm: " + cert.getSigAlgName());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid from: " + cert.getNotBefore());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Valid until: " + cert.getNotAfter());
                        AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        AbLogUtil.e(AuthSSLProtocolSocketFactory.class, e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

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 {/*from  w w  w  . ja v a  2  s.com*/
        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: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 .jav a2  s .  co 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:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java

@Test
public void testPublish() throws Exception {
    // STS//  www.j ava  2  s. 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 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:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java

@Test
public void testPublishViaSOAPAttachment() throws Exception {
    // STS/* w ww.j a v  a2 s .  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 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("application/octet-stream");
    publicationDocument.setDownloadFileName("test.dat");
    byte[] message = "hello world".getBytes();
    DataSource dataSource = new ByteArrayDataSource(message, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    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);
}

From source file:test.integ.be.fedict.hsm.jca.HSMProxySignatureTest.java

@Test
public void testSign() throws Exception {
    LOG.debug("sign");
    // operate/* ww w.j  av a 2  s.co m*/
    Security.addProvider(new HSMProxyProvider());
    KeyStore keyStore = KeyStore.getInstance("HSMProxy");

    HSMProxyTestCredential testCredential = new HSMProxyTestCredential();
    HSMProxyKeyStoreParameter keyStoreParameter = new HSMProxyKeyStoreParameter(
            testCredential.getCredentialPrivateKey(), testCredential.getCredentialCertificate(),
            "http://localhost:8080/hsm-proxy-ws/dss", new MyHSMProxyAudit());
    keyStore.load(keyStoreParameter);

    String alias = keyStore.aliases().nextElement();

    PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, null);
    assertNotNull(privateKey);

    X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);

    signAndVerify(certificate, privateKey, "SHA1withRSA");
    signAndVerify(certificate, privateKey, "SHA256withRSA");
    signAndVerify(certificate, privateKey, "SHA512withRSA");
}