Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

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

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:it.cnr.icar.eric.server.security.authentication.CertificateAuthority.java

/** Extension request to sign specified cert and return the signed cert. */
@SuppressWarnings("static-access")
public RegistryResponseHolder signCertificateRequest(UserType user, RegistryRequestType req,
        Map<?, ?> idToRepositoryItemMap) throws RegistryException {

    RegistryResponseHolder respHolder = null;
    RegistryResponseType ebRegistryResponseType = null;
    ServerRequestContext context = null;

    try {/*from w  w  w  .  j  a  v  a  2  s.c  o m*/
        context = new ServerRequestContext("CertificateAUthority.signCertificateRequest", req);
        context.setUser(user);

        if (idToRepositoryItemMap.keySet().size() == 0) {
            throw new MissingRepositoryItemException(
                    ServerResourceBundle.getInstance().getString("message.KSRepItemNotFound"));
        }

        String id = (String) idToRepositoryItemMap.keySet().iterator().next();

        Object obj = idToRepositoryItemMap.get(id);
        if (!(obj instanceof RepositoryItem)) {
            throw new InvalidContentException();
        }
        RepositoryItem ri = (RepositoryItem) obj; //This is the JKS keystore containing cert to be signed            

        //Read original cert from keystore
        InputStream is = ri.getDataHandler().getInputStream();
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(is, bu.FREEBXML_REGISTRY_KS_PASS_REQ.toCharArray());
        is.close();
        X509Certificate cert = (X509Certificate) keyStore
                .getCertificate(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);

        //Sign the cert
        cert = signCertificate(cert);

        //Replace cert with signed cert in keystore
        keyStore.deleteEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_REQ);
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_USERCERT_ALIAS_RESP, cert);

        //Add CA root cert (RegistryOPerator's cert) to keystore.
        keyStore.setCertificateEntry(bu.FREEBXML_REGISTRY_CACERT_ALIAS, getCACertificate());

        Certificate[] certChain = new Certificate[2];
        certChain[0] = cert;
        certChain[1] = getCACertificate();
        validateChain(certChain);

        File repositoryItemFile = File.createTempFile(".eric-ca-resp", ".jks");
        repositoryItemFile.deleteOnExit();
        FileOutputStream fos = new java.io.FileOutputStream(repositoryItemFile);
        keyStore.store(fos, bu.FREEBXML_REGISTRY_KS_PASS_RESP.toCharArray());
        fos.flush();
        fos.close();

        DataHandler dh = new DataHandler(new FileDataSource(repositoryItemFile));
        RepositoryItemImpl riNew = new RepositoryItemImpl(id, dh);

        ebRegistryResponseType = bu.rsFac.createRegistryResponseType();
        ebRegistryResponseType.setStatus(BindingUtility.CANONICAL_RESPONSE_STATUS_TYPE_ID_Success);

        HashMap<String, Object> respIdToRepositoryItemMap = new HashMap<String, Object>();
        respIdToRepositoryItemMap.put(id, riNew);

        respHolder = new RegistryResponseHolder(ebRegistryResponseType, respIdToRepositoryItemMap);

    } catch (RegistryException e) {
        context.rollback();
        throw e;
    } catch (Exception e) {
        context.rollback();
        throw new RegistryException(e);
    }

    context.commit();
    return respHolder;
}

