Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

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

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:org.kse.gui.actions.ImportCaReplyFromFileAction.java

/**
 * Do action./*ww  w  .  ja v  a  2  s .  c  o  m*/
 */
@Override
protected void doAction() {
    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStoreState newState = currentState.createBasisForNextState(this);

        KeyStore keyStore = newState.getKeyStore();
        KeyStoreType keyStoreType = KeyStoreType.resolveJce(keyStore.getType());

        Key privateKey = keyStore.getKey(alias, password.toCharArray());

        File caReplyFile = chooseCaFile();
        if (caReplyFile == null) {
            return;
        }

        X509Certificate[] certs = openCaReply(caReplyFile);

        if ((certs == null) || (certs.length == 0)) {
            return;
        }

        certs = X509CertUtil.orderX509CertChain(certs);

        X509Certificate[] exitingEntryCerts = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)));

        if (!exitingEntryCerts[0].getPublicKey().equals(certs[0].getPublicKey())) {
            JOptionPane.showMessageDialog(frame,
                    res.getString("ImportCaReplyFromFileAction.NoMatchPubKeyCaReply.message"),
                    res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                    JOptionPane.WARNING_MESSAGE);
            return;
        }

        // Holds the new certificate chain for the entry should the import succeed
        X509Certificate[] newCertChain = null;

        if (!applicationSettings.getEnableImportCaReplyTrustCheck()) {
            newCertChain = certs;
        } else {
            KeyStore caCertificates = getCaCertificates();
            KeyStore windowsTrustedRootCertificates = getWindowsTrustedRootCertificates();

            // PKCS #7 reply - try and match the self-signed root with any
            // of the certificates in the CA Certificates or current KeyStore
            if (certs.length > 1) {
                X509Certificate rootCert = certs[certs.length - 1];
                String matchAlias = null;

                if (caCertificates != null) // Match against CA Certificates KeyStore
                {
                    matchAlias = X509CertUtil.matchCertificate(caCertificates, rootCert);
                }

                // Match against Windows Trusted Root Certificates KeyStore
                if ((windowsTrustedRootCertificates != null) && (matchAlias == null)) {
                    matchAlias = X509CertUtil.matchCertificate(windowsTrustedRootCertificates, rootCert);
                }

                if (matchAlias == null) // Match against current KeyStore
                {
                    matchAlias = X509CertUtil.matchCertificate(keyStore, rootCert);
                }

                if (matchAlias == null) {
                    // No match for the root certificate - display the certificate to the user for confirmation
                    JOptionPane.showMessageDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.NoMatchRootCertCaReplyConfirm.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.INFORMATION_MESSAGE);

                    DViewCertificate dViewCertificate = new DViewCertificate(frame,
                            MessageFormat.format(
                                    res.getString("ImportCaReplyFromFileAction.CertDetailsFile.Title"),
                                    caReplyFile.getName()),
                            new X509Certificate[] { rootCert }, null, DViewCertificate.NONE);
                    dViewCertificate.setLocationRelativeTo(frame);
                    dViewCertificate.setVisible(true);

                    int selected = JOptionPane.showConfirmDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.AcceptCaReply.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.YES_NO_OPTION);
                    if (selected != JOptionPane.YES_OPTION) {
                        return;
                    }

                    newCertChain = certs;
                } else {
                    newCertChain = certs;
                }
            }
            // Single X.509 certificate reply - try and establish a chain of
            // trust from the certificate and ending with a root CA self-signed certificate
            else {
                // Establish trust against current KeyStore
                ArrayList<KeyStore> compKeyStores = new ArrayList<>();
                compKeyStores.add(keyStore);

                if (caCertificates != null) {
                    // Establish trust against CA Certificates KeyStore
                    compKeyStores.add(caCertificates);
                }

                if (windowsTrustedRootCertificates != null) {
                    // Establish trust against Windows Trusted Root Certificates KeyStore
                    compKeyStores.add(windowsTrustedRootCertificates);
                }

                X509Certificate[] trustChain = X509CertUtil.establishTrust(certs[0],
                        compKeyStores.toArray(new KeyStore[compKeyStores.size()]));

                if (trustChain != null) {
                    newCertChain = trustChain;
                } else {
                    // Cannot establish trust for the certificate - fail
                    JOptionPane.showMessageDialog(frame,
                            res.getString("ImportCaReplyFromFileAction.NoTrustCaReply.message"),
                            res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                            JOptionPane.WARNING_MESSAGE);
                    return;
                }
            }
        }

        if (keyStoreType.isFileBased()) {
            // TODO: why or when is delete actually necessary???
            keyStore.deleteEntry(alias);
            keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain);
        } else {
            keyStore.setKeyEntry(alias, privateKey, password.toCharArray(), newCertChain);
        }

        currentState.append(newState);

        kseFrame.updateControls(true);

        JOptionPane.showMessageDialog(frame,
                res.getString("ImportCaReplyFromFileAction.ImportCaReplySuccessful.message"),
                res.getString("ImportCaReplyFromFileAction.ImportCaReply.Title"),
                JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception ex) {
        DError.displayError(frame, ex);
    }
}

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

/**
 * Not supported according to Hannes De Clercq from eHealth.
 * /*from   ww  w .j av a 2s .c  om*/
 * @throws Exception
 */
@Test
public void testGetBoxInfoSelfSigned() throws Exception {
    // STS
    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");

    SessionKey sessionKey = new SessionKey(2048);
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusHours(24);
    sessionKey.setValidity(notBefore.toDate(), notAfter.toDate());
    X509Certificate eHealthCertificate = sessionKey.getCertificate();
    PrivateKey eHealthPrivateKey = sessionKey.getPrivate();

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

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

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

    assertNotNull(assertionElement);

    String assertionString = client.toString(assertionElement);

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);
    eHealthBoxClient.getBoxInfo();
}

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

