List of usage examples for java.security Security addProvider
public static int addProvider(Provider provider)
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.// w w w . j a v a2 s .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.cxf.ScenarioTest.java
/** * First we clean the eHealthBox. Then we publish to ourself. Next we * download this message.//from w w w . ja va2 s .co 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]; for (int idx = 0; idx < data.length; idx++) { data[idx] = 'X'; } 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(); 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); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testNonRepudiationSignature() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*from w w w .ja v a 2s .c o m*/ PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(signPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature"); assertNotNull(signCertificateChain); }
From source file:org.kse.gui.dialogs.sign.DSignJar.java
public static void main(String[] args) throws Exception { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); Security.addProvider(new BouncyCastleProvider()); java.awt.EventQueue.invokeLater(new Runnable() { @Override//from ww w .j ava2 s.c o m public void run() { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyPairType.RSA.jce(), "BC"); kpg.initialize(1024, new SecureRandom()); KeyPair kp = kpg.generateKeyPair(); DSignJar dialog = new DSignJar(new JFrame(), kp.getPrivate(), KeyPairType.RSA, "signature name", null); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } @Override public void windowDeactivated(WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); }
From source file:org.alfresco.repo.security.authentication.ntlm.NTLMAuthenticationComponentImpl.java
/** * Set the JCE provider/* www. j a v a2 s. c o m*/ * * @param providerClass String */ public void setJCEProvider(String providerClass) { // Set the JCE provider, required to provide various encryption/hashing algorithms not available // in the standard Sun JDK/JRE try { // Load the JCE provider class and validate Object jceObj = Class.forName(providerClass).newInstance(); if (jceObj instanceof java.security.Provider) { // Inform listeners, validate the configuration change Provider jceProvider = (Provider) jceObj; // Add the JCE provider Security.addProvider(jceProvider); // Debug if (logger.isDebugEnabled()) logger.debug("Using JCE provider " + providerClass); } else { throw new AlfrescoRuntimeException( "JCE provider class is not a valid Provider class:" + providerClass); } } catch (ClassNotFoundException ex) { throw new AlfrescoRuntimeException("JCE provider class " + providerClass + " not found"); } catch (Exception ex) { throw new AlfrescoRuntimeException("JCE provider class error", ex); } }
From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java
private void preloadLibraries() { AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Security.addProvider(new BouncyCastleProvider()); return null; }/*from ww w . ja v a 2 s . c o m*/ }); }
From source file:org.renci.ahab.ndllib.transport.OrcaSMXMLRPCProxy.java
private KeyStore loadX509Data(FileInputStream certIS, FileInputStream keyIS, String keyAlias, String keyPassword) throws Exception { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); }//from ww w. java2s . c o m /* AccessController.doPrivileged(new PrivilegedAction<Void>() { public Void run() { if (Security.getProvider("BC") == null) { Security.addProvider(new BouncyCastleProvider()); } System.out.println("Currently loaded security providers:"); for (Provider p: Security.getProviders()) { System.out.println("Provider " + p + " - " + p.getName()); } System.out.println("End of security provider list."); return null; } }); */ JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC"); JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter().setProvider("BC"); Object object; PEMParser pemParser = new PEMParser(new BufferedReader(new InputStreamReader(keyIS, "UTF-8"))); PrivateKey privKey = null; while ((object = pemParser.readObject()) != null) { if (object instanceof PKCS8EncryptedPrivateKeyInfo) { InputDecryptorProvider decProv = new JceOpenSSLPKCS8DecryptorProviderBuilder() .build(keyPassword.toCharArray()); privKey = keyConverter .getPrivateKey(((PKCS8EncryptedPrivateKeyInfo) object).decryptPrivateKeyInfo(decProv)); break; } else if (object instanceof PEMEncryptedKeyPair) { PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder() .build(keyPassword.toCharArray()); privKey = keyConverter.getPrivateKey( (((PEMEncryptedKeyPair) object).decryptKeyPair(decProv)).getPrivateKeyInfo()); break; } else if (object instanceof PEMKeyPair) { privKey = keyConverter.getPrivateKey(((PEMKeyPair) object).getPrivateKeyInfo()); break; } } if (privKey == null) throw new Exception("Private key file did not contain a private key."); pemParser = new PEMParser(new BufferedReader(new InputStreamReader(certIS, "UTF-8"))); ArrayList<Certificate> certs = new ArrayList<Certificate>(); while ((object = pemParser.readObject()) != null) { if (object instanceof X509CertificateHolder) { certs.add(certConverter.getCertificate((X509CertificateHolder) object)); } } if (certs.isEmpty()) throw new Exception("Certificate file contained no certificates."); KeyStore ks = KeyStore.getInstance("jks"); ks.load(null); ks.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), certs.toArray(new Certificate[certs.size()])); return ks; }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testNonRepudiationSignaturePPDU() throws Exception { CCID.riskPPDU(true);// w w w.j av a2 s. com Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(signPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature"); assertNotNull(signCertificateChain); }
From source file:it.eng.spagobi.tools.scheduler.dispatcher.UniqueMailDocumentDispatchChannel.java
/** AFter all files are stored in temporary tabe takes them and sens as zip or as separate attachments * /*from www . ja v a2s. com*/ * @param mailOptions * @return */ public boolean sendFiles(Map<String, Object> mailOptions) { logger.debug("IN"); try { final String DEFAULT_SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; final String CUSTOM_SSL_FACTORY = "it.eng.spagobi.commons.services.DummySSLSocketFactory"; String tempFolderPath = (String) mailOptions.get(TEMP_FOLDER_PATH); File tempFolder = new File(tempFolderPath); if (!tempFolder.exists() || !tempFolder.isDirectory()) { logger.error("Temp Folder " + tempFolderPath + " does not exist or is not a directory: stop sending mail"); return false; } String smtphost = null; String pass = null; String smtpssl = null; String trustedStorePath = null; String user = null; String from = null; int smtpPort = 25; try { smtphost = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtphost"); String smtpportS = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.smtpport"); smtpssl = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.useSSL"); logger.debug(smtphost + " " + smtpportS + " use SSL: " + smtpssl); //Custom Trusted Store Certificate Options trustedStorePath = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.trustedStore.file"); if ((smtphost == null) || smtphost.trim().equals("")) throw new Exception("Smtp host not configured"); if ((smtpportS == null) || smtpportS.trim().equals("")) { throw new Exception("Smtp host not configured"); } else { smtpPort = Integer.parseInt(smtpportS); } from = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.from"); if ((from == null) || from.trim().equals("")) from = "spagobi.scheduler@eng.it"; user = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.user"); if ((user == null) || user.trim().equals("")) { logger.debug("Smtp user not configured"); user = null; } // throw new Exception("Smtp user not configured"); pass = SingletonConfig.getInstance().getConfigValue("MAIL.PROFILES.scheduler.password"); if ((pass == null) || pass.trim().equals("")) { logger.debug("Smtp password not configured"); } // throw new Exception("Smtp password not configured"); } catch (Exception e) { logger.error("Some E-mail configuration not set in table sbi_config: check you have all settings.", e); throw new Exception( "Some E-mail configuration not set in table sbi_config: check you have all settings."); } String mailSubj = mailOptions.get(MAIL_SUBJECT) != null ? (String) mailOptions.get(MAIL_SUBJECT) : null; Map parametersMap = mailOptions.get(PARAMETERS_MAP) != null ? (Map) mailOptions.get(PARAMETERS_MAP) : null; mailSubj = StringUtilities.substituteParametersInString(mailSubj, parametersMap, null, false); String mailTxt = mailOptions.get(MAIL_TXT) != null ? (String) mailOptions.get(MAIL_TXT) : null; String[] recipients = mailOptions.get(RECIPIENTS) != null ? (String[]) mailOptions.get(RECIPIENTS) : null; //Set the host smtp address Properties props = new Properties(); props.put("mail.smtp.host", smtphost); props.put("mail.smtp.p ort", Integer.toString(smtpPort)); // open session Session session = null; // create autheticator object Authenticator auth = null; if (user != null) { auth = new SMTPAuthenticator(user, pass); props.put("mail.smtp.auth", "true"); //SSL Connection if (smtpssl.equals("true")) { Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider()); //props.put("mail.smtp.debug", "true"); props.put("mail.smtps.auth", "true"); props.put("mail.smtps.socketFactory.port", Integer.toString(smtpPort)); if ((!StringUtilities.isEmpty(trustedStorePath))) { /* Dynamic configuration of trustedstore for CA * Using Custom SSLSocketFactory to inject certificates directly from specified files */ //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", CUSTOM_SSL_FACTORY); } else { //System.setProperty("java.security.debug","certpath"); //System.setProperty("javax.net.debug","ssl "); props.put("mail.smtps.socketFactory.class", DEFAULT_SSL_FACTORY); } props.put("mail.smtp.socketFactory.fallback", "false"); } //session = Session.getDefaultInstance(props, auth); session = Session.getInstance(props, auth); //session.setDebug(true); //session.setDebugOut(null); logger.info("Session.getInstance(props, auth)"); } else { //session = Session.getDefaultInstance(props); session = Session.getInstance(props); logger.info("Session.getInstance(props)"); } // create a message Message msg = new MimeMessage(session); // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); InternetAddress[] addressTo = new InternetAddress[recipients.length]; for (int i = 0; i < recipients.length; i++) { addressTo[i] = new InternetAddress(recipients[i]); } msg.setRecipients(Message.RecipientType.TO, addressTo); // Setting the Subject and Content Type String subject = mailSubj; String nameSuffix = mailOptions.get(NAME_SUFFIX) != null ? (String) mailOptions.get(NAME_SUFFIX) : null; Boolean reportNameInSubject = mailOptions.get(REPORT_NAME_IN_SUBJECT) != null && !mailOptions.get(REPORT_NAME_IN_SUBJECT).toString().equals("") ? (Boolean) mailOptions.get(REPORT_NAME_IN_SUBJECT) : null; //Boolean descriptionSuffix =mailOptions.get(DESCRIPTION_SUFFIX) != null && !mailOptions.get(DESCRIPTION_SUFFIX).toString().equals("")? (Boolean) mailOptions.get(DESCRIPTION_SUFFIX) : null; String zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; String contentType = mailOptions.get(CONTENT_TYPE) != null ? (String) mailOptions.get(CONTENT_TYPE) : null; String fileExtension = mailOptions.get(FILE_EXTENSION) != null ? (String) mailOptions.get(FILE_EXTENSION) : null; if (reportNameInSubject) { subject += " " + nameSuffix; } msg.setSubject(subject); // create and fill the first message part MimeBodyPart mbp1 = new MimeBodyPart(); mbp1.setText(mailTxt); // attach the file to the message boolean isZipDocument = mailOptions.get(IS_ZIP_DOCUMENT) != null ? (Boolean) mailOptions.get(IS_ZIP_DOCUMENT) : false; zipFileName = mailOptions.get(ZIP_FILE_NAME) != null ? (String) mailOptions.get(ZIP_FILE_NAME) : "Zipped Documents"; // create the Multipart and add its parts to it Multipart mp = new MimeMultipart(); mp.addBodyPart(mbp1); if (isZipDocument) { logger.debug("Make zip"); // create the second message part MimeBodyPart mbp2 = new MimeBodyPart(); mbp2 = zipAttachment(zipFileName, mailOptions, tempFolder); mp.addBodyPart(mbp2); } else { logger.debug("Attach single files"); SchedulerDataSource sds = null; MimeBodyPart bodyPart = null; try { String[] entries = tempFolder.list(); for (int i = 0; i < entries.length; i++) { logger.debug("Attach file " + entries[i]); File f = new File(tempFolder + File.separator + entries[i]); byte[] content = getBytesFromFile(f); bodyPart = new MimeBodyPart(); sds = new SchedulerDataSource(content, contentType, entries[i]); //sds = new SchedulerDataSource(content, contentType, entries[i] + fileExtension); bodyPart.setDataHandler(new DataHandler(sds)); bodyPart.setFileName(sds.getName()); mp.addBodyPart(bodyPart); } } catch (Exception e) { logger.error("Error while attaching files", e); } } // add the Multipart to the message msg.setContent(mp); logger.debug("Preparing to send mail"); // send message if ((smtpssl.equals("true")) && (!StringUtilities.isEmpty(user)) && (!StringUtilities.isEmpty(pass))) { logger.debug("Smtps mode active user " + user); //USE SSL Transport comunication with SMTPS Transport transport = session.getTransport("smtps"); transport.connect(smtphost, smtpPort, user, pass); transport.sendMessage(msg, msg.getAllRecipients()); transport.close(); } else { logger.debug("Smtp mode"); //Use normal SMTP Transport.send(msg); } // logger.debug("delete tempFolder path "+tempFolder.getPath()); // boolean deleted = tempFolder.delete(); // logger.debug("Temp folder deleted "+deleted); } catch (Exception e) { logger.error("Error while sending schedule result mail", e); return false; } finally { logger.debug("OUT"); } return true; }
From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java
@Test public void testPublishViaSOAPAttachment() throws Exception { // STS/*from w w w .j av a 2 s.co m*/ EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService"); Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12"); FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path()); eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray()); Enumeration<String> aliasesEnum = eHealthKeyStore.aliases(); String alias = aliasesEnum.nextElement(); X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias); PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias, this.config.getEHealthPKCS12Password().toCharArray()); List<Attribute> attributes = new LinkedList<Attribute>(); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>(); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin")); attributeDesignators .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin")); attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth", "urn:be:fgov:person:ssin:nurse:boolean")); Element assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate, eHealthPrivateKey, attributes, attributeDesignators); assertNotNull(assertion); String assertionString = client.toString(assertion); // eHealthBox publication EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient( "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3"); ObjectFactory objectFactory = new ObjectFactory(); PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType(); String publicationId = UUID.randomUUID().toString().substring(1, 13); LOG.debug("publication id: " + publicationId); publicationMessage.setPublicationId(publicationId); DestinationContextType destinationContext = objectFactory.createDestinationContextType(); publicationMessage.getDestinationContext().add(destinationContext); destinationContext.setQuality("NURSE"); destinationContext.setType("INSS"); destinationContext.setId(getUserIdentifier(authnCertificate)); ContentContextType contentContext = objectFactory.createContentContextType(); publicationMessage.setContentContext(contentContext); PublicationContentType publicationContent = objectFactory.createPublicationContentType(); contentContext.setContent(publicationContent); PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType(); publicationContent.setDocument(publicationDocument); publicationDocument.setTitle("test"); publicationDocument.setMimeType("application/octet-stream"); publicationDocument.setDownloadFileName("test.dat"); byte[] message = "hello world".getBytes(); DataSource dataSource = new ByteArrayDataSource(message, "application/octet-stream"); DataHandler dataHandler = new DataHandler(dataSource); publicationDocument.setEncryptableBinaryContent(dataHandler); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256"); byte[] digest = messageDigest.digest(message); publicationDocument.setDigest(Base64.encodeBase64String(digest)); ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType(); contentContext.setContentSpecification(contentSpecification); contentSpecification.setContentType("DOCUMENT"); publicationClient.setCredentials(eHealthPrivateKey, assertionString); publicationClient.publish(publicationMessage); }