From source file:com.gnut3ll4.android.basicandroidkeystore.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.edittext);
    button = (Button) findViewById(R.id.button);

    mKeyStoreHelper = new KeyStoreHelper();
    mKeyStoreHelper.setAlias(ALIAS);//from w ww  .j a v  a 2 s .  com
    initializeLogging();

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            try {

                //Encrypt
                KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
                ks.load(null);
                Key key = ks.getKey(ALIAS, null);

                if (key instanceof PrivateKey) {

                    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
                    cipher.init(Cipher.ENCRYPT_MODE, ks.getCertificate(ALIAS).getPublicKey());
                    encryptedBytes = cipher.doFinal(editText.getText().toString().getBytes());

                    Log.d(TAG, "Encrypted bytes : " + Base64.encodeToString(encryptedBytes, Base64.DEFAULT));
                }

                //Decrypt
                PrivateKey privateKey = loadPrivateKey(ALIAS);
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "AndroidOpenSSL");
                cipher.init(Cipher.DECRYPT_MODE, privateKey);
                byte[] bytes = cipher.doFinal(encryptedBytes);

                Log.d(TAG, "Decrypted string : " + new String(bytes, "UTF-8"));

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    });

}

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   ww w  .  j  a v a 2  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//from w w w. j  a v  a  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/*from  w  w  w .ja  va  2  s  .  co  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("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:nl.clockwork.mule.ebms.cxf.EbMSSecSignatureInInterceptor.java

private boolean validateCertificate(KeyStore keyStore, X509Certificate certificate, Date date)
        throws KeyStoreException {
    try {/*from  w  ww. j  a va  2 s .  c  o m*/
        certificate.checkValidity(date);
    } catch (Exception e) {
        return false;
    }
    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        try {
            Certificate c = keyStore.getCertificate(aliases.nextElement());
            certificate.verify(c.getPublicKey());
            return true;
        } catch (KeyStoreException e) {
            throw e;
        } catch (Exception e) {
            logger.debug("", e);
        }
    }
    return false;
}

From source file:org.wso2.carbon.identity.user.store.ws.util.FileUtil.java

/**
 * Copy Public key to temporary location
 *
 * This method throws General Exception since current keyStoreManager.getDefaultPublicKey() throws Exception
 * @param publicKeyPath//from   ww  w .  j  a  va2s  .c  o  m
 * @throws Exception
 */
public void copyPublicKey(String publicKeyPath) throws Exception {
    int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantID);
    DataOutputStream dos = null;
    KeyStore keyStore;
    PublicKey publicKey;

    try {
        File file = new File(publicKeyPath);
        FileOutputStream fos = new FileOutputStream(file);
        dos = new DataOutputStream(fos);

        if (tenantID != MultitenantConstants.SUPER_TENANT_ID) {
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            Certificate publicCert = keyStore.getCertificate(tenantDomain); //Default keystore alias = tenantDomain name
            publicKey = publicCert.getPublicKey();
        } else {
            publicKey = keyStoreManager.getDefaultPublicKey();

        }

        byte[] keyBytes = publicKey.getEncoded();
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = encoder.encodeBuffer(keyBytes);
        dos.writeBytes(encoded);
        dos.flush();
    } finally {
        try {
            dos.close();
        } catch (IOException e) {
            log.error("Error occurred while closing data stream", e);
        }
    }
}

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

@Test
public void testPublishAnnex() throws Exception {
    // STS/*from w  ww .j av a 2 s .  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));

    List<PublicationAnnexType> publicationAnnexList = publicationContent.getAnnex();
    PublicationAnnexType publicationAnnex = objectFactory.createPublicationAnnexType();
    publicationAnnexList.add(publicationAnnex);
    publicationAnnex.setDownloadFileName("test.txt");
    publicationAnnex.setEncryptableTitle("hello world".getBytes());
    publicationAnnex.setMimeType("application/octet-stream");
    publicationAnnex.setEncryptableTextContent(message);
    messageDigest.reset();
    digest = messageDigest.digest(message);
    publicationAnnex.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.e_contract.mycarenet.sts.EHealthCertificateTest.java

@Test
public void testReadCertificate() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    LOG.debug("eHealth PKCS12 path: " + this.config.getEHealthPKCS12Path());
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    keyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = keyStore.aliases();
    while (aliasesEnum.hasMoreElements()) {
        String alias = aliasesEnum.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        LOG.debug("certificate: " + certificate);
        Certificate[] certificateChain = keyStore.getCertificateChain(alias);
        for (Certificate cert : certificateChain) {
            LOG.debug("certificate chain: " + cert);
        }/*from  ww  w. jav a2 s .com*/
    }
}