XML Signature with WSDL

Hello!!!
I created this topic also at Security forum, but i think that was a wrong choice
I need to consume Web Service (WSDL). It's working without any problem. But there is also one operation where I need to add Digitial Signature to it.
It is very hard to find any documentation how to configure signing XML messages in SAP. I was looking for SSF which should fit to my requriements. Then I found something like WS Security in LPCONFIG - but i don't know how to use it. I put there Profile OUT, but nothing happen. Could you give me some directions where to look for this?
To generate proxy i used SE80. I have only ABAP instance (but if there won't be any other choice i can install AS JAVA as well). No PI system in landscape.
Best regards
Rob

Are you doing digital signing transport level or message level?
Transport level:
if you do transport level then share the end system certificate in PI keystore and use https communication. Use Soap receiver adapter.
Message level:
If you need to message level digital signature then you might want to explore WS adapter. THis adapter supports digital signing as well WS Reliable Messaging Protocol. You have to configure WS adapter as receiver for this.  Refer SAP help document on WS adapter for this. If there is a limitation to use WS adapter on this area, then you might have to do java mapping using Apache Axis software for digital signing. This requires more java effort.

Similar Messages

  • XML Signature with Barcoded Form

    I have a form that has a number of fields that need to be filled out. When this is complete, the user should digitally sign (with a certificate) the form. However, due to legal requirements, the form must then be printed and mailed back to the organization. Is it possible to encode the signature data within the barcode (PDF417) so it can be validated?

    After finding the sign function and playing around with the resulting XML Signature, I've found it's just too much data to put in a barcode, even a 2D one.

  • Generating XML signature with prefix dsig ?

    Hi everyone,
    I'm facing a problem generating a signature of XML document. I'm using Jwsdp and the apache toolkit. So far, I can generate the signature of this form :
    <Signature>
    <SignedInfo> .....
    I would like to generate the signature like this :
    <dsig:Signature>
    <dsig:SignedInfo> ....
    The API doesn't specify how to add the prefix dsig befor tags element ...
    It's very important for me to solve the problem, so any help would be really really appreciated :-)
    Thanks a lot.

    There is a method in DOMSignContext to do that:
    // org.w3c.dom.Document doc;
    DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement());
    dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");  // or "ds" which is my case

  • Problem with XML signature

    Can anybody tell me how to generate an xml signature
    with the base 64 transform(Transform.BASE64)?
    I just can't find any documentation on the web.
    It would be great to provide a small code exemple.
    Thanks
    Antoine

    Thanks for the reply.
    I'm applying appropriate namespaces to the generated xml string. Could it be the probelem?
    this is how the generated xml looks in final stage, I mean after I'm doing some rework on the generated xml.
    <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><Reference URI="#PAYMENTS"><Transforms><Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><DigestValue>IXgHx5ioixsJ13jyg767D8UCU9s=</DigestValue></Reference></SignedInfo><SignatureValue>DO+Fngf3h0Q5iDoMq2mZFL+bxL3vY1i1fyqzBbKRPhHlzqWrW2wP3SFHjVzPLXdj92W8hMx9I8Jq
    QBV/D+pUKa32aZB7kPwOGZqR63X+d6Hca58jnTK7+zq8Fzi2DPlE+omQhgT3xeXp/lQpKI8vAgVT
    eX+eylRYTAZDSfDw7qk=</SignatureValue><Object Id="PAYMENTS"><PAYMENTS xmlns=""><Payment><PaymentIdA></PaymentIdA><PaymentIdB>aa</PaymentIdB><SrcBank>bb</SrcBank><SrcAccount>cc</SrcAccount><PayerId>dd</PayerId><PayerName>Dato</PayerName><TaxPayerId>00022023</TaxPayerId><TaxPayerName></TaxPayerName><ReceiverName>mof</ReceiverName><AdditinalInfo>racxa</AdditinalInfo><Amount>521</Amount><TreasuryCode>hello</TreasuryCode><PaymentTime>hi</PaymentTime><PaymentChannel>ib</PaymentChannel></Payment></PAYMENTS></Object></Signature>

  • Web Service Security with SAML - Invalid XML signature

    Hello together,
    we want to build a scenario where we want to use Web Service Security  with SAML.
    The scenario will be
    WS Client (Java Application) -> WS Adapter -> Integration Engine ->  WS Adapter-> CRM (Web AS ABAP 7.01 SP 3)
    SAP PI release is 7.11 (SP Level 4)
    We want to use the SAML Authentification from WS Client to PI and from PI to Web AS ABAP.
    The SAML authentifications between the WS Client and PI works when there is no SAML auth between PI and CRM.
    But we get following error at calling the CRM system when we want to communicate with SAML:
      <E_TEXT>CX_WS_SECURITY_FAULT:Invalid XML signature</E_TEXT>
    Has somebody an idea of the possible reason for the error.
    Thanks in advance
    Stefan

    Error Messages in the Trace/Log Viewer:
    CX_WS_SECURITY_FAULT : Invalid XML signature | program: CL_ST_CRYPTO==================CP include: CL_ST_CRYPTO==================CM00G line: 48
    A SOAP Runtime Core Exception occurred in method CL_ST_CRYPTO==================CM00G of class CL_ST_CRYPTO==================CP at position id 48  with internal error id 1001  and error text CX_WS_SECURITY_FAULT:Invalid XML signature (fault location is 1  ).
    Invalid XML signature

  • Loading Invoice XML IDoc with digital signature via XI into R/3

    Hi,
    I received an Invoice XML IDoc with digital signature via Mail (for test purposes) and want to load it via XI into an R/3 systeme.
    My idea is to load the Invoice XML IDoc file via the File Sender Adapter into XI and send it to the R/3 system via the IDoc Inbound adapter.
    Due to the digital signature the file looks like this:
    0‚ S      *†H†÷
        ‚ D0‚ @   1 0       +      0‚ '      *†H†÷
        ‚   ‚   ‚ –0‚ ’0‚ û      etc.
    When I load the file like this with the File Sender Adapter, an error message occurs in the XI Monitoring as the XML Parser cannot read the file due to the digital signatur (as expected).
    Has anybody an idea how I can configure the File Sender Adapter Communication Channel to be able to load only the XML IDoc and ignore the digital Signature strings?
    Thanks in advance for your support.
    Alex

    BTW
    do use the second way you need:
    Security Settings for the Sender Mail Adapter
    http://help.sap.com/saphelp_nw04/helpdata/en/27/c0524257a1b56be10000000a155106/content.htm
    and
    Key Storage Service
    http://help.sap.com/saphelp_webas630/helpdata/DE/e9/a1dd44d2c83c43afb5ec8a4292f3e0/content.htm
    apart from adapter module config
    Regards,
    michal

  • Transforming signed XML document with namespace invalidates signature

    I am running into a problem signing an XML document. Well, signing the document isn't the problem, as I can sign it and then verify the signature with the public key successfully. The problem comes when I transform the document to a string. It all appears to be OK, but when I transform it back, the hash no longer verifies. After more testing, it appears that the issue is related to namespaces. When I remove namespaces from the document, the signing and transformations work just fine. Does anyone have any insight on this?
    Here is how I am transforming the document to an XML string that I and back.
        try
          signSAML( doc, assertionElement );
          xmlSource = new DOMSource( doc );
          baos = new ByteArrayOutputStream();
          outputTarget = new StreamResult( baos );
          xmlString  = new String( new ByteArrayInputStream( baos.toByteArray() ) );
          transformerFactory = TransformerFactory.newInstance();
          transformer = transformerFactory.newTransformer();
          transformer.transform( xmlSource, outputTarget ); 
          boolean verified = verify( doc );
          if ( verified )
            System.out.println( "Verified" );
          else
            System.out.println( "UNVerified" );
        catch ( Exception e )
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

    jtahlborn wrote:
    i'm not talking about the transform, i'm talking about this line:
    xmlString  = new String( new ByteArrayInputStream( baos.toByteArray() ) );which is a great way to break xml data.Yes. That's not the only kind of data it's good at breaking, either.
    To the OP: just have your transform output to a StringWriter in the first place. Don't muck about converting between chars and bytes unless you know the correct encoding and use it. Which you don't know it and you didn't use it.

  • MTOM combined with WS-Security (XML signature)

    I'm testing the support of MTOM together with WS-Security (XML-DSIG) on OEG. When verifying the XML signature I noticed I had to add the "Insert MTOM attachments"-filter first. Is this the right way? Shouldn't the signature verification do this transparently?
    My other question is how OEG handles the attachments? Does it page them to disk? What happens if my attachments are very large? With the default setup of OEG I encountered out-of-memory issues with attachments above 200MB
    Edited by: wsalembi on Sep 22, 2011 12:45 AM

    If you just sign the <xop:Include> element, you are effectively only signing the reference to the attachment, i.e. the value of the href attribute. This will only prevent someone changing the href to point to a different attachment.
    If you in-line the base64 encoded contents of the attachment into the XML message and only sign the base64 encoded string, you are only preventing anyone from changing the contents of the attachment.
    You are not stopping somebody from changing what the <xop:Include> href attribute points to.
    So I think there is value in signing BOTH the contents AND the <xop:Include> element so that:
    - The integrity of the contents of the attachment is ensured, and
    - The integrity of the reference to the attachment in the <xop:Include> element is ensured.
    Interestingly, the XOP spec acknowledges this issue in Section 6.1:
    http://www.w3.org/TR/xop10/#package_integrity
    6.1 XOP Package Integrity
    The integrity of Infosets optimized using XOP may need to be ensured. As XOP packages can be transformed to recover such Infosets (see 3.2 Interpreting XOP Packages), existing XML Digital Signature techniques can be used to protect them. Note, however, that a signature over the Infoset does not necessarily protect against modifications of other aspects of the XOP packaging; for example, an Infoset signature check might not protect against re-ordering of non-root parts.
    In the future a transform algorithm for use with XML Signature could provide a more efficient processing model where the raw octets are digested directly.
    In OEG, it would be possible to use 2 XML Signature Validation filters with an Insert MTOM Attachment filter to validate both signatures.
    The flow in the policy would be as follows:
    1. 1st XML Signature Filter :- Validate the Signature over the <xop:Include> element
    2. Insert MTOM Attachment Filter :- Inline the base64 encoded contents of the attachment
    3. 2nd XML Signature Filter :- Validate the Signature over the element now containing the in-lined base64 encoded data.
    This policy would ensure the integrity of the attachment contents AND the reference to this attachment in the <xop:Include> element.

  • Problem in XML Signature

    Hi,
    i get an Exception in Registering mechanism for XML Signature factory
    it says.
    javax.xml.crypto.NoSuchMechanismException : Cannot find DOM Mechanism type
    I use J2sdk1.4.2_05 with JWSDP 1.4
    Following is the code do let me know where i go wrong.
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import javax.xml.crypto.dsig.XMLSignatureFactory;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.XMLSignatureFactory;
    import javax.xml.crypto.dsig.Reference;
    import javax.xml.crypto.dsig.SignedInfo;
    import javax.xml.crypto.dsig.XMLSignature;
    import javax.xml.crypto.dsig.CanonicalizationMethod;
    import javax.xml.crypto.dsig.Transform;
    import javax.xml.crypto.dsig.DigestMethod;
    import javax.xml.crypto.dsig.SignatureMethod;
    import javax.xml.crypto.*;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dom.*;
    import java.security.Provider;
    import javax.xml.crypto.dsig.keyinfo.KeyInfo;
    import javax.xml.crypto.dsig.keyinfo.KeyValue;
    import java.security.KeyPairGenerator;
    import java.security.KeyPair;
    import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
    import java.io.FileInputStream;
    import java.util.Collections;
    //author Palani V. Rajan
    // SafeScrypt Ltd
    class XMLSign
    XMLSign(){}
    /*XMLSign(String inputFile)
    public void signTheMarkup(String inputFilePath)
    Document domDoc;
    try{
    System.out.println("Creating DOM");
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    domDoc = db.parse(new FileInputStream(inputFilePath));
    System.out.println("Generating Key's.....");
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();
    DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), domDoc.getDocumentElement());
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
    System.out.println("Creating xml sign.....");
    System.out.println("Provider Name "+providerName);
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",(Provider) Class.forName(providerName).newInstance());
    System.out.println("T 1");
    Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null),Collections.singletonList(fac.newTransform(Transform.ENVELOPED, null)),null, null);
    System.out.println("T 2");
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, null),fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),Collections.singletonList(ref));
    System.out.println("T 4");
    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(kp.getPublic());
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
    System.out.println("T 5");
    XMLSignature signature = fac.newXMLSignature(si, ki);
    signature.sign(dsc);
    }catch(Exception e){e.printStackTrace();}
    public static void main(String[] q)
    System.out.println("Creating XML Signatures.....");
    XMLSign xs = new XMLSign();
    xs.signTheMarkup(q[0]);
    Thnx in Advance
    Vinodh

    I have encountered the same problem. I am using Jbuilder 5 with JDK 1.3.0. I copied all the JAR files of jwsdp-1.5 by creating a custom library.
    Even then It didnt work. Can some one who has resolved this please help.
    I have tried running the same code in JDeveloper 10g (10.1.2) and got a same error.
    Regards,
    Srinivas.

  • Validating detached signature with jsr105

    Hi all.
    I need to sign a SOAP message and I need to use JSR105. I've created a message with the following code and is signed without problems. However, I can't validate the signature. As you can see the elements that contains the nodes are OMElement (specific for Axis2 SOAP server) that are an instance of Node and Element classes.
    The error I get is:
    Exception in thread "main" javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID 1
         at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(DOMReference.java:366)
         at org.jcp.xml.dsig.internal.dom.DOMReference.validate(DOMReference.java:318)
         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.validate(DOMXMLSignature.java:230)
         at SignedSoap.main(SignedSoap.java:272)
    Caused by: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID 1
         at org.jcp.xml.dsig.internal.dom.DOMURIDereferencer.dereference(DOMURIDereferencer.java:84)
         at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(DOMReference.java:358)
         ... 3 more
    Caused by: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID 1
         at com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment.engineResolve(Unknown Source)
         at com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver.resolve(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMURIDereferencer.dereference(DOMURIDereferencer.java:77)
         ... 4 more
    javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID 1
         at org.jcp.xml.dsig.internal.dom.DOMURIDereferencer.dereference(DOMURIDereferencer.java:84)
         at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(DOMReference.java:358)
         at org.jcp.xml.dsig.internal.dom.DOMReference.validate(DOMReference.java:318)
         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.validate(DOMXMLSignature.java:230)
         at SignedSoap.main(SignedSoap.java:272)
    Caused by: com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException: Cannot resolve element with ID 1
         at com.sun.org.apache.xml.internal.security.utils.resolver.implementations.ResolverFragment.engineResolve(Unknown Source)
         at com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver.resolve(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMURIDereferencer.dereference(DOMURIDereferencer.java:77)
         ... 4 more
    My code is as follows
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.Provider;
    import java.security.SecureRandom;
    import java.util.Calendar;
    import java.util.Collections;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dom.*;
    import javax.xml.crypto.dsig.dom.*;
    import javax.xml.crypto.dsig.keyinfo.*;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import javax.xml.soap.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.stream.*;
    import org.apache.axiom.om.OMAttribute;
    import org.apache.axiom.om.OMElement;
    import org.apache.axiom.om.OMNamespace;
    import org.apache.axiom.om.impl.dom.factory.OMDOMFactory;
    import org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader;
    import org.w3c.dom.*;
    import org.w3c.dom.Node;
    import org.xml.sax.InputSource;
    //import org.xmlsoap.schemas.soap.encoding.DateTime;
    * Construct a SOAP message, sign it and then validate the signature.
    * This implementation follows the
    * <a ref="http://www.w3.org/TR/SOAP-dsig/">
    * W3C Note on digital signatures in SOAP messages
    * </a>.
    * The validating key is included in the signature.
    * DOM Level 2 is used throughout.
    * <p>
    * The following SOAP message is signed:
    * <pre><code>
    * <?xml version="1.0" encoding="UTF-8"?>
    * <soap-env:Envelope
    * xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
    * <soap-env:Header>
    * <SOAP-SEC:Signature
    * mustUnderstand="1"
    * xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12"/>
    * </soap-env:Header>
    * <soap-env:Body id="Body">
    * <m:GetLastTradePrice xmlns:m="http://wombats.ztrade.com">
    * <symbol>SUNW</symbol>
    * </m:GetLastTradePrice>
    * </soap-env:Body>
    * </soap-env:Envelope>
    * </code></pre>
    public class SignedSoap {
    private static boolean debug = false;
    public static void main(String[] args) throws Exception {
         int argc = args.length;
         if (argc == 1) {
         if (args[0].equalsIgnoreCase("-help")) {
              System.out.println("Usage: SignedSoap [-debug]");
              System.out.println(" -debug\tactivates debug messages");
              return;
         debug = args[0].equalsIgnoreCase("-debug");
         // Create the SOAP message
         OMDOMFactory omfact=new OMDOMFactory();
         //Node nodo1=fd.newDomNode(options);
         OMNamespace namespace=omfact.createOMNamespace("http://schemas.xmlsoap.org/soap/security/2000-12", "soapenv");
         OMNamespace namespace2=omfact.createOMNamespace("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "wsu");
         OMAttribute attr=omfact.createOMAttribute("mustUnderstand",namespace,"1");
         OMAttribute id=omfact.createOMAttribute("id",namespace,"1");
         OMAttribute id2=omfact.createOMAttribute("id",namespace,"2");
         OMElement sec=omfact.createOMElement("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","wsse");
         OMElement timestamp=omfact.createOMElement("Timestamp",namespace2);
         OMElement created=omfact.createOMElement("Created",namespace2);
         OMElement expires=omfact.createOMElement("Expires",namespace2);
         created.setText("12122007");
         expires.setText("12122008");
         timestamp.addAttribute(id);
         timestamp.addChild(created);
         timestamp.addChild(expires);
         sec.addChild(timestamp);
         System.out.println("Generating the DOM tree...");
         // Get input source
         org.w3c.dom.Node security = (Node)sec;
         //if (debug) {
         // dumpDOMDocument(root);
         // Generate a DSA key pair
         System.out.println("Generating the DSA keypair...");
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
         kpg.initialize(1024, new SecureRandom("not so random".getBytes()));
         KeyPair keypair = kpg.generateKeyPair();
    // Assemble the signature parts
         System.out.println("Preparing the signature...");
         String providerName = System.getProperty
    ("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
         XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM",
    (Provider) Class.forName(providerName).newInstance());
    Reference ref = sigFactory.newReference("#1",
         sigFactory.newDigestMethod(DigestMethod.SHA1, null));
    SignedInfo signedInfo = sigFactory.newSignedInfo(
         sigFactory.newCanonicalizationMethod(
              CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
              (C14NMethodParameterSpec) null),
    sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
         Collections.singletonList(ref));
         KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
         KeyValue kv = kif.newKeyValue(keypair.getPublic());
    KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));
    XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);
         // Insert XML signature into DOM tree and sign
         System.out.println("Signing the SOAP message...");
         // Find where to insert signature
         Element ts = getFirstChildElement(envelope);
         DOMSignContext sigContext =
         new DOMSignContext(keypair.getPrivate(), sec);
         // Need to distinguish the Signature element in DSIG (from that in SOAP)
         sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
         // register Body ID attribute getNextSiblingElement(
         sigContext.setIdAttributeNS
         (ts,
         "http://schemas.xmlsoap.org/soap/security/2000-12","id");
         sig.sign(sigContext);
         if (debug) {
         dumpDOMDocument(envelope);
         // Validate the XML signature
    // Locate the signature element
         Element sigElement = getNextSiblingElement(ts);
    // Validate the signature using the public key generated above
    DOMValidateContext valContext =
         new DOMValidateContext(keypair.getPublic(), sigElement);
         // register Body ID attribute getNextSiblingElement(
         valContext.setIdAttributeNS
         (ts,
         "http://schemas.xmlsoap.org/soap/security/2000-12","id");
    boolean isValid = sig.validate(valContext);
         System.out.println("Validating the signature... " +
         (isValid ? "valid" : "invalid"));
    * Outputs DOM representation to the standard output stream.
    * @param root The DOM representation to be outputted
    private static void dumpDOMDocument(org.w3c.dom.Node root)
         throws TransformerException, TransformerConfigurationException {
         System.out.println("\n");
         // Create a new transformer object
         Transformer transformer =
         TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
         // Dump the DOM representation to standard output
         transformer.transform(new DOMSource(root), new StreamResult(System.out));
         System.out.println("\n");
    * Returns the first child element of the specified node, or null if there
    * is no such element.
    * @param node the node
    * @return the first child element of the specified node, or null if there
    *     is no such element
    * @throws NullPointerException if <code>node == null</code>
    private static Element getFirstChildElement(org.w3c.dom.Node node) {
         org.w3c.dom.Node child = node.getFirstChild();
         while (child != null &&
         child.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
    child = child.getNextSibling();
    return (Element) child;
    * Returns the next sibling element of the specified node, or null if there
    * is no such element.
    * @param node the node
    * @return the next sibling element of the specified node, or null if there
    *     is no such element
    * @throws NullPointerException if <code>node == null</code>
    public static Element getNextSiblingElement(org.w3c.dom.Node node) {
         org.w3c.dom.Node sibling = node.getNextSibling();
         while (sibling != null &&
         sibling.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
    sibling = sibling.getNextSibling();
    return (Element) sibling;
    Thanks in advance

    I've done further advancemets. It seems that the element to feed the sign validator MUST be a document AND that the ID attribute has to be registered in it even if has been already located in inner elements of the message. Now my code looks as follows but I'm not validating the reference. The sign itself can validate though.
    The problem is the reference validation. Any ideas? Could it be the prefixes or namespaces? I've been making tests changing both but no luck so far.
    Thanks in advance.
    package _2006_08.sa.liberty;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.Provider;
    import java.security.SecureRandom;
    import java.util.Calendar;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.xml.crypto.URIDereferencer;
    import javax.xml.crypto.URIReference;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dom.*;
    import javax.xml.crypto.dsig.dom.*;
    import javax.xml.crypto.dsig.keyinfo.*;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import javax.xml.soap.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.sax.SAXSource;
    import javax.xml.transform.stream.*;
    import org.apache.axiom.om.OMAttribute;
    import org.apache.axiom.om.OMElement;
    import org.apache.axiom.om.OMNamespace;
    import org.apache.axiom.om.impl.dom.factory.OMDOMFactory;
    import org.apache.xmlbeans.impl.piccolo.xml.XMLStreamReader;
    import org.oasis_open.docs.wss._2004._01.oasis_200401_wss_wssecurity_secext_1_0_xsd.SecurityDocument;
    import org.w3c.dom.*;
    import org.w3c.dom.Node;
    import org.xml.sax.InputSource;
    //import org.xmlsoap.schemas.soap.encoding.DateTime;
    * Construct a SOAP message, sign it and then validate the signature.
    * This implementation follows the
    * <a ref="http://www.w3.org/TR/SOAP-dsig/">
    * W3C Note on digital signatures in SOAP messages
    * </a>.
    * The validating key is included in the signature.
    * DOM Level 2 is used throughout.
    * <p>
    * The following SOAP message is signed:
    * <pre><code>
    * <?xml version="1.0" encoding="UTF-8"?>
    * <soap-env:Envelope
    * xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/">
    * <soap-env:Header>
    * <SOAP-SEC:Signature
    * mustUnderstand="1"
    * xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12"/>
    * </soap-env:Header>
    * <soap-env:Body id="Body">
    * <m:GetLastTradePrice xmlns:m="http://wombats.ztrade.com">
    * <symbol>SUNW</symbol>
    * </m:GetLastTradePrice>
    * </soap-env:Body>
    * </soap-env:Envelope>
    * </code></pre>
    public class SignedSoap {
    private static boolean debug = false;
    public static void main(String[] args) throws Exception {
         int argc = args.length;
         if (argc == 1) {
         if (args[0].equalsIgnoreCase("-help")) {
              System.out.println("Usage: SignedSoap [-debug]");
              System.out.println(" -debug\tactivates debug messages");
              return;
         debug = args[0].equalsIgnoreCase("-debug");
         // Create the SOAP message
         System.out.println("Creating the SOAP message...");
         SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
         SOAPPart soapPart = soapMessage.getSOAPPart();
         SOAPEnvelope soapEnvelope = soapPart.getEnvelope();
         if(soapEnvelope instanceof Source){
              System.out.println("0");
         if(soapEnvelope instanceof Node){
         System.out.println("1");
         if(soapEnvelope instanceof Element){
         System.out.println("2");
         if(soapEnvelope instanceof Document){
              System.out.println("3");
         SOAPHeader soapHeader = soapEnvelope.getHeader();
         SOAPHeaderElement headerElement = soapHeader.addHeaderElement(
    soapEnvelope.createName("Signature", "SOAP-SEC",
    "http://schemas.xmlsoap.org/soap/security/2000-12"));
         SOAPBody soapBody = soapEnvelope.getBody();
         soapBody.addAttribute(soapEnvelope.createName("id", "SOAP-SEC",
         "http://schemas.xmlsoap.org/soap/security/2000-12"), "1");
         Name bodyName =soapEnvelope.createName("GetLastTradePrice", "m",
         "http://wombats.ztrade.com");
         SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);
         Name name = soapEnvelope.createName("symbol");
         SOAPElement symbol = gltp.addChildElement(name);
         symbol.addTextNode("SUNW");
         // Generate a DOM representation of the SOAP message
         OMDOMFactory omfact=new OMDOMFactory();
         //Node nodo1=fd.newDomNode(options);
         OMNamespace namespace=omfact.createOMNamespace("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "wsu");
         OMNamespace namespace2=omfact.createOMNamespace("http://www.w3.org/2002/12/soap-envelope", "S");
         OMAttribute attr=omfact.createOMAttribute("mustUnderstand",namespace,"1");
         OMAttribute id=omfact.createOMAttribute("Id",namespace2,"1");
         OMAttribute id2=omfact.createOMAttribute("Id",namespace2,"2");
         OMElement sec=omfact.createOMElement("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","wsse");
         OMElement timestamp=omfact.createOMElement("Timestamp",namespace);
         OMElement created=omfact.createOMElement("Created",namespace);
         OMElement expires=omfact.createOMElement("Expires",namespace);
         OMElement frame=omfact.createOMElement("Framework",namespace2);
         OMElement signa=omfact.createOMElement("Signature",namespace2);
         timestamp.declareDefaultNamespace(namespace.getNamespaceURI());
         timestamp.setNamespace(namespace);
         Calendar now=Calendar.getInstance();
         Calendar exp=Calendar.getInstance();
         exp.add(now.MINUTE, 5);
         System.out.println("test");
         created.setText("created");
         expires.setText("expires");
         System.out.println("test");
         timestamp.addAttribute(id);
         System.out.println("test");
         timestamp.addChild(created);
         timestamp.addChild(expires);
         //sec.addChild(signa);
         sec.addAttribute(id2);
         sec.addChild(timestamp);
         //sec.addChild(frame);
         //System.out.println(sec.getParent().toString());
         System.out.println("Generating the DOM tree...");
         // Get input source
         Source source = soapPart.getContent();
         if(soapPart instanceof Source){
                   System.out.println("10");
              if(soapPart instanceof Node){
              System.out.println("11");
              if(soapPart instanceof Element){
              System.out.println("12");
              if(soapPart instanceof Document){
                   System.out.println("13");
         //Source source2 = soapPart.getFirstChild();
         //System.out.println(source.toString());
              //javax.xml.stream.XMLStreamReader inSource = sec.getXMLStreamReader();
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = null;
         System.out.println("13");
         //synchronized (dbf) {
              db = dbf.newDocumentBuilder();
              System.out.println("13");
         Document doc = db.newDocument();
         doc.appendChild((Node)sec);
         org.w3c.dom.Node root = (org.w3c.dom.Node) doc.getDocumentElement();
         System.out.println("13");
         System.out.println("13: "+root.getFirstChild().getLocalName());
         org.w3c.dom.Node envelope = (Node)sec;//soapPart.getFirstChild();
    /* Node) sec;
         if (source instanceof DOMSource) {
         root = ((DOMSource)source).getNode();
         } else if (source instanceof SAXSource) {
         InputSource inSource = ((SAXSource)source).getInputSource();
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         DocumentBuilder db = null;
         synchronized (dbf) {
              db = dbf.newDocumentBuilder();
         Document doc = db.parse(inSource);
         root = (org.w3c.dom.Node) doc.getDocumentElement();
         } else {
         System.err.println("error: cannot convert SOAP message (" +
              source.getClass().getName() + ") into a W3C DOM tree");
         System.exit(-1);
         //if (debug) {
         // dumpDOMDocument(root);
         // Generate a DSA key pair
         System.out.println("Generating the DSA keypair...");
         KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
         kpg.initialize(1024, new SecureRandom("not so random".getBytes()));
         KeyPair keypair = kpg.generateKeyPair();
    // Assemble the signature parts
         System.out.println("Preparing the signature...");
         String providerName = System.getProperty
    ("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
         XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance("DOM",
    (Provider) Class.forName(providerName).newInstance());
    Reference ref = sigFactory.newReference("#1",
         sigFactory.newDigestMethod(DigestMethod.SHA1, null));
    SignedInfo signedInfo = sigFactory.newSignedInfo(
         sigFactory.newCanonicalizationMethod(
              CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
              (C14NMethodParameterSpec) null),
    sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
         Collections.singletonList(ref));
         KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
         KeyValue kv = kif.newKeyValue(keypair.getPublic());
    KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));
    XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);
         // Insert XML signature into DOM tree and sign
         System.out.println("Signing the SOAP message...");
         // Find where to insert signature
         //Element envelope = getFirstChildElement(root);
         Element header = getFirstChildElement(envelope);
         System.out.println("Signing the SOAP message...");
         //System.out.println(header.getLocalName());
         DOMSignContext sigContext =
         new DOMSignContext(keypair.getPrivate(), envelope);
         // Need to distinguish the Signature element in DSIG (from that in SOAP)
         System.out.println("Signing the SOAP message...");
         sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
         // register Body ID attribute getNextSiblingElement(
         sigContext.setIdAttributeNS
         (header,
                   "http://www.w3.org/2002/12/soap-envelope","Id");
         System.out.println("Signing the SOAP message...");
         sig.sign(sigContext);
         if (debug) {
         dumpDOMDocument(envelope);
         // Validate the XML signature
         String providerName2 = System.getProperty
    ("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
    XMLSignatureFactory sigFactory2 = XMLSignatureFactory.getInstance("DOM",
    (Provider) Class.forName(providerName2).newInstance());
    SecurityDocument secdoc=SecurityDocument.Factory.parse(envelope);
    System.out.println(secdoc.xmlText());
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         Document doc = dbf.newDocumentBuilder().parse(secdoc.newInputStream());
    // Locate the signature element
         //Element sigElement = //getFirstChildElement(header);
              //getNextSiblingElement(header);
    // Validate the signature using the public key generated above
         System.out.println(doc.getFirstChild().getLastChild().getLocalName());
         DOMValidateContext valContext = new DOMValidateContext
    (keypair.getPublic(), doc.getElementsByTagName("ds:Signature").item(0));
              valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
              System.out.println(doc.getElementsByTagName("ds:Signature").item(0).getLocalName());
    // DOMValidateContext valContext =
         // new DOMValidateContext(keypair.getPublic(), sigElement);
         // register Body ID attribute getNextSiblingElement(
    // System.out.println(header.getNamespaceURI());
              //valContext.setIdAttributeNS((Element) doc.
                   //     getElementsByTagNameNS("wsu", "Timestamp").item
                        //(0), null, "Id");
              ((Element)doc.getElementsByTagName("wsu:Timestamp").item(0)).setAttributeNS("S", "Id", "1");
              ((Element)doc.getElementsByTagName("wsu:Timestamp").item(0)).setPrefix("wsu");
              valContext.setIdAttributeNS((Element)doc.getElementsByTagName("wsu:Timestamp").item(0),
         "http://www.w3.org/2002/12/soap-envelope","Id");
         //System.out.println(valContext.getElementById("1").getLocalName());
         //valContext.setBaseURI("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
         System.out.println("1");
         XMLSignature signature = sigFactory2.unmarshalXMLSignature(valContext);
         System.out.println("2: "+valContext.getDefaultNamespacePrefix());
         System.out.println(valContext.getElementById("1").getLocalName());
         //System.out.println(header.getLocalName());
         //System.out.println(getNextSiblingElement(header).getLocalName());
         //System.out.println(header.getAttribute("id"));
         //System.out.println(header.getBaseURI());
         if(signature.getSignatureValue().validate(valContext))
         System.out.println("Firma OK");
         Iterator it = signature.getSignedInfo().getReferences().iterator();
    if (((Reference) it.next()).validate(valContext))
         System.out.println("ref OK");
    boolean isValid = signature.validate(valContext);
         System.out.println("Validating the signature... " +
         (isValid ? "valid" : "invalid"));
    * Outputs DOM representation to the standard output stream.
    * @param root The DOM representation to be outputted
    private static void dumpDOMDocument(org.w3c.dom.Node root)
         throws TransformerException, TransformerConfigurationException {
         System.out.println("\n");
         // Create a new transformer object
         Transformer transformer =
         TransformerFactory.newInstance().newTransformer();
         transformer.setOutputProperty(OutputKeys.INDENT, "yes");
         // Dump the DOM representation to standard output
         transformer.transform(new DOMSource(root), new StreamResult(System.out));
         System.out.println("\n");
    * Returns the first child element of the specified node, or null if there
    * is no such element.
    * @param node the node
    * @return the first child element of the specified node, or null if there
    *     is no such element
    * @throws NullPointerException if <code>node == null</code>
    private static Element getFirstChildElement(org.w3c.dom.Node node) {
         org.w3c.dom.Node child = node.getFirstChild();
         while (child != null &&
         child.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
    child = child.getNextSibling();
    return (Element) child;
    * Returns the next sibling element of the specified node, or null if there
    * is no such element.
    * @param node the node
    * @return the next sibling element of the specified node, or null if there
    *     is no such element
    * @throws NullPointerException if <code>node == null</code>
    public static Element getNextSiblingElement(org.w3c.dom.Node node) {
         org.w3c.dom.Node sibling = node.getNextSibling();
         while (sibling != null &&
         sibling.getNodeType() != org.w3c.dom.Node.ELEMENT_NODE) {
    sibling = sibling.getNextSibling();
    return (Element) sibling;
    }

  • Problem verifying xml signature

    We have a problem with verifying XML Signatures which are part of a SOAP message. Thanks a lot for helping! Hope my problem is understandable - otherwise ask.
    We use the following enviroment:
    Java6
    Axis 2 V1.2 with XML Beans
    Step 1:
    The Java 6 XML Signature is an enveloped signature over an element called payload with exclusive XML canonicalization. We sign the payload and send the payload including signature to the server. At first I discovered the following namespace problem.
    DigesterOutputstream Create Signature:
    FEINER: <Payload Id="c623c3be-529b-4d6d-8f1e-a4a29660f344"><Parameter Encoding="base64"><Name>VSD</Name><Value>PFBlcmZvcm1VcGRhdGVzIHhtbG5zPSJodHRwOi8vd3MuZ2VtYXRpay5kZS9jbS9jYy9DbUNjU2VydmljZVJlcXVlc3QvdjEuMiIgeG1sbnM6djE9Imh0dHA6Ly93cy5nZW1hdGlrLmRlL2NtL2NvbW1vbi9DbUNvbW1vbi92MS4yIj4NCiAgPHYxOkljY3NuPjgwMjc2MDAxMDQwMDAwMDAyNDAwPC92MTpJY2Nzbj4NCiAgPHYxOlVwZGF0ZUlkPjAxPC92MTpVcGRhdGVJZD4NCjwvUGVyZm9ybVVwZGF0ZXM+</Value></Parameter><MessageID>urn:uuid:34D51D9DE4B7A19DD411938151524022</MessageID><Timestamp><Created>UNDO</Created></Timestamp></Payload>
    DigesterOutput Verify Signature:
    FEINER: <Payload xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" Id="c623c3be-529b-4d6d-8f1e-a4a29660f344"><Parameter Encoding="base64"><Name>VSD</Name><Value>PFBlcmZvcm1VcGRhdGVzIHhtbG5zPSJodHRwOi8vd3MuZ2VtYXRpay5kZS9jbS9jYy9DbUNjU2VydmljZVJlcXVlc3QvdjEuMiIgeG1sbnM6djE9Imh0dHA6Ly93cy5nZW1hdGlrLmRlL2NtL2NvbW1vbi9DbUNvbW1vbi92MS4yIj4NCiAgPHYxOkljY3NuPjgwMjc2MDAxMDQwMDAwMDAyNDAwPC92MTpJY2Nzbj4NCiAgPHYxOlVwZGF0ZUlkPjAxPC92MTpVcGRhdGVJZD4NCjwvUGVyZm9ybVVwZGF0ZXM+</Value></Parameter><MessageID>urn:uuid:34D51D9DE4B7A19DD411938151524022</MessageID><Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Created>UNDO</Created></Timestamp></Payload>
    31.10.2007 08:25:48 org.jcp.xml.dsig.internal.dom.DOMReference validate
    FEIN: Expected digest: 71PfJ/xxn38TtQrpZOpRdqTZsBw=
    31.10.2007 08:25:48 org.jcp.xml.dsig.internal.dom.DOMReference validate
    FEIN: Actual digest: B1Qdei/0yW1mqR2T50LXKFfxhl0=
    Soap request with payload:
    <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header><TelematikHeader xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1"><MessageID>urn:uuid:34D51D9DE4B7A19DD411938151524022</MessageID><ConversationID /><ServiceLocalization><Type>VSD</Type><Provider>101575519</Provider></ServiceLocalization><MessageType><Component>VSD</Component><Operation>PerformUpdates</Operation></MessageType><RoleDataProcessor /></TelematikHeader><TransportHeader xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1"><InterfaceVersion>0.0.24.3</InterfaceVersion></TransportHeader></soapenv:Header><soapenv:Body><TelematikExecute xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1"><Payload Id="c623c3be-529b-4d6d-8f1e-a4a29660f344"><Parameter Encoding="base64"><Name>VSD</Name><Value>PFBlcmZvcm1VcGRhdGVzIHhtbG5zPSJodHRwOi8vd3MuZ2VtYXRpay5kZS9jbS9jYy9DbUNjU2VydmljZVJlcXVlc3QvdjEuMiIgeG1sbnM6djE9Imh0dHA6Ly93cy5nZW1hdGlrLmRlL2NtL2NvbW1vbi9DbUNvbW1vbi92MS4yIj4NCiAgPHYxOkljY3NuPjgwMjc2MDAxMDQwMDAwMDAyNDAwPC92MTpJY2Nzbj4NCiAgPHYxOlVwZGF0ZUlkPjAxPC92MTpVcGRhdGVJZD4NCjwvUGVyZm9ybVVwZGF0ZXM+</Value></Parameter><MessageID>urn:uuid:34D51D9DE4B7A19DD411938151524022</MessageID><Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Created>UNDO</Created></Timestamp><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI="#c623c3be-529b-4d6d-8f1e-a4a29660f344"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>71PfJ/xxn38TtQrpZOpRdqTZsBw=</DigestValue></Reference></SignedInfo><SignatureValue>FuhOdrz9kHR0MeAUq9Rxkg6w++7foR77s9AYQUQxb8qPJ44Ba6By8R/H+CCn5JP5cPFz8/mGOgOD NGKLgZp66xbVSWe1UeehmZLH1a2kvHsx/VvYo3Lr5foHsl6YikUBMXCBdhI4ukKJTuwBOK/7m3lu 7Zl07SFo0zWL73gUTxc=</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=Harris Knafla,OU=IP,O=TK,ST=Hamburg,C=DE</X509SubjectName><X509Certificate>MIIC0DCCAjmgAwIBAgIBBDANBgkqhkiG9w0BAQUFADCBjTELMAkGA1UEBhMCREUxEDAOBgNVBAgT B0hhbWJ1cmcxEDAOBgNVBAcTB0hhbWJ1cmcxCzAJBgNVBAoTAlRLMQswCQYDVQQLEwJJUDEUMBIG A1UEAxMLTmlscyBLbmFmbGExKjAoBgkqhkiG9w0BCQEWG0RyLk5pbHMuS25hZmxhQHRrLW9ubGlu ZS5kZTAeFw0wNzA2MjkxNzQ2MzBaFw0wODA2MjgxNzQ2MzBaMFExCzAJBgNVBAYTAkRFMRAwDgYD VQQIEwdIYW1idXJnMQswCQYDVQQKEwJUSzELMAkGA1UECxMCSVAxFjAUBgNVBAMTDUhhcnJpcyBL bmFmbGEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJMjAnKFGjXjbPbi4X1vnI/H7ArNfayv HO7+QbuV1FqIR+aZuAYZeR5v0s8NKyGOcMxscAQk59ZrdfqaaIiwtcXk2fNHphtSVqLqR4NLWO2q xJKXwBcAxIn7byjq/DqjiUr5nmw1cMWJtK1xwB6pVMvCv97KGg2Z8peronBxg6mVAgMBAAGjezB5 MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRl MB0GA1UdDgQWBBRaMTzoUhWt1wguyvPlPuUUV8VRtTAfBgNVHSMEGDAWgBQuZ2A4G1XF+GvL7vai Zst6RUCqYjANBgkqhkiG9w0BAQUFAAOBgQAr3rtJIVNchr3pMEfFcSzbJJWo/c0LRkUnWkP1gD6f MqLoLFUbl8k6tKJ9V4P0Oe2BODRIfNyTFjKLzD1lHAFFRz9pzYUx+hq4VDWooA3MsewNDDyJwupi vlmHcM+Y8Cv97q9pERiqAY88TRMZxntl/b98W61KARAO+HUDhTnA1g==</X509Certificate></X509Data></KeyInfo></Signature></Payload></TelematikExecute></soapenv:Body></soapenv:Envelope>     
    The problem is the namespaces under the elements payload and timestamp. For verification the namespaces are inherited from parent element. I wonder why this happens - I thought this should not happen when using exclusive canonicalization, or?
    Step 2:
    Then I added the namespaces before creating the signature , e.g.
    payloadElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "http://ws.gematik.de/Schema/Telematik/Transport/V1");
    for all attributes that are not part of the create signature log. Then the xml signature was verify successfully when I tested this against my own server. See log files:
    DigesterOutputstream for create signature:
    31.10.2007 11:16:00 org.jcp.xml.dsig.internal.DigesterOutputStream write
    FEINER: <Payload xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Id="c623c3be-529b-4d6d-8f1e-a4a29660f344"><Parameter Encoding="base64"><Name>VSD</Name><Value>PFBlcmZvcm1VcGRhdGVzIHhtbG5zPSJodHRwOi8vd3MuZ2VtYXRpay5kZS9jbS9jYy9DbUNjU2VydmljZVJlcXVlc3QvdjEuMiIgeG1sbnM6djE9Imh0dHA6Ly93cy5nZW1hdGlrLmRlL2NtL2NvbW1vbi9DbUNvbW1vbi92MS4yIj4NCiAgPHYxOkljY3NuPjgwMjc2MDAxMDQwMDAwMDMwMjI5PC92MTpJY2Nzbj4NCiAgPHYxOlVwZGF0ZUlkPjAxPC92MTpVcGRhdGVJZD4NCjwvUGVyZm9ybVVwZGF0ZXM+</Value></Parameter><MessageID>urn:uuid:9E0D31C48FDB63BBCD11938257462232</MessageID><Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Created>UNDO</Created></Timestamp></Payload>
    DigesterOutputstream verify signature:
    31.10.2007 11:19:00 org.jcp.xml.dsig.internal.DigesterOutputStream write
    FEINER: <Payload xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" Id="c623c3be-529b-4d6d-8f1e-a4a29660f344"><Parameter Encoding="base64"><Name>VSD</Name><Value>PFBlcmZvcm1VcGRhdGVzIHhtbG5zPSJodHRwOi8vd3MuZ2VtYXRpay5kZS9jbS9jYy9DbUNjU2VydmljZVJlcXVlc3QvdjEuMiIgeG1sbnM6djE9Imh0dHA6Ly93cy5nZW1hdGlrLmRlL2NtL2NvbW1vbi9DbUNvbW1vbi92MS4yIj4NCiAgPHYxOkljY3NuPjgwMjc2MDAxMDQwMDAwMDMwMjI5PC92MTpJY2Nzbj4NCiAgPHYxOlVwZGF0ZUlkPjAxPC92MTpVcGRhdGVJZD4NCjwvUGVyZm9ybVVwZGF0ZXM+</Value></Parameter><MessageID>urn:uuid:9E0D31C48FDB63BBCD11938257462232</MessageID><Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Created>UNDO</Created></Timestamp></Payload>
    The whole soap request:
    <?xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header> <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1"><wsse:BinarySecurityToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" wsu:Id="CertId-3596382">MIIC0DCCAjmgAwIBAgIBBDANBgkqhkiG9w0BAQUFADCBjTELMAkGA1UEBhMCREUxEDAOBgNVBAgTB0hhbWJ1cmcxEDAOBgNVBAcTB0hhbWJ1cmcxCzAJBgNVBAoTAlRLMQswCQYDVQQLEwJJUDEUMBIGA1UEAxMLTmlscyBLbmFmbGExKjAoBgkqhkiG9w0BCQEWG0RyLk5pbHMuS25hZmxhQHRrLW9ubGluZS5kZTAeFw0wNzA2MjkxNzQ2MzBaFw0wODA2MjgxNzQ2MzBaMFExCzAJBgNVBAYTAkRFMRAwDgYDVQQIEwdIYW1idXJnMQswCQYDVQQKEwJUSzELMAkGA1UECxMCSVAxFjAUBgNVBAMTDUhhcnJpcyBLbmFmbGEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJMjAnKFGjXjbPbi4X1vnI/H7ArNfayvHO7+QbuV1FqIR+aZuAYZeR5v0s8NKyGOcMxscAQk59ZrdfqaaIiwtcXk2fNHphtSVqLqR4NLWO2qxJKXwBcAxIn7byjq/DqjiUr5nmw1cMWJtK1xwB6pVMvCv97KGg2Z8peronBxg6mVAgMBAAGjezB5MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRlMB0GA1UdDgQWBBRaMTzoUhWt1wguyvPlPuUUV8VRtTAfBgNVHSMEGDAWgBQuZ2A4G1XF+GvL7vaiZst6RUCqYjANBgkqhkiG9w0BAQUFAAOBgQAr3rtJIVNchr3pMEfFcSzbJJWo/c0LRkUnWkP1gD6fMqLoLFUbl8k6tKJ9V4P0Oe2BODRIfNyTFjKLzD1lHAFFRz9pzYUx+hq4VDWooA3MsewNDDyJwupivlmHcM+Y8Cv97q9pERiqAY88TRMZxntl/b98W61KARAO+HUDhTnA1g==</wsse:BinarySecurityToken><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="Signature-8331318"> <ds:SignedInfo> <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /> <ds:Reference URI="#id-28000914"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <ds:DigestValue>Q2LregRFO//cXlkcThu9Bx0jal4=</ds:DigestValue> </ds:Reference> <ds:Reference URI="#id-10464309"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <ds:DigestValue>BX651XEWk4u4pGgshQhocYxPkSo=</ds:DigestValue> </ds:Reference> <ds:Reference URI="#Timestamp-7651652"> <ds:Transforms> <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /> </ds:Transforms> <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /> <ds:DigestValue>ezisLn/pGWNqMHbT6UlHyM4Ez64=</ds:DigestValue> </ds:Reference> </ds:SignedInfo> <ds:SignatureValue> Xl4SSEwrtyUnsqf8xOmfzojLLU18tOrikOhK+HRyqHqv0lPF+AqANLU6yygNdhbfI5qyef9BLr6I CmSPIX4QQR+Hq45l/Ewa+M2K1OOjqvBUGYyQqrKCqUFtsISr9xPudB8ZmaVfaUu5chjIvy/sPYYx TuYv2Ma6uEwek1YZpbE= </ds:SignatureValue> <ds:KeyInfo Id="KeyId-1823783"> <wsse:SecurityTokenReference xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="STRId-17125267"><wsse:Reference URI="#CertId-3596382" ValueType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3" /></wsse:SecurityTokenReference> </ds:KeyInfo> </ds:Signature><wsu:Timestamp xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Timestamp-7651652"><wsu:Created>2007-10-31T10:16:00.474Z</wsu:Created><wsu:Expires>2007-10-31T10:21:00.474Z</wsu:Expires></wsu:Timestamp></wsse:Security><TelematikHeader xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-10464309"><MessageID>urn:uuid:9E0D31C48FDB63BBCD11938257462232</MessageID><ConversationID /><ServiceLocalization><Type>VSD</Type><Provider>101575519</Provider></ServiceLocalization><MessageType><Component>VSD</Component><Operation>PerformUpdates</Operation></MessageType><RoleDataProcessor /></TelematikHeader><TransportHeader xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1"><InterfaceVersion>0.0.24.3</InterfaceVersion></TransportHeader></soapenv:Header><soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="id-28000914"><TelematikExecute xmlns="http://ws.gematik.de/Schema/Telematik/Transport/V1"><Payload Id="c623c3be-529b-4d6d-8f1e-a4a29660f344"><Parameter Encoding="base64"><Name>VSD</Name><Value>PFBlcmZvcm1VcGRhdGVzIHhtbG5zPSJodHRwOi8vd3MuZ2VtYXRpay5kZS9jbS9jYy9DbUNjU2VydmljZVJlcXVlc3QvdjEuMiIgeG1sbnM6djE9Imh0dHA6Ly93cy5nZW1hdGlrLmRlL2NtL2NvbW1vbi9DbUNvbW1vbi92MS4yIj4NCiAgPHYxOkljY3NuPjgwMjc2MDAxMDQwMDAwMDMwMjI5PC92MTpJY2Nzbj4NCiAgPHYxOlVwZGF0ZUlkPjAxPC92MTpVcGRhdGVJZD4NCjwvUGVyZm9ybVVwZGF0ZXM+</Value></Parameter><MessageID>urn:uuid:9E0D31C48FDB63BBCD11938257462232</MessageID><Timestamp xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><Created>UNDO</Created></Timestamp><Signature xmlns="http://www.w3.org/2000/09/xmldsig#"><SignedInfo><CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#" /><SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /><Reference URI="#c623c3be-529b-4d6d-8f1e-a4a29660f344"><Transforms><Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /></Transforms><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /><DigestValue>XHIiHK4NYczByvAJSZH8u3hSvuQ=</DigestValue></Reference></SignedInfo><SignatureValue>JQnTQJ1TidrMuWmSmpHE3ZR5M728A3tlvKjrM3GxFPuy5YOmmybxR0T7xe72WSdWsqvFT9QGE+iP GL5POuc3s8lLc1QGZRKhZvjHAKFldDNyxAMWRL7ZXmhpjsRXT3HethKWew3669SKjJFkZ1IYEnZz QrJOmgt1MMjWx99CgaQ=</SignatureValue><KeyInfo><X509Data><X509SubjectName>CN=Harris Knafla,OU=IP,O=TK,ST=Hamburg,C=DE</X509SubjectName><X509Certificate>MIIC0DCCAjmgAwIBAgIBBDANBgkqhkiG9w0BAQUFADCBjTELMAkGA1UEBhMCREUxEDAOBgNVBAgT B0hhbWJ1cmcxEDAOBgNVBAcTB0hhbWJ1cmcxCzAJBgNVBAoTAlRLMQswCQYDVQQLEwJJUDEUMBIG A1UEAxMLTmlscyBLbmFmbGExKjAoBgkqhkiG9w0BCQEWG0RyLk5pbHMuS25hZmxhQHRrLW9ubGlu ZS5kZTAeFw0wNzA2MjkxNzQ2MzBaFw0wODA2MjgxNzQ2MzBaMFExCzAJBgNVBAYTAkRFMRAwDgYD VQQIEwdIYW1idXJnMQswCQYDVQQKEwJUSzELMAkGA1UECxMCSVAxFjAUBgNVBAMTDUhhcnJpcyBL bmFmbGEwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJMjAnKFGjXjbPbi4X1vnI/H7ArNfayv HO7+QbuV1FqIR+aZuAYZeR5v0s8NKyGOcMxscAQk59ZrdfqaaIiwtcXk2fNHphtSVqLqR4NLWO2q xJKXwBcAxIn7byjq/DqjiUr5nmw1cMWJtK1xwB6pVMvCv97KGg2Z8peronBxg6mVAgMBAAGjezB5 MAkGA1UdEwQCMAAwLAYJYIZIAYb4QgENBB8WHU9wZW5TU0wgR2VuZXJhdGVkIENlcnRpZmljYXRl MB0GA1UdDgQWBBRaMTzoUhWt1wguyvPlPuUUV8VRtTAfBgNVHSMEGDAWgBQuZ2A4G1XF+GvL7vai Zst6RUCqYjANBgkqhkiG9w0BAQUFAAOBgQAr3rtJIVNchr3pMEfFcSzbJJWo/c0LRkUnWkP1gD6f MqLoLFUbl8k6tKJ9V4P0Oe2BODRIfNyTFjKLzD1lHAFFRz9pzYUx+hq4VDWooA3MsewNDDyJwupi vlmHcM+Y8Cv97q9pERiqAY88TRMZxntl/b98W61KARAO+HUDhTnA1g==</X509Certificate></X509Data></KeyInfo></Signature></Payload></TelematikExecute></soapenv:Body></soapenv:Envelope>
    As you can see in the soap request on top of the xml signature there is a Webservice Security signature (WSSE) over three elements. This should be no problem altough WSSE adds the wsu:id attribute to the body element. WSSE was omitted in step 1 for simplicity.
    I wonder that the attributes which have been set to the payloadElement are not part of the actual message. But it works!
    Step 3:
    The same request was sent to an external webservice server and the server reports a xml signature verification problem. I don't have any logs or further information. But I have to get this to work against this server.
    Java Files for Create + Verify Signature. For Create I get a DOM Node from a XML Bean. For step 1 the attribute setting should be in comments. I use VerifySignature for step 1 + 2.
    SignPayload.java:
    package de.tk.signature;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.security.KeyStore;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import javax.xml.crypto.dsig.CanonicalizationMethod;
    import javax.xml.crypto.dsig.DigestMethod;
    import javax.xml.crypto.dsig.Reference;
    import javax.xml.crypto.dsig.SignatureMethod;
    import javax.xml.crypto.dsig.SignedInfo;
    import javax.xml.crypto.dsig.Transform;
    import javax.xml.crypto.dsig.XMLSignature;
    import javax.xml.crypto.dsig.XMLSignatureFactory;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.keyinfo.KeyInfo;
    import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
    import javax.xml.crypto.dsig.keyinfo.X509Data;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import javax.xml.crypto.dsig.spec.ExcC14NParameterSpec;
    import javax.xml.crypto.dsig.spec.TransformParameterSpec;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.OutputKeys;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.apache.xmlbeans.XmlObject;
    import de.tk.schemaTools.TkSchemaHandler;
    import de.tk.util.ClientProperties;
    public class SignPayload {
         public static void signDocument(XmlObject telematikExecuteXmlObject, String payloadId) {
              try {
                   // get Document
                   org.w3c.dom.Node node = telematikExecuteXmlObject.getDomNode();
                   Document documentTo = node.getOwnerDocument();
                   XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
                   Reference ref = fac.newReference("#"+payloadId, fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac
                             .newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
                   // Create the SignedInfo.
                   SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                             Collections.singletonList(ref));
                   KeyStore keyStore = KeyStore.getInstance("JKS");
                   String keyStoreFilename = ClientProperties.getKeystorefile();
                   FileInputStream keyStoreFile = new FileInputStream(keyStoreFilename);
                   keyStore.load(keyStoreFile, "storePwd".toCharArray());
                   keyStoreFile.close();
                   KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry("harris", new KeyStore.PasswordProtection("keyPwd".toCharArray()));
                   X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
                   // Create the KeyInfo containing the X509Data.
                   KeyInfoFactory kif = fac.getKeyInfoFactory();
                   List x509Content = new ArrayList();
                   x509Content.add(cert.getSubjectX500Principal().getName());
                   x509Content.add(cert);
                   X509Data xd = kif.newX509Data(x509Content);
                   KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
                   Node payloadNode = new TkSchemaHandler().getNode(documentTo, "Payload");
                   String prefix = payloadNode.getPrefix();
                   NamedNodeMap nameNodeMap = payloadNode.getAttributes();
                   // String baseUri = payloadNode.getBaseURI(); not implemented
                   boolean attributes = payloadNode.hasAttributes();
                   Element payloadElement = (Element) payloadNode;
                   //xmlns is the prefix and first parameter the namespaceURI
                   // xmlns existiert ohne WSSE, beim Create XMLOutputter ausgegeben
                   payloadElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "http://ws.gematik.de/Schema/Telematik/Transport/V1");
                   // existiert ohne WSSE
                   // bei Create nicht; aber bei Verify im DigestOutputter mit drin
                   payloadElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:soapenv", "http://schemas.xmlsoap.org/soap/envelope/");
                   // existiert nur bei WSSE
                   payloadElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
                   Node timestampNode = new TkSchemaHandler().getNode(documentTo, "Timestamp");
                   Element timestampElement = (Element) timestampNode;
                   // existiert ohne WSSE
                   // beim Create Outputter angegeben sowie beim Verify
                   timestampElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
                   // existiert nur bei WSSE, war wohl nur notwendig da bei WSSE Signature auf falschen Timestamp zugegriffen worden ist.
                   // Create a DOMSignContext and specify the RSA PrivateKey and
                   // location of the resulting XMLSignature's parent element.
                   DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(),payloadNode);
                   // Create the XMLSignature, but don't sign it yet.
                   XMLSignature signature = fac.newXMLSignature(si, ki);
                   // DomInfo.visualize(document);
                   SAXBuilderDemo2.print(documentTo);
                   // Marshal, generate, and sign the enveloped signature.
                   signature.sign(dsc);
              } catch (Exception exc) {
                   throw new RuntimeException(exc.getMessage());
    VerifySignature.java:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.security.Key;
    import java.security.KeyStore;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Enumeration;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.crypto.dsig.CanonicalizationMethod;
    import javax.xml.crypto.dsig.DigestMethod;
    import javax.xml.crypto.dsig.Reference;
    import javax.xml.crypto.dsig.SignatureMethod;
    import javax.xml.crypto.dsig.SignedInfo;
    import javax.xml.crypto.dsig.Transform;
    import javax.xml.crypto.dsig.XMLSignature;
    import javax.xml.crypto.dsig.XMLSignatureFactory;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.dom.DOMValidateContext;
    import javax.xml.crypto.dsig.keyinfo.KeyInfo;
    import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
    import javax.xml.crypto.dsig.keyinfo.X509Data;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import javax.xml.crypto.dsig.spec.TransformParameterSpec;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    public class VerifySignature {
         * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              try {
                   String filename = args[0];
                   System.out.println("Verify Document: " + filename);
                   XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
                   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                   dbf.setNamespaceAware(true);
                   Document doc = dbf
                   .newDocumentBuilder()
                   .parse(
                             new FileInputStream(filename));
    //               Find Signature element.
    //               NodeList nl =
    //               doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
                   Node node = TkSchemaHandler.getNode(doc,"/*[local-name()='Envelope' and namespace-uri()='http://schemas.xmlsoap.org/soap/envelope/']/*[local-name()='Body' and namespace-uri()='http://schemas.xmlsoap.org/soap/envelope/'][1]/*[local-name()='TelematikExecute' and namespace-uri()='http://ws.gematik.de/Schema/Telematik/Transport/V1'][1]/*[local-name()='Payload' and namespace-uri()='http://ws.gematik.de/Schema/Telematik/Transport/V1'][1]/*[local-name()='Signature' and namespace-uri()='http://www.w3.org/2000/09/xmldsig#'][1]");
                   if (nl.getLength() == 0) {
                   throw new Exception("Cannot find Signature element");
                   Node node = nl.item(0); */
    //               Create a DOMValidateContext and specify a KeySelector
    //               and document context.
                   DOMValidateContext valContext = new DOMValidateContext
                   (new X509KeySelector(), node);
    //               Unmarshal the XMLSignature.
                   XMLSignature signature = fac.unmarshalXMLSignature(valContext);
    //               Validate the XMLSignature.
                   boolean coreValidity = signature.validate(valContext);
                   // sample 6
    //               Check core validation status.
                   if (coreValidity == false) {
                   System.err.println("Signature failed core validation");
                   boolean sv = signature.getSignatureValue().validate(valContext);
                   System.out.println("signature validation status: " + sv);
                   if (sv == false) {
                   // Check the validation status of each Reference.
                   Iterator i = signature.getSignedInfo().getReferences().iterator();
                   for (int j=0; i.hasNext(); j++) {
                   boolean refValid = ((Reference) i.next()).validate(valContext);
                   System.out.println("ref["+j+"] validity status: " + refValid);
                   } else {
                   System.out.println("OK! Signature passed core validation!");
              } catch (Exception exc) {
                   exc.printStackTrace();
    Questions:
    1. Do I really have to set all the namespace attributes? I thought with exclusive xml this should not be necessary. Is there any other solution?
    2. Do you think I got all the settings right in SignPayload.java?
    Thanks a lot in advance.
    Cheers !
    Nils

    It seems to be a bug with the JDK you are using. What is the JDK version you are using?

  • XSLT Transform in XML Signature: Exception

    Hello,
    I have following problem with an XSLT tranform in my XML signature. Here is the code I use to add XSLT to signature:
    main() {
    DOMStructure stylesheet = new DOMStructure( getStylesheet() );
    XSLTTransformParameterSpec spec = new XSLTTransformParameterSpec( stylesheet );
    transforms.add( fac.newTransform( Transform.XSLT, spec ) );
    private Element getStylesheet() throws Exception {
         String stylesheet = //"<?xml version=\"1.0\"?>" +
                        "<xslt:stylesheet version=\"1.0\" xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\">\n" +
                        " <xsl:include href=\"http://extern XSLT\" />\n" +
                        " <xslt:template match=\"/\">" +
                        " <xsl:apply-imports />" +
                        " </xslt:template>" +
                        "</xslt:stylesheet>\n";
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         //dbf.setValidating( true );
         return dbf.newDocumentBuilder().parse( new ByteArrayInputStream( stylesheet.getBytes() ) ).getDocumentElement();
    I get following exception:
    javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.dsig.TransformException: com.sun.org.apache.xml.internal.security.transforms.TransformationException: Cannot find xslt:stylesheet in Transform
    Original Exception was com.sun.org.apache.xml.internal.security.transforms.TransformationException: Cannot find xslt:stylesheet in Transform
         at org.jcp.xml.dsig.internal.dom.DOMReference.transform(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMReference.digest(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.digestReference(Unknown Source)
         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(Unknown Source)
    In google I cannot find any details what can be wrong.
    Any suggestions?
    Thanks in advance,
    errno

    Thanks for your response. Sorry - I tried both versions with xslt and xsl - doesn't worked -> the error in my post is actually caused through the multiple changes of this part of code. Here once again:
    private Element getStylesheet() throws Exception {
              String stylesheet = //"<?xml version=\"1.0\"?>" +
                                       "<xslt:stylesheet version=\"1.0\" xmlns:xslt=\"http://www.w3.org/1999/XSL/Transform\">\n" +
                                       " <xslt:include href=\"external XSLTl\" />\n" +
                                       " <xslt:template match=\"/\">" +
                                       " <xslt:apply-imports />" +
                                       " </xslt:template>" +
                                       "</xslt:stylesheet>\n";
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              //dbf.setValidating( true );
              return dbf.newDocumentBuilder().parse( new ByteArrayInputStream( stylesheet.getBytes() ) ).getDocumentElement();
    Thanks,
    errno

  • Sap PI - XML signature

    Hi Experts
    We have to digitally Sign and Encrypt and Decrypt an XML file in PI7.11 system using soap adapter
    To have an expert advise
    can I use WSSE or Apache WSS4J or SAML or Apache axis soap adapter
    My requirement is:
    XML Documents shall be signed using XML signature and Use enveloped signatures
    Support RSA signing in conformance with the algorithm indentified by sha1
    Use exclusive canonicalization (with comment or without comments)
    Will WSSE or Wss4j can support the above requirements...Please advise
    Thanking you
    Pooja

    Hi ,
    Thank you for your response...
    I mean when you say java experts can do easily...yes we do have java experts who can develop a source code encrypt and sign the code and give it to us as an ear file
    However I tried deploying EAR file on PI system my converting it into sda file ...no luck ..the file getting converted to ear file and i renamed and tried to deploy using jspm....no luck
    As we cannot import the ear file directly to NWDS to deploy it on PI system ....what we are trying is to get the source code from Java developer and we are developing and EJB and Ear projects by replacing the source code
    and later once deploy using adapter modules we can test it
    My question is:
    Can we configure WSSE on PI as per this link(/people/rajendra.badi/blog/2011/08/24/configuring-wsse-digital-signing-and-encryption-using-sap-pi-711-aae-soap-adapter) and try
    Signing and Enc/Dec
                                                     or
    How to configure and use Apache wss4j and Apache axis soap adapter...can you please forward me some documents on it
    Thanking you
    Pooja

  • Webservice response (XML response) with tag not mandatory

    Hello all,
    I have a problem with a webservice response.
    I implemented a wsdl who created some method to call webservices (Methox X, Y ,Z).
    I call the method 'X' with a table of string who have3 values in input, and I have in a  XML Answer of the webservice call that :
    <tag1> Value 1.1
    <tag2> Value 1.2
    <tag3> Value 1.3
    <message>OK
    <tag3> Value 2.3
    <message>KO
    <tag1> Value 3.1
    <tag2> Value 3.2
    <tag3> Value 3.3
    <message>OK
    Tags 1, 2 and 3 are not mandatory in wsdl (Min occurs = 0).
    In output of the method 'X' (created by wsdl implemantation) a ABAP structure with that :
    ValueTag1 | ValueTag2 | ValueTag3 | message
    Value 1.1 | Value 1.2 | Value 1.3 | OK
    Value 3.1 | Value 3.2 | Value 2.3 | KO
    No value. | No value. | Value 3.3 | OK
    I expect to have logically:
    ValueTag1 | ValueTag2 | ValueTag3 | message
    Value 1.1 | Value 1.2 | Value 1.3 | OK
    No value. | No value. | Value 2.3 | KO
    Value 3.1 | Value 3.2 | Value 3.3 | OK
    SAP put into the line 2of the structure, data of 3rd response because it dont found tag in the 2nd response.
    If i do my call, value by value and i concatenate anwsers, i have no problem.
    I dont understand the error and i cant find SAP note on the subject.
    Someone know ths problem ?
    Thanks.

    Hello,
    I have a wsdl file who describe webmethod and his parameters.
    I implemented this wsdl into a client proxy.
    SAP create automatically some CLASS, METHOD, STRUTURE.
    I call one of this method to ask the webservice.
    A XML flow sent and the webservice respond to me with a other XML flow.
    The XML flow response his automatically transforme by SAP, and i receive it into a structure in output of my method.
    Example :
    CREATE OBJECT XXX
      EXPORTING
        logical_port_name = `ZZZZ`.
    CATCH cx_ai_system_fault INTO fault.
      RAISE EXCEPTION fault.
    IF XXX IS BOUND.
      TRY.
        XXX->METHODYYY(
                EXPORTING
                   input =  ii_input
                IMPORTING
                   output = oo_output ).
       CATCH cx_ai_system_fault INTO fault1.
         RAISE EXCEPTION lr_fault1 .
       CATCH Error_ws INTO fault2.
         RAISE EXCEPTION lr_fault2.
       CATCH cx_ai_application_fault INTO fault3.
         RAISE EXCEPTION lr_fault3.
       CLEANUP.
      ENDTRY.
    ENDIF.
    METHODYYY was created by SAP with wsdl file.
    ii_input and oo_output and typed like structure in wsdl file.
    I can see XML flow and his content in SOAMANAGER transaction when i activate full trace.

  • Issue with WSDL created for sender agreement

    Hi,
    Can you please help me why I am getting the erroe with WSDL that has been created from directory Sener agreement in PI 7.1 EHP1?
    My interface is a SOAP to file ASYNC scenario and we have been given 5 XSDs that are referencing one each other ,5 XSDs are imported successfully and referenced properly,no errors/issues found.
    Created all ESr and directory objects and I tried creating WSDL from sender agreement for my Source/outbound inteface that is created with XSDs in ESR.
    When I try to import WSDL into SOPA UI to validate ,the import process stuck for ever while trying to import "http://www.w3.org/2001/xml.xsd" and finally throws me error.
    After that I tried importing WSDL created in Directory into AltovaXML spy to created the webservice request,I am getting the following error""invalid XML Schema:"xml:lang" is already declared in the schema dcument C:|..my WSDL.
    Even our partner who wants to make Webservice calls using this WSDL,they are not able to develop their Webservices they are getting errors something related to schema not found /not defined etc.
    Please let me know,what might be the issue?I verified several times with my XSD imports and referencing properly and configuration objects.
    Thank you for your help in advance.
    Regards,
    Prem

    Hi Mark,
    I am not getting issue while displaying/Exporting  as WSDL in ESR.I am getting issue while trying import WSDL that is generated out of Service Interface into SOAP UI or Altova XML Spy.
    I don't think PI created the WSDl out of W3 standards.
    This is the error I am getting in XML Spy:
    File C:\Documents and Settings\Prem\Desktop\SI_XYZ_O.wsdl is not valid
         Invalid XML schema: ''xml:lang' is already declared.
              Error location: schema / attribute++
    and in SOAP UI:It is trying to import the WSDL and it stuck for ever while trying to import http://www.w3.org/2001/xml.xsd and never imprts the WSDL into SOAP UI project.
    Please let me know,if you have any ideas.
    Thank you,
    Prem.

Maybe you are looking for

  • Error in creating function group

    Hi In my z function group, do i need to declare all the parameters used in function modules explicitly in any top include?.it was not declared as such in the standard function group from which i copied .

  • Problem with zip operating system command

    Hello, i have the following configuration in the file receiver adapter: Directory: /tmp/ File Name Scheme: %name%.txt Variable substitution: Variable Name: name                 Reference: payload: record,1,name,1 Run Operating system command: /usr/bi

  • Premiere network account login issues

    We currently are running CS5 and having issues logging anyone in other than Admin.  Is anyone else having issues looging in and dtarting Premiere with network accounts?  Better yet has any found a fix if this is a common problem?

  • Please help to load image in the database

    Hi to all. .... I need to save image file in the database thru forms ... I have some image file in the application server and I need to load it in the database in a Blob col.. Any help ... ?? Thank's in advance

  • Transfer Binary JPG from Table to AL11

    Hi folks, I have the problem, that I can not transfer a JPG-File from a Table (stored in bin-format) to AL11 directory properly. When I transfer the files to my local harddrive, everything is fine and I can open the picture. When I tranfer it to Al11