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:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private void verifyCertificate(X509Certificate certificate) throws Exception {
    KeyStore ks = KeyStore.getInstance(JKS_INSTANCE);

    ks.load(this.getClass().getResourceAsStream(certificateVerifierConfig.getStorePath()),
            certificateVerifierConfig.getStorePwd().toCharArray());
    Set<X509Certificate> trustedRootCerts = new HashSet<X509Certificate>();
    for (String alias : certificateVerifierConfig.getTrustCertAliases()) {
        java.security.cert.Certificate stsCert = ks.getCertificate(alias);
        trustedRootCerts.add((X509Certificate) stsCert);
    }/*from w ww  . j a va2 s.  co  m*/

    CertificateVerifier.verifyCertificate(certificate, trustedRootCerts,
            certificateVerifierConfig.isVerifySelfSignedCert());
}

From source file:org.wso2.carbon.apimgt.impl.token.AbstractJWTGenerator.java

/**
 * Helper method to add public certificate to JWT_HEADER to signature verification.
 *
 * @param endUserName/*from w  w w  .  ja v  a2 s  .c  om*/
 * @throws APIManagementException
 */
private String addCertToHeader(String endUserName) throws APIManagementException {

    try {
        //get tenant domain
        String tenantDomain = MultitenantUtils.getTenantDomain(endUserName);
        //get tenantId
        int tenantId = APIUtil.getTenantId(endUserName);
        Certificate publicCert = null;

        if (!(publicCerts.containsKey(tenantId))) {
            //get tenant's key store manager
            APIUtil.loadTenantRegistry(tenantId);
            KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId);

            KeyStore keyStore = null;
            if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
                //derive key store name
                String ksName = tenantDomain.trim().replace(".", "-");
                String jksName = ksName + ".jks";
                keyStore = tenantKSM.getKeyStore(jksName);
                publicCert = keyStore.getCertificate(tenantDomain);
            } else {
                keyStore = tenantKSM.getPrimaryKeyStore();
                publicCert = tenantKSM.getDefaultPrimaryCertificate();
            }
            if (publicCert != null) {
                publicCerts.put(tenantId, publicCert);
            }
        } else {
            publicCert = publicCerts.get(tenantId);
        }

        //generate the SHA-1 thumbprint of the certificate
        //TODO: maintain a hashmap with tenants' pubkey thumbprints after first initialization
        MessageDigest digestValue = MessageDigest.getInstance("SHA-1");
        byte[] der = publicCert.getEncoded();
        digestValue.update(der);
        byte[] digestInBytes = digestValue.digest();

        String publicCertThumbprint = hexify(digestInBytes);
        String base64EncodedThumbPrint = Base64Utils.encode(publicCertThumbprint.getBytes());
        //String headerWithCertThumb = JWT_HEADER.replaceAll("\\[1\\]", base64EncodedThumbPrint);
        //headerWithCertThumb = headerWithCertThumb.replaceAll("\\[2\\]", signatureAlgorithm);
        //return headerWithCertThumb;

        StringBuilder jwtHeader = new StringBuilder();
        //Sample header
        //{"typ":"JWT", "alg":"SHA256withRSA", "x5t":"NmJmOGUxMzZlYjM2ZDRhNTZlYTA1YzdhZTRiOWE0NWI2M2JmOTc1ZA=="}
        //{"typ":"JWT", "alg":"[2]", "x5t":"[1]"}
        jwtHeader.append("{\"typ\":\"JWT\",");
        jwtHeader.append("\"alg\":\"");
        jwtHeader.append(SHA256_WITH_RSA.equals(signatureAlgorithm)
                ? JWTSignatureAlg.SHA256_WITH_RSA.getJwsCompliantCode()
                : signatureAlgorithm);
        jwtHeader.append("\",");

        jwtHeader.append("\"x5t\":\"");
        jwtHeader.append(base64EncodedThumbPrint);
        jwtHeader.append("\"");

        jwtHeader.append("}");
        return jwtHeader.toString();

    } catch (KeyStoreException e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error);
    } catch (CertificateEncodingException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error);
    } catch (NoSuchAlgorithmException e) {
        String error = "Error in generating public cert thumbprint";
        throw new APIManagementException(error);
    } catch (Exception e) {
        String error = "Error in obtaining tenant's keystore";
        throw new APIManagementException(error);
    }
}