@Test
public void testGetBoxInfoViaString() throws Exception {
    // STS/*from www.  j  av a  2s  .  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 request = "<ehbox:GetBoxInfoRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\"/>";

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, toString(assertion));
    String result = eHealthBoxClient.invoke(request);
    LOG.debug("result: " + result);
}

From source file:org.apache.xml.security.test.signature.CreateSignatureTest.java

String doSignWithCert() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;/*ww  w  . ja va 2  s.  c o m*/
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        fis = new FileInputStream(BASEDIR + SEP + "data/test.jks");
    } else {
        fis = new FileInputStream("data/test.jks");
    }
    ks.load(fis, "changeit".toCharArray());
    PrivateKey privateKey = (PrivateKey) ks.getKey("mullan", "changeit".toCharArray());
    org.w3c.dom.Document doc = db.newDocument();
    X509Certificate signingCert = (X509Certificate) ks.getCertificate("mullan");
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");

    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));

    Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);
    canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

    SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, XMLSignature.ALGO_ID_SIGNATURE_DSA);
    XMLSignature sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);

    root.appendChild(sig.getElement());
    doc.appendChild(doc.createComment(" Comment after "));
    Transforms transforms = new Transforms(doc);
    transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
    transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);

    sig.addKeyInfo(signingCert);
    sig.sign(privateKey);
    X509Certificate cert = sig.getKeyInfo().getX509Certificate();
    sig.checkSignatureValue(cert.getPublicKey());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    XMLUtils.outputDOMc14nWithComments(doc, bos);
    return new String(bos.toByteArray());
}

From source file:eu.eidas.auth.engine.SAMLEngineUtils.java

/**
 *
 * @param encryptionKeyStore//from ww  w . ja  v  a  2  s  .co m
 * @param serialNumber
 * @param issuer
 * @param keyPassword
 * @return the credential of the private key of the certificate having the given serialnumber and issuer
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws SAMLEngineException
 */

public static Credential getCredential(KeyStore encryptionKeyStore, String serialNumber, String issuer,
        char[] keyPassword)
        throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException, SAMLEngineException {
    CertificateAliasPair pair = getCertificatePair(encryptionKeyStore, serialNumber, issuer);
    final PrivateKey privateKey = (PrivateKey) encryptionKeyStore.getKey(pair.getAlias(), keyPassword);
    return SAMLEngineUtils.createCredential(pair.getCertificate(), privateKey);
}

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

@Test
public void testGetBoxInfoViaDOM() throws Exception {
    // STS/*from ww  w . j a  v a  2s . 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 request = "<ehbox:GetBoxInfoRequest xmlns:ehbox=\"urn:be:fgov:ehealth:ehbox:consultation:protocol:v3\"/>";
    DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    documentBuilderFactory.setNamespaceAware(true);
    DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
    Document requestDocument = documentBuilder.parse(new InputSource(new StringReader(request)));
    Element requestElement = requestDocument.getDocumentElement();

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, toString(assertion));
    eHealthBoxClient.invoke(requestElement);
}

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

@Test
public void testGetBoxInfoGetMessageDeleteMessage() throws Exception {
    // STS/* w w  w.  j ava  2s .com*/
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

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

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

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

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

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

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);
    eHealthBoxClient.getBoxInfo();

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        eHealthBoxClient.getMessage(messageId);
        eHealthBoxClient.deleteMessage(messageId);
    }
}

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

@Test
public void testDecryptMessages() throws Exception {
    // STS//  w  w  w  .j a  v 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());
    String encryptionAlias = aliasesEnum.nextElement();
    X509Certificate encryptionCertificate = (X509Certificate) eHealthKeyStore.getCertificate(encryptionAlias);
    PrivateKey encryptionPrivateKey = (PrivateKey) eHealthKeyStore.getKey(encryptionAlias,
            this.config.getEHealthPKCS12Password().toCharArray());

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

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

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

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox
    EHealthBoxConsultationClient eHealthBoxClient = new EHealthBoxConsultationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxConsultation/v3");
    eHealthBoxClient.setCredentials(eHealthPrivateKey, assertionString);

    GetMessageListResponseType messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId);
        DataHandler dataHandler = getFullMessageResponse.getMessage().getContentContext().getContent()
                .getDocument().getEncryptableBinaryContent();
        byte[] data;
        if (null != dataHandler) {
            data = IOUtils.toByteArray(dataHandler.getInputStream());
        } else {
            data = getFullMessageResponse.getMessage().getContentContext().getContent().getDocument()
                    .getEncryptableTextContent();
        }
        LOG.debug("data size: " + data.length);
        Unsealer unsealer = new Unsealer(encryptionPrivateKey, encryptionCertificate);
        unsealer.unseal(data);
    }
}

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

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

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

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

From source file:gui.configurar.GerarAssinatura.java

String assinar() {
    String senha = tSenha.getText();
    String c = tContribuinte.getText() + tDev.getText();
    if (certificado == null) {
        Msg.show("Escolha o certificado");
        return "";
    }/*  w ww  .  j  a  v a2  s.co  m*/
    try {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(new FileInputStream(certificado), senha.toCharArray());
        ArrayList<String> apelidos = new ArrayList<String>();
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            apelidos.add(aliases.nextElement());
        }
        PrivateKey key = (PrivateKey) keystore.getKey(apelidos.get(0), senha.toCharArray());
        Signature assinatura = Signature.getInstance("SHA256withRSA");
        assinatura.initSign(key);
        byte[] bytes = c.getBytes();
        assinatura.update(bytes);
        byte[] assinado = assinatura.sign();
        String strAssinado = Base64.encodeBase64String(assinado);
        return strAssinado;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}