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.icestuff.getdown.maven.SignConfig.java

private void sign(File inputFile, File signatureFile)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException, InvalidKeyException, SignatureException {
    // initialize the keystore
    KeyStore store = KeyStore.getInstance(storetype == null ? "JKS" : storetype);
    FileInputStream storeInput = new FileInputStream(getKeystore());
    store.load(storeInput, getStorepass().toCharArray());
    PrivateKey key = (PrivateKey) store.getKey(getAlias(),
            getKeypass() == null ? getKeypass().toCharArray() : getKeypass().toCharArray());

    // sign the digest file
    Signature sig = Signature.getInstance("SHA1withRSA");
    FileInputStream dataInput = new FileInputStream(inputFile);
    byte[] buffer = new byte[8192];
    int length;//from ww w .  j a v a2 s. c  om

    sig.initSign(key);
    while ((length = dataInput.read(buffer)) != -1) {
        sig.update(buffer, 0, length);
    }

    // Write out the signature
    FileOutputStream signatureOutput = new FileOutputStream(signatureFile);
    String signed = new String(Base64.encodeBase64(sig.sign()));
    signatureOutput.write(signed.getBytes("utf8"));
}

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

/**
 * Unlock a key or key pair entry. Updates the KeyStore history with the
 * password.//www . j  a  v  a2s. co  m
 *
 * @param alias
 *            Entry's alias
 * @param state
 *            KeyStore state
 * @return Key pair password if successful, null otherwise
 */
protected Password unlockEntry(String alias, KeyStoreState state) {
    try {
        KeyStore keyStore = state.getKeyStore();

        DGetPassword dGetPassword = new DGetPassword(frame,
                MessageFormat.format(res.getString("KeyStoreExplorerAction.UnlockEntry.Title"), alias));
        dGetPassword.setLocationRelativeTo(frame);
        dGetPassword.setVisible(true);
        Password password = dGetPassword.getPassword();

        if (password == null) {
            return null;
        }

        keyStore.getKey(alias, password.toCharArray()); // Test password is correct

        state.setEntryPassword(alias, password);
        kseFrame.updateControls(true);

        return password;
    } catch (GeneralSecurityException ex) {
        String problemStr = MessageFormat.format(res.getString("KeyStoreExplorerAction.NoUnlockEntry.Problem"),
                alias);

        String[] causes = new String[] { res.getString("KeyStoreExplorerAction.PasswordIncorrectEntry.Cause") };

        Problem problem = new Problem(problemStr, causes, ex);

        DProblem dProblem = new DProblem(frame,
                res.getString("KeyStoreExplorerAction.ProblemUnlockingEntry.Title"), problem);
        dProblem.setLocationRelativeTo(frame);
        dProblem.setVisible(true);

        return null;
    }
}

From source file:org.wso2.carbon.identity.entitlement.pep.agent.wsxacml.WSXACMLEntitlementServiceClient.java

/**
 * Create basic X509 credentials using server configuration
 *
 * @return basicX509Credential/*from  ww w . j  a  v  a2 s.c o m*/
 */