From source file:org.wso2.carbon.identity.sso.saml.cloud.util.SAMLSSOUtil.java

/**
 * Get the X509CredentialImpl object for a particular tenant
 *
 * @param tenantDomain/*from   w  w w  .j a v a  2s. c  om*/
 * @param alias
 * @return X509CredentialImpl object containing the public certificate of
 * that tenant
 * @throws IdentitySAML2SSOException Error when creating X509CredentialImpl object
 */
public static X509CredentialImpl getX509CredentialImplForTenant(String tenantDomain, String alias)
        throws IdentitySAML2SSOException {

    if (tenantDomain == null || tenantDomain.trim().isEmpty() || alias == null || alias.trim().isEmpty()) {
        throw new IllegalArgumentException(
                "Invalid parameters; domain name : " + tenantDomain + ", " + "alias : " + alias);
    }
    int tenantId;
    try {
        tenantId = realmService.getTenantManager().getTenantId(tenantDomain);
    } catch (org.wso2.carbon.user.api.UserStoreException e) {
        String errorMsg = "Error getting the tenant ID for the tenant domain : " + tenantDomain;
        throw new IdentitySAML2SSOException(errorMsg, e);
    }

    KeyStoreManager keyStoreManager;
    // get an instance of the corresponding Key Store Manager instance
    keyStoreManager = KeyStoreManager.getInstance(tenantId);

    X509CredentialImpl credentialImpl = null;
    KeyStore keyStore;

    try {
        if (tenantId != -1234) {// for tenants, load private key from their generated key store
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
        } else { // for super tenant, load the default pub. cert using the
            // config. in carbon.xml
            keyStore = keyStoreManager.getPrimaryKeyStore();
        }
        java.security.cert.X509Certificate cert = (java.security.cert.X509Certificate) keyStore
                .getCertificate(alias);
        credentialImpl = new X509CredentialImpl(cert);

    } catch (Exception e) {
        String errorMsg = "Error instantiating an X509CredentialImpl object for the public certificate of "
                + tenantDomain;
        throw new IdentitySAML2SSOException(errorMsg, e);
    }
    return credentialImpl;
}

From source file:de.brendamour.jpasskit.signing.PKSigningInformationUtil.java

/**
 * Load all signing information necessary for pass generation using two input streams for the key store and the Apple WWDRCA certificate.
 * //from  ww  w.  j a v a  2 s . c om
 * The caller is responsible for closing the stream after this method returns successfully or fails.
 * 
 * @param pkcs12KeyStoreInputStream
 *            <code>InputStream</code> of the key store
 * @param keyStorePassword
 *            Password used to access the key store
 * @param appleWWDRCAFileInputStream
 *            <code>InputStream</code> of the Apple WWDRCA certificate.
 * @return Signing informatino necessary to sign a pass.
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 * @throws KeyStoreException
 * @throws NoSuchProviderException
 * @throws UnrecoverableKeyException
 */
public PKSigningInformation loadSigningInformationFromPKCS12AndIntermediateCertificate(
        final InputStream pkcs12KeyStoreInputStream, final String keyStorePassword,
        final InputStream appleWWDRCAFileInputStream) throws IOException, NoSuchAlgorithmException,
        CertificateException, KeyStoreException, NoSuchProviderException, UnrecoverableKeyException {

    KeyStore pkcs12KeyStore = loadPKCS12File(pkcs12KeyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases = pkcs12KeyStore.aliases();

    PrivateKey signingPrivateKey = null;
    X509Certificate signingCert = null;

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

        Key key = pkcs12KeyStore.getKey(aliasName, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            signingPrivateKey = (PrivateKey) key;
            Object cert = pkcs12KeyStore.getCertificate(aliasName);
            if (cert instanceof X509Certificate) {
                signingCert = (X509Certificate) cert;
                break;
            }
        }
    }

    X509Certificate appleWWDRCACert = loadDERCertificate(appleWWDRCAFileInputStream);
    return checkCertsAndReturnSigningInformationObject(signingPrivateKey, signingCert, appleWWDRCACert);
}

