use of com.helger.phase4.crypto.IAS4CryptoFactory in project phase4 by phax.
the class AS4BidirectionalClientHelper method sendAS4UserMessageAndReceiveAS4SignalMessage.
public static void sendAS4UserMessageAndReceiveAS4SignalMessage(@Nonnull final IAS4CryptoFactory aCryptoFactory, @Nonnull final IPModeResolver aPModeResolver, @Nonnull final IAS4IncomingAttachmentFactory aIAF, @Nonnull final IAS4IncomingProfileSelector aIncomingProfileSelector, @Nonnull final AS4ClientUserMessage aClientUserMsg, @Nonnull final Locale aLocale, @Nonnull final String sURL, @Nullable final IAS4ClientBuildMessageCallback aBuildMessageCallback, @Nullable final IAS4OutgoingDumper aOutgoingDumper, @Nullable final IAS4IncomingDumper aIncomingDumper, @Nullable final IAS4RetryCallback aRetryCallback, @Nullable final IAS4RawResponseConsumer aResponseConsumer, @Nullable final IAS4SignalMessageConsumer aSignalMsgConsumer) throws IOException, Phase4Exception, WSSecurityException, MessagingException {
if (LOGGER.isInfoEnabled())
LOGGER.info("Sending AS4 UserMessage to '" + sURL + "' with max. " + aClientUserMsg.httpRetrySettings().getMaxRetries() + " retries");
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(" ServiceType = '" + aClientUserMsg.getServiceType() + "'");
LOGGER.debug(" Service = '" + aClientUserMsg.getServiceValue() + "'");
LOGGER.debug(" Action = '" + aClientUserMsg.getAction() + "'");
LOGGER.debug(" ConversationId = '" + aClientUserMsg.getConversationID() + "'");
LOGGER.debug(" MessageProperties:");
for (final Ebms3Property p : aClientUserMsg.ebms3Properties()) LOGGER.debug(" [" + p.getName() + "] = [" + p.getValue() + "]");
LOGGER.debug(" Attachments (" + aClientUserMsg.attachments().size() + "):");
for (final WSS4JAttachment a : aClientUserMsg.attachments()) {
LOGGER.debug(" [" + a.getId() + "] with [" + a.getMimeType() + "] and [" + a.getCharsetOrDefault(null) + "] and [" + a.getCompressionMode() + "] and [" + a.getContentTransferEncoding() + "]");
}
}
final Wrapper<HttpResponse> aWrappedResponse = new Wrapper<>();
final ResponseHandler<byte[]> aResponseHdl = aHttpResponse -> {
// throws an ExtendedHttpResponseException on exception
final HttpEntity aEntity = ResponseHandlerHttpEntity.INSTANCE.handleResponse(aHttpResponse);
if (aEntity == null)
return null;
aWrappedResponse.set(aHttpResponse);
return EntityUtils.toByteArray(aEntity);
};
final AS4ClientSentMessage<byte[]> aResponseEntity = aClientUserMsg.sendMessageWithRetries(sURL, aResponseHdl, aBuildMessageCallback, aOutgoingDumper, aRetryCallback);
if (LOGGER.isInfoEnabled())
LOGGER.info("Successfully transmitted AS4 UserMessage with message ID '" + aResponseEntity.getMessageID() + "' to '" + sURL + "'");
if (aResponseConsumer != null)
aResponseConsumer.handleResponse(aResponseEntity);
// Try interpret result as SignalMessage
if (aResponseEntity.hasResponse() && aResponseEntity.getResponse().length > 0) {
final IAS4IncomingMessageMetadata aMessageMetadata = new AS4IncomingMessageMetadata(EAS4MessageMode.RESPONSE).setRemoteAddr(sURL);
// Read response as EBMS3 Signal Message
// Read it in any case to ensure signature validation etc. happens
final Ebms3SignalMessage aSignalMessage = AS4IncomingHandler.parseSignalMessage(aCryptoFactory, aPModeResolver, aIAF, aIncomingProfileSelector, aClientUserMsg.getAS4ResourceHelper(), aClientUserMsg.getPMode(), aLocale, aMessageMetadata, aWrappedResponse.get(), aResponseEntity.getResponse(), aIncomingDumper);
if (aSignalMessage != null && aSignalMsgConsumer != null)
aSignalMsgConsumer.handleSignalMessage(aSignalMessage);
} else
LOGGER.info("AS4 ResponseEntity is empty");
}
use of com.helger.phase4.crypto.IAS4CryptoFactory in project phase4 by phax.
the class MainPhase4PeppolSenderInMemoryKeyStore method main.
public static void main(final String[] args) {
WebScopeManager.onGlobalBegin(MockServletContext.create());
try {
final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/base-example.xml")).getDocumentElement();
if (aPayloadElement == null)
throw new IllegalStateException("Failed to read XML file to be send");
// Start configuring here
final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9914:atu68241501");
final KeyStore aKS = KeyStoreHelper.loadKeyStoreDirect(EKeyStoreType.PKCS12, "test-ap.p12", "peppol");
if (aKS == null)
throw new IllegalStateException();
final KeyStore aTS = KeyStoreHelper.loadKeyStoreDirect(EKeyStoreType.JKS, "complete-truststore.jks", "peppol");
if (aTS == null)
throw new IllegalStateException();
final IAS4CryptoFactory aInMemoryCryptoFactory = new AS4CryptoFactoryInMemoryKeyStore(aKS, "openpeppol aisbl id von pop000306", "peppol", aTS);
final ESimpleUserMessageSendResult eResult;
eResult = Phase4PeppolSender.builder().documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).validationConfiguration(PeppolValidation3_13_0.VID_OPENPEPPOL_INVOICE_V3, new Phase4PeppolValidatonResultHandler()).cryptoFactory(aInMemoryCryptoFactory).sendMessageAndCheckForReceipt();
LOGGER.info("Peppol send result: " + eResult);
} catch (final Exception ex) {
LOGGER.error("Error sending Peppol message via AS4", ex);
} finally {
WebScopeManager.onGlobalEnd();
}
}
use of com.helger.phase4.crypto.IAS4CryptoFactory in project phase4 by phax.
the class MainPhase4PeppolSenderQvalia method main.
public static void main(final String[] args) {
WebScopeManager.onGlobalBegin(MockServletContext.create());
// Dump (for debugging purpose only)
AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
try {
final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/base-example.xml")).getDocumentElement();
if (aPayloadElement == null)
throw new IllegalStateException("Failed to read XML file to be send");
// Start configuring here
final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {
public void onAS4Message(final AbstractAS4Message<?> aMsg) {
final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
LOGGER.info("Sending out AS4 message with conversation ID '" + aUserMsg.getEbms3UserMessage().getCollaborationInfo().getConversationId() + "'");
}
};
// Invalid certificate is valid until 2029
final IAS4CryptoFactory cf = true ? AS4CryptoFactoryProperties.getDefaultInstance() : new AS4CryptoFactoryInMemoryKeyStore(KeyStoreHelper.loadKeyStoreDirect(EKeyStoreType.JKS, "invalid-keystore-pw-peppol.jks", "peppol"), "1", "peppol", KeyStoreHelper.loadKeyStore(PeppolKeyStoreHelper.TRUSTSTORE_TYPE, PeppolKeyStoreHelper.Config2018.TRUSTSTORE_PRODUCTION_CLASSPATH, PeppolKeyStoreHelper.TRUSTSTORE_PASSWORD).getKeyStore());
final ESimpleUserMessageSendResult eResult;
eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).cryptoFactory(cf).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).smpClient(new SMPClientReadOnly(Phase4PeppolSender.URL_PROVIDER, aReceiverID, ESML.DIGIT_TEST)).rawResponseConsumer(new AS4RawResponseConsumerWriteToFile()).validationConfiguration(PeppolValidation3_13_0.VID_OPENPEPPOL_INVOICE_V3, new Phase4PeppolValidatonResultHandler()).buildMessageCallback(aBuildMessageCallback).sendMessageAndCheckForReceipt();
LOGGER.info("Peppol send result: " + eResult);
} catch (final Exception ex) {
LOGGER.error("Error sending Peppol message via AS4", ex);
} finally {
WebScopeManager.onGlobalEnd();
}
}
use of com.helger.phase4.crypto.IAS4CryptoFactory in project phase4 by phax.
the class MainPhase4PeppolSenderQvaliaConstantReceiver method main.
public static void main(final String[] args) {
WebScopeManager.onGlobalBegin(MockServletContext.create());
// Dump (for debugging purpose only)
AS4DumpManager.setIncomingDumper(new AS4IncomingDumperFileBased());
AS4DumpManager.setOutgoingDumper(new AS4OutgoingDumperFileBased());
try {
final Element aPayloadElement = DOMReader.readXMLDOM(new File("src/test/resources/examples/base-example.xml")).getDocumentElement();
if (aPayloadElement == null)
throw new IllegalStateException("Failed to read XML file to be send");
// Start configuring here
final IParticipantIdentifier aReceiverID = Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("0007:5567321707");
final IAS4ClientBuildMessageCallback aBuildMessageCallback = new IAS4ClientBuildMessageCallback() {
public void onAS4Message(final AbstractAS4Message<?> aMsg) {
final AS4UserMessage aUserMsg = (AS4UserMessage) aMsg;
LOGGER.info("Sending out AS4 message with message ID '" + aUserMsg.getEbms3UserMessage().getMessageInfo().getMessageId() + "'");
}
};
final IAS4CryptoFactory cf = AS4CryptoFactoryProperties.getDefaultInstance();
final ESimpleUserMessageSendResult eResult;
eResult = Phase4PeppolSender.builder().httpRetrySettings(new HttpRetrySettings().setMaxRetries(0)).cryptoFactory(cf).documentTypeID(Phase4PeppolSender.IF.createDocumentTypeIdentifierWithDefaultScheme("urn:oasis:names:specification:ubl:schema:xsd:Invoice-2::Invoice##urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0::2.1")).processID(Phase4PeppolSender.IF.createProcessIdentifierWithDefaultScheme("urn:fdc:peppol.eu:2017:poacc:billing:01:1.0")).senderParticipantID(Phase4PeppolSender.IF.createParticipantIdentifierWithDefaultScheme("9915:phase4-test-sender")).receiverParticipantID(aReceiverID).senderPartyID("POP000306").payload(aPayloadElement).receiverEndpointDetails(CertificateHelper.convertStringToCertficate("-----BEGIN CERTIFICATE-----\r\n" + "MIIFxzCCA6+gAwIBAgIQTJRiSywVkdw+JqmDB29xYjANBgkqhkiG9w0BAQsFADBr MQswCQYDVQQGEwJCRTEZMBcGA1UEChMQT3BlblBFUFBPTCBBSVNCTDEWMBQGA1UE CxMNRk9SIFRFU1QgT05MWTEpMCcGA1UEAxMgUEVQUE9MIEFDQ0VTUyBQT0lOVCBU RVNUIENBIC0gRzIwHhcNMjAwODIxMDAwMDAwWhcNMjIwODExMjM1OTU5WjBUMRIw EAYDVQQDDAlQU0UwMDAwOTQxFzAVBgNVBAsMDlBFUFBPTCBURVNUIEFQMRgwFgYD VQQKDA9RdmFsaWEgR3JvdXAgQUIxCzAJBgNVBAYTAlNFMIIBIjANBgkqhkiG9w0B AQEFAAOCAQ8AMIIBCgKCAQEArMPej9tY7q6Yf1X3ki4yDcMIuVBrBvwEluXxBoLI C02BeGA2gFln2gGz/2ydFF1hokW5rmoUrJwHT2WoxHK2evvbiyDIOh3ULNKD5Qml XMZMPOHrMth0r3v0Fuvvl8t88pcB2zJxmysHa+Y0HDb6O2W9uZssMZr25eKPb3p+ /qUe0/UoAsPW+u7mhjZdjIsUz+MtYlUyAedcQptM6uh18f6eR2mL0mnp0V2jeBH9 s8YVxh4YoL3pfFVEYGXR/KoRrTdz2CMDhDjO+A4sUsidr7C5gy1CKTUKxUHoensA 0KJKMIJ3ZetslMnizSP2Y7600N8ry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xT6nM5pw5ZPvqIS0h4lOTWCq5Y5j2aXmo23trDfMoWqRncOlX18cnAThlnT2 RydPPOVrcFk4JehM2oRgm3ldo+Pj4lhQQ5WnBdX9o7yvnZhn96KyVqiMU25TDf6M JNLrljdeiEAl3pNsqzXSJ7nREhWzVI2IWe+NXEOUN3z7PgeKH0sh2KdS7g==" + "-----END CERTIFICATE-----\r\n" + ""), "https://peppol-ap-test.qvalia.com/peppol/as4").validationConfiguration(PeppolValidation3_13_0.VID_OPENPEPPOL_INVOICE_V3, new Phase4PeppolValidatonResultHandler()).buildMessageCallback(aBuildMessageCallback).sendMessageAndCheckForReceipt();
LOGGER.info("Peppol send result: " + eResult);
} catch (final Exception ex) {
LOGGER.error("Error sending Peppol message via AS4", ex);
} finally {
WebScopeManager.onGlobalEnd();
}
}
use of com.helger.phase4.crypto.IAS4CryptoFactory in project phase4 by phax.
the class AS4Signer method _createSignedMessage.
@Nonnull
private static Document _createSignedMessage(@Nonnull final IAS4CryptoFactory aCryptoFactory, @Nonnull final Document aPreSigningMessage, @Nonnull final ESoapVersion eSoapVersion, @Nonnull @Nonempty final String sMessagingID, @Nullable final ICommonsList<WSS4JAttachment> aAttachments, @Nonnull @WillNotClose final AS4ResourceHelper aResHelper, final boolean bMustUnderstand, @Nonnull final AS4SigningParams aSigningParams) throws WSSecurityException {
ValueEnforcer.notNull(aCryptoFactory, "CryptoFactory");
ValueEnforcer.notNull(aPreSigningMessage, "PreSigningMessage");
ValueEnforcer.notNull(eSoapVersion, "SoapVersion");
ValueEnforcer.notEmpty(sMessagingID, "MessagingID");
ValueEnforcer.notNull(aResHelper, "ResHelper");
ValueEnforcer.notNull(aSigningParams, "SigningParams");
if (LOGGER.isInfoEnabled())
LOGGER.info("Now signing AS4 message");
// Start signing the document
final WSSecHeader aSecHeader = new WSSecHeader(aPreSigningMessage);
aSecHeader.insertSecurityHeader();
final WSSecSignature aBuilder = new WSSecSignature(aSecHeader);
aBuilder.setKeyIdentifierType(aSigningParams.getKeyIdentifierType().getTypeID());
// Set keystore alias and key password
aBuilder.setUserInfo(aCryptoFactory.getKeyAlias(), aCryptoFactory.getKeyPassword());
aBuilder.setSignatureAlgorithm(aSigningParams.getAlgorithmSign().getAlgorithmURI());
// PMode indicates the DigestAlgorithm as Hash Function
aBuilder.setDigestAlgo(aSigningParams.getAlgorithmSignDigest().getAlgorithmURI());
aBuilder.setSigCanonicalization(aSigningParams.getAlgorithmC14N().getAlgorithmURI());
// Sign the Ebms3 Messaging element itself
aBuilder.getParts().add(new WSEncryptionPart(sMessagingID, "Content"));
// Sign the SOAP body
aBuilder.getParts().add(new WSEncryptionPart("Body", eSoapVersion.getNamespaceURI(), "Content"));
if (CollectionHelper.isNotEmpty(aAttachments)) {
// Modify builder for attachments
// "cid:Attachments" is a predefined ID used inside WSSecSignatureBase
aBuilder.getParts().add(new WSEncryptionPart(MessageHelperMethods.PREFIX_CID + "Attachments", "Content"));
final WSS4JAttachmentCallbackHandler aAttachmentCallbackHandler = new WSS4JAttachmentCallbackHandler(aAttachments, aResHelper);
aBuilder.setAttachmentCallbackHandler(aAttachmentCallbackHandler);
}
// Set the mustUnderstand header of the wsse:Security element as well
final Attr aMustUnderstand = aSecHeader.getSecurityHeaderElement().getAttributeNodeNS(eSoapVersion.getNamespaceURI(), "mustUnderstand");
if (aMustUnderstand != null)
aMustUnderstand.setValue(eSoapVersion.getMustUnderstandValue(bMustUnderstand));
return aBuilder.build(aCryptoFactory.getCrypto());
}
Aggregations