private BasicX509Credential createBasicCredentials() {

    PrivateKey issuerPK = null;
    Certificate certificate = null;
    ServerConfiguration serverConfig = ServerConfiguration.getInstance();
    String ksPassword = serverConfig.getFirstProperty("Security.KeyStore.Password");
    String ksLocation = serverConfig.getFirstProperty("Security.KeyStore.Location");
    String keyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
    String ksType = serverConfig.getFirstProperty("Security.KeyStore.Type");
    String privateKeyPassword = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");

    try {
        FileInputStream fis = new FileInputStream(ksLocation);
        BufferedInputStream bis = new BufferedInputStream(fis);
        KeyStore keyStore = KeyStore.getInstance(ksType);

        keyStore.load(bis, ksPassword.toCharArray());
        bis.close();
        issuerPK = (PrivateKey) keyStore.getKey(keyAlias, privateKeyPassword.toCharArray());
        certificate = keyStore.getCertificate(keyAlias);

    } catch (KeyStoreException e) {
        log.error("Error in getting a keystore.", e);
    } catch (FileNotFoundException e) {
        log.error("Error in reading the keystore file from given the location.", e);
    } catch (CertificateException e) {
        log.error("Error in creating a X.509 certificate.", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Error in loading the keystore.", e);
    } catch (IOException e) {
        log.error("Error in reading keystore file.", e);
    } catch (UnrecoverableKeyException e) {
        log.error("Error in getting the private key.", e);
    }

    BasicX509Credential basicCredential = new BasicX509Credential();
    basicCredential.setEntityCertificate((java.security.cert.X509Certificate) certificate);
    basicCredential.setPrivateKey(issuerPK);

    return basicCredential;
}

From source file:org.wso2.pwprovider.DefaultPasswordProvider.java

/**
 * Encrypted password value would be decrypted using primary key of carbon server
 * @param  encryptedPassword  password which has been encrypted
 * @return decryptedPassword  /*from ww w  . ja  v a2  s  .  c  o  m*/
 */
public String resolve(String encryptedPassword) {

    log.info("Password is decrypted using DefaultPasswordProvider");

    final String xpathOfKeyLocation = "//KeyStore/KeyStoreName";
    final String xpathOfType = "//KeyStore/Type";
    final String xpathOfAlias = "//KeyStore/KeyAlias";
    final String xpathOfKeyStorePass = "//KeyStore/KeyStorePassword";
    final String xpathOfKeyPass = "//KeyStore/PrivateKeyPassword";

    final String xpathOfPrimaryKeyLocation = "//Server/Security/KeyStore/Location";
    final String xpathOfPrimaryKeyType = "//Server/Security/KeyStore/Type";
    final String xpathOfPrimaryKeyAlias = "//Server/Security/KeyStore/KeyAlias";

    String textFileName;
    String textFileName_tmp;
    boolean samePrivateKeyStorePass;
    carbonHome = System.getProperty("carbon.home");
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().indexOf("win") == -1) {
        textFileName = "password";
        textFileName_tmp = "password-tmp";
    } else {
        textFileName = "password.txt";
        textFileName_tmp = "password-tmp.txt";
    }

    String keyStorePrivateKeyPass = System.getProperty("private.keyStore.password");
    if (keyStorePrivateKeyPass != null && keyStorePrivateKeyPass.trim().equals("false")) {
        samePrivateKeyStorePass = false;
    } else {
        samePrivateKeyStorePass = true;
    }
    keyDataFile = new File(carbonHome + File.separator + "resources" + File.separator + "security"
            + File.separator + textFileName);

    DefaultPasswordProvider passwordHideThread = new DefaultPasswordProvider();
    if (keyStorePassWord == null || keyStorePassWord.equals("") || privateKeyPassWord == null
            || privateKeyPassWord.equals("")) {
        if (keyDataFile.exists()) {
            keyStorePassWord = readPassword(keyDataFile, "keyStore");
            privateKeyPassWord = readPassword(keyDataFile, "privateKey");
            if (keyStorePassWord != null && !keyStorePassWord.equals("")) {
                if (privateKeyPassWord == null || privateKeyPassWord.equals("")) {
                    privateKeyPassWord = keyStorePassWord;
                }
            }
            keyStoreName = getPrimaryKeyData(xpathOfPrimaryKeyLocation);
            keyAlias = getPrimaryKeyData(xpathOfPrimaryKeyAlias);
            keyType = getPrimaryKeyData(xpathOfPrimaryKeyType);
            keyStoreName = carbonHome + keyStoreName.substring((keyStoreName.indexOf('}')) + 1);
            if (!renameConfigFile(textFileName_tmp)) {
                try {
                    throw new PasswordProviderException("Can not rename Password config" + " File");
                } catch (PasswordProviderException e) {
                    e.printStackTrace();
                }
            }
        } else {
            keyDataFile = new File(carbonHome + File.separator + "resources" + File.separator + "security"
                    + File.separator + textFileName_tmp);
            if (keyDataFile.exists()) {
                keyStorePassWord = readPassword(keyDataFile, "keyStore");
                privateKeyPassWord = readPassword(keyDataFile, "privateKey");
                if (keyStorePassWord != null && !keyStorePassWord.equals("")) {
                    if (privateKeyPassWord == null || privateKeyPassWord.equals("")) {
                        privateKeyPassWord = keyStorePassWord;
                    }
                }
                keyStoreName = getPrimaryKeyData(xpathOfPrimaryKeyLocation);
                keyAlias = getPrimaryKeyData(xpathOfPrimaryKeyAlias);
                keyType = getPrimaryKeyData(xpathOfPrimaryKeyType);
                keyStoreName = carbonHome + keyStoreName.substring((keyStoreName.indexOf('}')) + 1);
                if (!deleteConfigFile()) {
                    try {
                        throw new PasswordProviderException("Can not delete Password config " + "File");
                    } catch (PasswordProviderException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                keyDataFile = new File(carbonHome + File.separator + "resources" + File.separator + "security"
                        + File.separator + "key-password.xml");
                if (keyDataFile.exists()) {
                    keyStorePassWord = getDataFromConfigFile(keyDataFile, xpathOfKeyStorePass);
                    privateKeyPassWord = getDataFromConfigFile(keyDataFile, xpathOfKeyPass);
                    keyStoreName = getDataFromConfigFile(keyDataFile, xpathOfKeyLocation);
                    keyType = getDataFromConfigFile(keyDataFile, xpathOfType);
                    keyAlias = getDataFromConfigFile(keyDataFile, xpathOfAlias);
                    if (!renameConfigFile("key-password-tmp.xml")) {
                        try {
                            throw new PasswordProviderException("Can not rename Password " + "config File");
                        } catch (PasswordProviderException e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    keyDataFile = new File(carbonHome + File.separator + "resources" + File.separator
                            + "security" + File.separator + "key-password-tmp.xml");
                    if (keyDataFile.exists()) {
                        keyStorePassWord = getDataFromConfigFile(keyDataFile, xpathOfKeyStorePass);
                        privateKeyPassWord = getDataFromConfigFile(keyDataFile, xpathOfKeyPass);
                        keyStoreName = getDataFromConfigFile(keyDataFile, xpathOfKeyLocation);
                        keyType = getDataFromConfigFile(keyDataFile, xpathOfType);
                        keyAlias = getDataFromConfigFile(keyDataFile, xpathOfAlias);
                        if (!deleteConfigFile()) {
                            try {
                                throw new PasswordProviderException("Can not delete Password" + " config File");
                            } catch (PasswordProviderException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        passwordHideThread.start();
                        BufferedReader input1 = new BufferedReader(new InputStreamReader(System.in));
                        if (samePrivateKeyStorePass) {
                            log.info("Enter Primary KeyStore and Private Key Password of " + "Carbon Server :");
                            try {
                                keyStorePassWord = input1.readLine();
                                stopThread = false;
                                privateKeyPassWord = keyStorePassWord;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        } else {
                            log.info("Enter Primary KeyStore Password of Carbon Server :");
                            try {
                                keyStorePassWord = input1.readLine();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            BufferedReader input2 = new BufferedReader(new InputStreamReader(System.in));
                            log.info("Enter Private Key Password of Carbon Server :");
                            try {
                                privateKeyPassWord = input2.readLine();
                                stopThread = false;
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }

            }

        }
    }

    if (keyStoreName == null || keyStoreName.equals("")) {
        keyStoreName = getPrimaryKeyData(xpathOfPrimaryKeyLocation);
        keyStoreName = carbonHome + keyStoreName.substring((keyStoreName.indexOf('}')) + 1);
    }
    if (keyAlias == null || keyAlias.equals("")) {
        keyAlias = getPrimaryKeyData(xpathOfPrimaryKeyAlias);
    }
    if (keyType == null || keyType.equals("")) {
        keyType = getPrimaryKeyData(xpathOfPrimaryKeyType);
    }

    byte[] decrypted = null;
    PrivateKey privateKey = null;
    Cipher cipher = null;
    FileInputStream in = null;
    try {
        KeyStore keyStore = KeyStore.getInstance(keyType);
        in = new FileInputStream(keyStoreName);
        keyStore.load(in, keyStorePassWord.toCharArray());
        privateKey = (PrivateKey) keyStore.getKey(keyAlias, privateKeyPassWord.toCharArray());
    } catch (Exception e) {
        handleException("Error loading key store for decrypting " + "passwords in config files ", e);
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            handleException("Error closing input stream of keystore file");
        }
    }

    try {
        cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
    } catch (InvalidKeyException e) {
        handleException("Error initializing Cipher ");
    } catch (NoSuchAlgorithmException e) {
        handleException("Error initializing Cipher ");
    } catch (NoSuchPaddingException e) {
        handleException("Error initializing Cipher ");
    }

    if (encryptedPassword == null) {
        handleException("Error encrypted data can not be null ");
    }
    if (privateKey == null) {
        handleException("Error private key can not be null ");
    }

    try {
        decrypted = cipher.doFinal(new BASE64Decoder().decodeBuffer(encryptedPassword));
    } catch (Exception e) {
        handleException("Error occurred when decrypting encrypted value");
    }
    return new String(decrypted);
}

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

public String generateCertificateReq(final String keyStoreName, final String keyStorePwd, final String keyAlias,
        final String signAlg, final boolean withTag) {
    try {//from ww  w .  jav a 2s . c o m
        final KeyStore ctlKeyStore = KeyStore.getInstance("JKS");
        final FileInputStream fInputStream = new FileInputStream(workingDir + keyStoreName);
        ctlKeyStore.load(fInputStream, keyStorePwd.toCharArray());
        if (ctlKeyStore.containsAlias(keyAlias)) {
            final X509Certificate odlCert = (X509Certificate) ctlKeyStore.getCertificate(keyAlias);
            final PublicKey pubKey = odlCert.getPublicKey();
            final PrivateKey privKey = (PrivateKey) ctlKeyStore.getKey(keyAlias, keyStorePwd.toCharArray());
            final String subject = odlCert.getSubjectDN().getName();
            final X509Name xname = new X509Name(subject);
            final String signatureAlgorithm = signAlg;
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(signatureAlgorithm, xname,
                    pubKey, null, privKey);
            final String certReq = DatatypeConverter.printBase64Binary(csr.getEncoded());
            if (withTag) {
                final StringBuilder sb = new StringBuilder();
                sb.append(KeyStoreConstant.BEGIN_CERTIFICATE_REQUEST);
                sb.append("\n");
                sb.append(certReq);
                sb.append("\n");
                sb.append(KeyStoreConstant.END_CERTIFICATE_REQUEST);
                return sb.toString();
            }
            return certReq;
        }
        LOG.info("{} KeyStore does not contain alias {}", keyStoreName, keyAlias);
        return null;
    } catch (NoSuchAlgorithmException | CertificateException | IOException | KeyStoreException
            | UnrecoverableKeyException | InvalidKeyException | NoSuchProviderException
            | SignatureException e) {
        LOG.error("Failed to generate certificate request {}", e.getMessage());
        return null;
    }
}

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 av  a  2  s .  com*/
 * 
 * @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   w  w w .  j  av  a  2s .  c  o m
 * 
 * @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:test.integ.be.e_contract.mycarenet.etee.SealTest.java

@Test
public void testSeal() throws Exception {
    InputStream sealInputStream = SealTest.class.getResourceAsStream("/seal-fcorneli.der");
    assertNotNull(sealInputStream);/*  ww  w .  jav a 2 s. c om*/
    byte[] cmsData = IOUtils.toByteArray(sealInputStream);

    // check outer signature
    byte[] data = getVerifiedContent(cmsData);

    // decrypt content

    CMSEnvelopedDataParser cmsEnvelopedDataParser = new CMSEnvelopedDataParser(data);
    LOG.debug("content encryption algo: "
            + cmsEnvelopedDataParser.getContentEncryptionAlgorithm().getAlgorithm().getId());

    RecipientInformationStore recipientInformationStore = cmsEnvelopedDataParser.getRecipientInfos();
    Collection<RecipientInformation> recipients = recipientInformationStore.getRecipients();
    RecipientInformation recipientInformation = recipients.iterator().next();
    LOG.debug("recipient info type: " + recipientInformation.getClass().getName());
    KeyTransRecipientInformation keyTransRecipientInformation = (KeyTransRecipientInformation) recipientInformation;

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

    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory.createKey(eHealthPrivateKey.getEncoded());
    BcRSAKeyTransEnvelopedRecipient recipient = new BcRSAKeyTransEnvelopedRecipient(privKeyParams);
    byte[] decryptedContent = recipientInformation.getContent(recipient);
    assertNotNull(decryptedContent);
    LOG.debug("decrypted content size: " + decryptedContent.length);

    byte[] result = getVerifiedContent(decryptedContent);
    LOG.debug("result: " + new String(result));
}

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

@Test
public void testAuthenticationSignatures() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);//  w  w w .j a v  a 2  s  .com
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);

    verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA224withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA256withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD128withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD160withRSA", authnPrivateKey, authnCertificate.getPublicKey());
    verifySignatureAlgorithm("RIPEMD256withRSA", authnPrivateKey, authnCertificate.getPublicKey());
}

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  w w w .  j  av  a 2s . c o m
 * 
 * @throws Exception
 */
@Test
public void testScenarioInvokePlainText() 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
    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[] data = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(data);
    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();
        for (Map.Entry<String, DataHandler> messageAttachment : messageAttachments.entrySet()) {
            LOG.debug("message attachment id: " + messageAttachment.getKey());
            LOG.debug("message data handler: " + messageAttachment.getValue());
            DataHandler resultDataHandler = messageAttachment.getValue();
            DataSource resultDataSource = resultDataHandler.getDataSource();
            byte[] attachmentData = IOUtils.toByteArray(resultDataSource.getInputStream());
            LOG.debug("DataHandler.DataSource.getInputStream length: " + attachmentData.length);
        }
        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);
    }
}