From source file:test.integ.be.e_contract.sts.CXFSTSClientTest.java

@Test
public void testBeIDAuthnCertToFile() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//  w ww  .  ja va 2s.c o  m
    Certificate certificate = keyStore.getCertificate("Authentication");
    File tmpFile = File.createTempFile("eid-authn-", ".der");
    FileUtils.writeByteArrayToFile(tmpFile, certificate.getEncoded());
    LOGGER.debug("eID authn cert file: {}", tmpFile.getAbsolutePath());
}

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)) {
            /*/*from w w  w . j av  a  2 s  .  c o m*/
             * 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:mitm.BouncyCastleSslEngineSource.java

private void initializeKeyStore()
        throws RootCertificateException, GeneralSecurityException, OperatorCreationException, IOException {
    if (authority.aliasFile(KEY_STORE_FILE_EXTENSION).exists() && authority.aliasFile(".pem").exists()) {
        return;/*  www.  ja  va 2 s  .  com*/
    }
    MillisecondsDuration duration = new MillisecondsDuration();
    KeyStore keystore = CertificateHelper.createRootCertificate(authority, KEY_STORE_TYPE);
    LOG.info("Created root certificate authority key store in {}ms", duration);

    OutputStream os = null;
    try {
        os = new FileOutputStream(authority.aliasFile(KEY_STORE_FILE_EXTENSION));
        keystore.store(os, authority.password());
    } finally {
        IOUtils.closeQuietly(os);
    }

    Certificate cert = keystore.getCertificate(authority.alias());
    exportPem(authority.aliasFile(".pem"), cert);
}

From source file:test.integ.be.e_contract.mycarenet.cxf.ScenarioTest.java

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.//from  ww  w. j ava2 s . c om
 * 
 * @throws Exception
 */
@Test
public void testScenario() 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");

    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: remove all messages.
    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);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    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[] data = new byte[1024 * 256];
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        GetFullMessageResponseType getFullMessageResponse = eHealthBoxClient.getMessage(messageId);
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

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

/**
 * First we clean the eHealthBox. Then we publish to ourself. Next we
 * download this message.//from  www. ja va2s  .  c  om
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvoke() 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");

    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: remove all messages.
    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);
        eHealthBoxClient.deleteMessage(messageId);
    }

    // eHealthBox: publish via SOAP attachment
    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[] data = new byte[1024 * 256];
    DataSource dataSource = new ByteArrayDataSource(data, "application/octet-stream");
    DataHandler dataHandler = new DataHandler(dataSource);
    publicationDocument.setEncryptableBinaryContent(dataHandler);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(data);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();
    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);

    // give eHealthBox some time.
    Thread.sleep(1000 * 5);

    LOG.debug("GET MESSAGES LIST");
    messageList = eHealthBoxClient.getMessagesList();
    for (Message message : messageList.getMessage()) {
        String messageId = message.getMessageId();
        LOG.debug("message id: " + messageId);
        LOG.debug("GET FULL MESSAGE");
        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: " + response);
        JAXBContext consultationContext = JAXBContext
                .newInstance(be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ObjectFactory.class);
        Unmarshaller consultationUnmarshaller = consultationContext.createUnmarshaller();
        Map<String, DataHandler> messageAttachments = eHealthBoxClient.getMessageAttachments();
        consultationUnmarshaller.setAttachmentUnmarshaller(new SOAPAttachmentUnmarshaller(messageAttachments));
        JAXBElement<GetFullMessageResponseType> jaxbElement = (JAXBElement<GetFullMessageResponseType>) consultationUnmarshaller
                .unmarshal(new StringReader(response));
        GetFullMessageResponseType getFullMessageResponse = jaxbElement.getValue();
        ConsultationMessageType consultationMessage = getFullMessageResponse.getMessage();
        be.e_contract.mycarenet.ehbox.jaxb.consultation.protocol.ContentContextType consultationContentContext = consultationMessage
                .getContentContext();
        ConsultationContentType consultationContent = consultationContentContext.getContent();
        ConsultationDocumentType consultationDocument = consultationContent.getDocument();
        byte[] encryptableTextContent = consultationDocument.getEncryptableTextContent();
        if (null != encryptableTextContent) {
            LOG.debug("result EncryptableTextContent: " + encryptableTextContent.length);
        } else {
            LOG.debug("no EncryptableTextContent");
        }
        DataHandler resultDataHandler = consultationDocument.getEncryptableBinaryContent();
        if (null != resultDataHandler) {
            LOG.debug("result EncryptableBinaryContent");
            byte[] resultData = IOUtils.toByteArray(resultDataHandler.getInputStream());
            LOG.debug("result data size: " + resultData.length);
        }
        LOG.debug("DELETE MESSAGE");
        eHealthBoxClient.deleteMessage(messageId);
    }
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Performs test signatures for the specified keys or for all if "all" specified.
 * @param keyStore Loaded keystore to read keys from
 * @param alias Alias of key to test or "all" to test all
 * @param authCode Key password (if used, ie for JKS only)
 * @param signatureProvider Provider for creating the signature
 * @return The results for each key found
 * @throws CryptoTokenOfflineException In case the key could not be used
 *//*from w  w  w  .ja va 2s.  c  o m*/
public static Collection<KeyTestResult> testKey(KeyStore keyStore, String alias, char[] authCode,
        String signatureProvider) throws CryptoTokenOfflineException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("testKey for alias: " + alias);
    }

    final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>();

    try {
        final Enumeration<String> e = keyStore.aliases();
        while (e.hasMoreElements()) {
            final String keyAlias = e.nextElement();
            if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("checking keyAlias: " + keyAlias);
                }

                if (keyStore.isKeyEntry(keyAlias)) {
                    String status;
                    String publicKeyHash = null;
                    boolean success = false;
                    try {
                        final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode);
                        final Certificate entryCert = keyStore.getCertificate(keyAlias);
                        if (entryCert != null) {
                            final PublicKey publicKey = entryCert.getPublicKey();
                            publicKeyHash = createKeyHash(publicKey);
                            testSignAndVerify(privateKey, publicKey, signatureProvider);
                            success = true;
                            status = "";
                        } else {
                            status = "Not testing keys with alias " + keyAlias + ". No certificate exists.";
                        }
                    } catch (ClassCastException ce) {
                        status = "Not testing keys with alias " + keyAlias + ". Not a private key.";
                    } catch (InvalidKeyException ex) {
                        LOG.error("Error testing key: " + keyAlias, ex);
                        status = ex.getMessage();
                    } catch (KeyStoreException ex) {
                        LOG.error("Error testing key: " + keyAlias, ex);
                        status = ex.getMessage();
                    } catch (NoSuchAlgorithmException ex) {
                        LOG.error("Error testing key: " + keyAlias, ex);
                        status = ex.getMessage();
                    } catch (NoSuchProviderException ex) {
                        LOG.error("Error testing key: " + keyAlias, ex);
                        status = ex.getMessage();
                    } catch (SignatureException ex) {
                        LOG.error("Error testing key: " + keyAlias, ex);
                        status = ex.getMessage();
                    } catch (UnrecoverableKeyException ex) {
                        LOG.error("Error testing key: " + keyAlias, ex);
                        status = ex.getMessage();
                    }
                    result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash));
                }
            }
        }
    } catch (KeyStoreException ex) {
        throw new CryptoTokenOfflineException(ex);
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("<testKey");
    }
    return result;
}