Architectural Difference Effect on Signing/Verifying XML Document

Hi all,
I am using Apache Santuario for signing XML.
1. I have a Windows Server 2008 64 Bit, which is using JAVA 7 32 bit JVM. Let's say my signed document is Signed_A. On Windows Server 2008 I am signing the document but the verification fails for Signed_A.
2. Same application is being run on Windows 7 32 bit with the same JVM version. And the document is Signed_B on this machine. I am signing the document and verifying it without a problem.
3. If I move the document Signed_B (which I could sign & verify on Windows 7) to Windows 2008 Server, using the same application I can verify the document. So, my spider senses tell me that, there is a problem with signing.
4. Again if I move the document Signed_A to Windows 7 machine, I could not verify the signature.
I don't know whether the situation is occur because of the difference of processors on machines. But if you have anything that can help me please let me know. Anything could be helpful for now because I'm stuck in here.
Please feel free to ask if you need further explanations. I am not providing any code, because I am suspecting a configuration issue here.
Thanks in advance.

Hi,
Can you tell me about your project on short notes. For information.
Regards
R.Rajendran

Similar Messages

  • Difference between SDO and a xml document

    Hello,
    I want to know what is the exact difference between a SDO and XML document.According to my understanding, SDO defines a Java binding framework of its own. XML is a kind of data being bound to SDO.
    SDO can be represented as XML.
    But what is the difference between a normal XML document and a XML representing a SDO ?
    How can we say by looking at a XML doc that it is a representation of a SDO and not JUST ANY xml doc?
    Please clarify.
    Thanks
    Nutan

    Let's see.
    Facelets creates a facelets page
    JSP creates a JSP page
    {noformat}:){noformat}
    Facelets is the "official" view language for JSF 2.0
    http://www.realdevelopers.com/blog/development/facelets-vs-jsp should give you some more insight as well.
    John

  • Problem Digitally signing an xml document "Cannot resolve element"

    I am trying to sign a cXML document. I try to add 3 references to the XMLSignatureFactory but when it hits the 2nd on it throws an error "Cannot resolve element with ID cXMLData". How come I can't add more than 1?
    Here is the stack trace :
    java.lang.RuntimeException: javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.res olver.ResourceResolverException: Cannot resolve element with ID cXMLData
    at com.praxair.security.b2b.CXMLDigitalSig.sign(CXMLD igitalSig.java:303)
    at com.praxair.security.b2b.CXMLDigitalSig.main(CXMLD igitalSig.java:359)
    Java Code:
    public class CXMLDigitalSig
         private XMLSignatureFactory factory;
         private KeyStore keyStore;
         private KeyPair keyPair;
         private KeyInfo keyInfo;
         private X509Certificate signingCert;
         public CXMLDigitalSig()
         private void loadCert() throws Exception
              //String keystoreFile = config.getString(KEY_STORE_FILE);
              //String password = config.getString(KEY_STORE_PASSWORD);
              //String alias = config.getString(KEY_STORE_ALIAS);
              String keystoreFile = "C:\\cxmlsign\\teststore";
              String password = "xxxxx";
              String alias = "xxxxx (thawte ssl ca)";
              keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
              File file = new File(keystoreFile);
              FileInputStream inStream = new FileInputStream(file);
              char [] passAsChar = password.toCharArray();          
              keyStore.load(inStream, passAsChar);
              inStream.close();
              String providerName = System.getProperty("jsr105Provider",
                        "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
              factory = XMLSignatureFactory.getInstance("DOM", (Provider) Class
                        .forName(providerName).newInstance());
              KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
                        .getEntry(alias, new KeyStore.PasswordProtection(passAsChar));
              signingCert = (X509Certificate) entry.getCertificate();
              keyPair = new KeyPair(entry.getCertificate().getPublicKey(),
                        entry.getPrivateKey());
              KeyInfoFactory kFactory = factory.getKeyInfoFactory();
              keyInfo = kFactory.newKeyInfo(Collections.singletonList(kFactory
                        .newX509Data(Collections.singletonList(entry
                                  .getCertificate()))));
          * This method returns the message digest for given certificate.
          * @param cert
          * @return
          * @throws NoSuchAlgorithmException
          * @throws CertificateEncodingException
         private static String getThumbPrint(X509Certificate cert)
                   throws NoSuchAlgorithmException, CertificateEncodingException {
              MessageDigest md = MessageDigest.getInstance("SHA-1");
              byte[] der = cert.getEncoded();
              md.update(der);
              byte[] digest = md.digest();
              return hexify(digest);
         private static String hexify(byte bytes[]) {
              char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'a', 'b', 'c', 'd', 'e', 'f' };
              StringBuffer buf = new StringBuffer(bytes.length * 2);
              for (int i = 0; i < bytes.length; ++i) {
                   buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
                   buf.append(hexDigits[bytes[i] & 0x0f]);
              return buf.toString();
          * Adds an enveloped signature to the given document. The signature is
          * generated as per the CXML specfication outlined in the CXML user guide.
          * This method creates the signature and three references and also the XADES
          * information.
         public void sign(Element cxmlElement, String payloadId) throws SQLException {
              Reference ref1;
              Reference ref2;
              Reference ref3;
              List<Reference> refs = new ArrayList<Reference>();
              SignedInfo signedInfo;
              try {
                   ref1 = factory.newReference("#cXMLSignedInfo",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref1);
                   ref2 = factory.newReference("#cXMLData",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref2);
                   ref3 = factory.newReference("#XAdESSignedProps",
                             factory.newDigestMethod(DigestMethod.SHA1, null));
                   refs.add(ref3);
                   signedInfo = factory.newSignedInfo(factory
                             .newCanonicalizationMethod(
                                       CanonicalizationMethod.INCLUSIVE,
                                       (C14NMethodParameterSpec) null), factory
                             .newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
              } catch (NoSuchAlgorithmException e) {
                   throw new RuntimeException(e);
              } catch (InvalidAlgorithmParameterException e) {
                   throw new RuntimeException(e);
              List<DOMStructure> xmlObjSignedInfo = new ArrayList<DOMStructure>();
              Element signedInfoElement = createElement(cxmlElement,
                        "cXMLSignedInfo", null, null);
              signedInfoElement.setAttributeNS(null, "Id", "cXMLSignedInfo");
              signedInfoElement.setAttributeNS(null, "payloadID", payloadId);
              signedInfoElement.setAttributeNS(null, "signatureVersion", "1.0");
              DOMStructure signedInfoStruct = new DOMStructure(signedInfoElement);
              xmlObjSignedInfo.add(signedInfoStruct);
              String xadesNS = "http://uri.etsi.org/01903/v1.1.1#";
              // Create the necessary XADES information as outlined in the CXML
              // specification
              Element QPElement = createElement(cxmlElement, "QualifyingProperties",
                        "xades", xadesNS);
              QPElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
                        "xmlns:xades", xadesNS);
              QPElement.setAttributeNS(null, "Target", "#cXMLSignature");
              Element SPElement = createElement(cxmlElement, "SignedProperties",
                        "xades", xadesNS);
              SPElement.setAttributeNS(null, "Id", "XAdESSignedProps");
              IdResolver.registerElementById(SPElement, "XAdESSignedProps");
              QPElement.appendChild(SPElement);
              Element signedSPElement = createElement(cxmlElement,
                        "SignedSignatureProperties", "xades", xadesNS);
              Element signingTimeElement = createElement(cxmlElement, "SigningTime",
                        "xades", xadesNS);
              SimpleDateFormat dateFormatter = new SimpleDateFormat(
                        "yyyy-MM-dd'T'HH:mm:ss");
              signingTimeElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(dateFormatter.format(new Date())));
              signedSPElement.appendChild(signingTimeElement);
              SPElement.appendChild(signedSPElement);
              String certDigest = "";
              try {
                   certDigest = getThumbPrint(signingCert);
              } catch (CertificateEncodingException ce) {
                   throw new RuntimeException(ce);
              } catch (NoSuchAlgorithmException ne) {
                   throw new RuntimeException(ne);
              Element signingCertificateElement = createElement(cxmlElement,
                        "SigningCertificate", "xades", xadesNS);
              Element certElement = createElement(cxmlElement, "Cert", "xades",
                        xadesNS);
              Element certDigestElement = createElement(cxmlElement, "CertDigest",
                        "xades", xadesNS);
              Element digestMethodElement = createElement(cxmlElement,
                        "DigestMethod", "ds", XMLSignature.XMLNS);
              digestMethodElement
                        .setAttributeNS(null, "Algorithm", DigestMethod.SHA1);
              Element digestValueElement = createElement(cxmlElement, "DigestValue",
                        "ds", XMLSignature.XMLNS);
              digestValueElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(certDigest));
              Element issuerSerialElement = createElement(cxmlElement,
                        "IssuerSerial", "xades", xadesNS);
              Element x509IssuerNameElement = createElement(cxmlElement,
                        "X509IssuerName", "ds", XMLSignature.XMLNS);
              x509IssuerNameElement
                        .appendChild(cxmlElement.getOwnerDocument().createTextNode(
                                  signingCert.getIssuerX500Principal().toString()));
              Element x509IssuerSerialNumberElement = createElement(cxmlElement,
                        "X509IssuerSerialNumber", "ds", XMLSignature.XMLNS);
              x509IssuerSerialNumberElement.appendChild(cxmlElement
                        .getOwnerDocument().createTextNode(
                                  signingCert.getSerialNumber().toString()));
              certDigestElement.appendChild(digestMethodElement);
              certDigestElement.appendChild(digestValueElement);
              certElement.appendChild(certDigestElement);
              issuerSerialElement.appendChild(x509IssuerNameElement);
              issuerSerialElement.appendChild(x509IssuerSerialNumberElement);
              certElement.appendChild(issuerSerialElement);
              signingCertificateElement.appendChild(certElement);
              signedSPElement.appendChild(signingCertificateElement);
              DOMStructure qualifPropStruct = new DOMStructure(QPElement);
              List<DOMStructure> xmlObjQualifyingProperty = new ArrayList<DOMStructure>();
              xmlObjQualifyingProperty.add(qualifPropStruct);
              XMLObject objectSingedInfo = factory.newXMLObject(xmlObjSignedInfo,
                        null, null, null);
              XMLObject objectQualifyingProperty = factory.newXMLObject(
                        xmlObjQualifyingProperty, null, null, null);
              // Create the ds:object tags
              List<XMLObject> objects = new ArrayList<XMLObject>();
              objects.add(objectSingedInfo);
              objects.add(objectQualifyingProperty);
              XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo,
                        objects, "cXMLSignature", null);
              DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
                        cxmlElement);
              signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
              try {
                   signature.sign(signContext);
              } catch (MarshalException e) {
                   throw new RuntimeException(e);
              } catch (XMLSignatureException e) {
                   throw new RuntimeException(e);
         private Element createElement(Element element, String tag, String prefix,
                   String nsURI) {
              String qName = prefix == null ? tag : prefix + ":" + tag;
              return element.getOwnerDocument().createElementNS(nsURI, qName);
         X509Certificate getSigningCert() {
              return signingCert;
         private static String readFileAsString(String filePath)     throws java.io.IOException
              byte[] buffer = new byte[(int) new File(filePath).length()];
              BufferedInputStream f = null;
              try {
                   f = new BufferedInputStream(new FileInputStream(filePath));
                   f.read(buffer);
              } finally {
                   if (f != null) {
                        try {
                             f.close();
                        } catch (IOException ignored) {
              return new String(buffer);
         public static void main(String args[])
              System.out.println("start");
              CXMLDigitalSig cXMLDigitalSig = new CXMLDigitalSig();
              try
                   cXMLDigitalSig.loadCert();
                      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                      dbf.setNamespaceAware(true);
                   String cXML = readFileAsString("C:\\cxmlsign\\cxml.xml");
                      Document cxmlDocument = dbf.newDocumentBuilder()
                                                 .parse(new ByteArrayInputStream(cXML
                                                           .getBytes("UTF-8")));
                   System.out.println(cxmlDocument.getDocumentElement().getTagName());
                      cXMLDigitalSig.sign(cxmlDocument.getDocumentElement(), "55");
              catch(Exception e)
                   //System.out.println(e.getMessage());
                   System.out.println(getStackTrace(e));
                 System.out.println("end");
           public static String getStackTrace(Throwable aThrowable) {
                  final Writer result = new StringWriter();
                  final PrintWriter printWriter = new PrintWriter(result);
                  aThrowable.printStackTrace(printWriter);
                  return result.toString();
    }Edited by: sabre150 on Jan 18, 2012 1:57 PM
    Moderator action : added [ code ] tags to format source code

    I am trying to sign a cXML document. I try to add 3 references to the XMLSignatureFactory but when it hits the 2nd on it throws an error "Cannot resolve element with ID cXMLData". How come I can't add more than 1?
    Here is the stack trace :
    java.lang.RuntimeException: javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: com.sun.org.apache.xml.internal.security.utils.res olver.ResourceResolverException: Cannot resolve element with ID cXMLData
    at com.praxair.security.b2b.CXMLDigitalSig.sign(CXMLD igitalSig.java:303)
    at com.praxair.security.b2b.CXMLDigitalSig.main(CXMLD igitalSig.java:359)
    Java Code:
    public class CXMLDigitalSig
         private XMLSignatureFactory factory;
         private KeyStore keyStore;
         private KeyPair keyPair;
         private KeyInfo keyInfo;
         private X509Certificate signingCert;
         public CXMLDigitalSig()
         private void loadCert() throws Exception
              //String keystoreFile = config.getString(KEY_STORE_FILE);
              //String password = config.getString(KEY_STORE_PASSWORD);
              //String alias = config.getString(KEY_STORE_ALIAS);
              String keystoreFile = "C:\\cxmlsign\\teststore";
              String password = "xxxxx";
              String alias = "xxxxx (thawte ssl ca)";
              keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
              File file = new File(keystoreFile);
              FileInputStream inStream = new FileInputStream(file);
              char [] passAsChar = password.toCharArray();          
              keyStore.load(inStream, passAsChar);
              inStream.close();
              String providerName = System.getProperty("jsr105Provider",
                        "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
              factory = XMLSignatureFactory.getInstance("DOM", (Provider) Class
                        .forName(providerName).newInstance());
              KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
                        .getEntry(alias, new KeyStore.PasswordProtection(passAsChar));
              signingCert = (X509Certificate) entry.getCertificate();
              keyPair = new KeyPair(entry.getCertificate().getPublicKey(),
                        entry.getPrivateKey());
              KeyInfoFactory kFactory = factory.getKeyInfoFactory();
              keyInfo = kFactory.newKeyInfo(Collections.singletonList(kFactory
                        .newX509Data(Collections.singletonList(entry
                                  .getCertificate()))));
          * This method returns the message digest for given certificate.
          * @param cert
          * @return
          * @throws NoSuchAlgorithmException
          * @throws CertificateEncodingException
         private static String getThumbPrint(X509Certificate cert)
                   throws NoSuchAlgorithmException, CertificateEncodingException {
              MessageDigest md = MessageDigest.getInstance("SHA-1");
              byte[] der = cert.getEncoded();
              md.update(der);
              byte[] digest = md.digest();
              return hexify(digest);
         private static String hexify(byte bytes[]) {
              char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                        'a', 'b', 'c', 'd', 'e', 'f' };
              StringBuffer buf = new StringBuffer(bytes.length * 2);
              for (int i = 0; i < bytes.length; ++i) {
                   buf.append(hexDigits[(bytes[i] & 0xf0) >> 4]);
                   buf.append(hexDigits[bytes[i] & 0x0f]);
              return buf.toString();
          * Adds an enveloped signature to the given document. The signature is
          * generated as per the CXML specfication outlined in the CXML user guide.
          * This method creates the signature and three references and also the XADES
          * information.
         public void sign(Element cxmlElement, String payloadId) throws SQLException {
              Reference ref1;
              Reference ref2;
              Reference ref3;
              List<Reference> refs = new ArrayList<Reference>();
              SignedInfo signedInfo;
              try {
                   ref1 = factory.newReference("#cXMLSignedInfo",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref1);
                   ref2 = factory.newReference("#cXMLData",
                             factory.newDigestMethod(DigestMethod.SHA1, null), null,
                             null, null);
                   refs.add(ref2);
                   ref3 = factory.newReference("#XAdESSignedProps",
                             factory.newDigestMethod(DigestMethod.SHA1, null));
                   refs.add(ref3);
                   signedInfo = factory.newSignedInfo(factory
                             .newCanonicalizationMethod(
                                       CanonicalizationMethod.INCLUSIVE,
                                       (C14NMethodParameterSpec) null), factory
                             .newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
              } catch (NoSuchAlgorithmException e) {
                   throw new RuntimeException(e);
              } catch (InvalidAlgorithmParameterException e) {
                   throw new RuntimeException(e);
              List<DOMStructure> xmlObjSignedInfo = new ArrayList<DOMStructure>();
              Element signedInfoElement = createElement(cxmlElement,
                        "cXMLSignedInfo", null, null);
              signedInfoElement.setAttributeNS(null, "Id", "cXMLSignedInfo");
              signedInfoElement.setAttributeNS(null, "payloadID", payloadId);
              signedInfoElement.setAttributeNS(null, "signatureVersion", "1.0");
              DOMStructure signedInfoStruct = new DOMStructure(signedInfoElement);
              xmlObjSignedInfo.add(signedInfoStruct);
              String xadesNS = "http://uri.etsi.org/01903/v1.1.1#";
              // Create the necessary XADES information as outlined in the CXML
              // specification
              Element QPElement = createElement(cxmlElement, "QualifyingProperties",
                        "xades", xadesNS);
              QPElement.setAttributeNS("http://www.w3.org/2000/xmlns/",
                        "xmlns:xades", xadesNS);
              QPElement.setAttributeNS(null, "Target", "#cXMLSignature");
              Element SPElement = createElement(cxmlElement, "SignedProperties",
                        "xades", xadesNS);
              SPElement.setAttributeNS(null, "Id", "XAdESSignedProps");
              IdResolver.registerElementById(SPElement, "XAdESSignedProps");
              QPElement.appendChild(SPElement);
              Element signedSPElement = createElement(cxmlElement,
                        "SignedSignatureProperties", "xades", xadesNS);
              Element signingTimeElement = createElement(cxmlElement, "SigningTime",
                        "xades", xadesNS);
              SimpleDateFormat dateFormatter = new SimpleDateFormat(
                        "yyyy-MM-dd'T'HH:mm:ss");
              signingTimeElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(dateFormatter.format(new Date())));
              signedSPElement.appendChild(signingTimeElement);
              SPElement.appendChild(signedSPElement);
              String certDigest = "";
              try {
                   certDigest = getThumbPrint(signingCert);
              } catch (CertificateEncodingException ce) {
                   throw new RuntimeException(ce);
              } catch (NoSuchAlgorithmException ne) {
                   throw new RuntimeException(ne);
              Element signingCertificateElement = createElement(cxmlElement,
                        "SigningCertificate", "xades", xadesNS);
              Element certElement = createElement(cxmlElement, "Cert", "xades",
                        xadesNS);
              Element certDigestElement = createElement(cxmlElement, "CertDigest",
                        "xades", xadesNS);
              Element digestMethodElement = createElement(cxmlElement,
                        "DigestMethod", "ds", XMLSignature.XMLNS);
              digestMethodElement
                        .setAttributeNS(null, "Algorithm", DigestMethod.SHA1);
              Element digestValueElement = createElement(cxmlElement, "DigestValue",
                        "ds", XMLSignature.XMLNS);
              digestValueElement.appendChild(cxmlElement.getOwnerDocument()
                        .createTextNode(certDigest));
              Element issuerSerialElement = createElement(cxmlElement,
                        "IssuerSerial", "xades", xadesNS);
              Element x509IssuerNameElement = createElement(cxmlElement,
                        "X509IssuerName", "ds", XMLSignature.XMLNS);
              x509IssuerNameElement
                        .appendChild(cxmlElement.getOwnerDocument().createTextNode(
                                  signingCert.getIssuerX500Principal().toString()));
              Element x509IssuerSerialNumberElement = createElement(cxmlElement,
                        "X509IssuerSerialNumber", "ds", XMLSignature.XMLNS);
              x509IssuerSerialNumberElement.appendChild(cxmlElement
                        .getOwnerDocument().createTextNode(
                                  signingCert.getSerialNumber().toString()));
              certDigestElement.appendChild(digestMethodElement);
              certDigestElement.appendChild(digestValueElement);
              certElement.appendChild(certDigestElement);
              issuerSerialElement.appendChild(x509IssuerNameElement);
              issuerSerialElement.appendChild(x509IssuerSerialNumberElement);
              certElement.appendChild(issuerSerialElement);
              signingCertificateElement.appendChild(certElement);
              signedSPElement.appendChild(signingCertificateElement);
              DOMStructure qualifPropStruct = new DOMStructure(QPElement);
              List<DOMStructure> xmlObjQualifyingProperty = new ArrayList<DOMStructure>();
              xmlObjQualifyingProperty.add(qualifPropStruct);
              XMLObject objectSingedInfo = factory.newXMLObject(xmlObjSignedInfo,
                        null, null, null);
              XMLObject objectQualifyingProperty = factory.newXMLObject(
                        xmlObjQualifyingProperty, null, null, null);
              // Create the ds:object tags
              List<XMLObject> objects = new ArrayList<XMLObject>();
              objects.add(objectSingedInfo);
              objects.add(objectQualifyingProperty);
              XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo,
                        objects, "cXMLSignature", null);
              DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),
                        cxmlElement);
              signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
              try {
                   signature.sign(signContext);
              } catch (MarshalException e) {
                   throw new RuntimeException(e);
              } catch (XMLSignatureException e) {
                   throw new RuntimeException(e);
         private Element createElement(Element element, String tag, String prefix,
                   String nsURI) {
              String qName = prefix == null ? tag : prefix + ":" + tag;
              return element.getOwnerDocument().createElementNS(nsURI, qName);
         X509Certificate getSigningCert() {
              return signingCert;
         private static String readFileAsString(String filePath)     throws java.io.IOException
              byte[] buffer = new byte[(int) new File(filePath).length()];
              BufferedInputStream f = null;
              try {
                   f = new BufferedInputStream(new FileInputStream(filePath));
                   f.read(buffer);
              } finally {
                   if (f != null) {
                        try {
                             f.close();
                        } catch (IOException ignored) {
              return new String(buffer);
         public static void main(String args[])
              System.out.println("start");
              CXMLDigitalSig cXMLDigitalSig = new CXMLDigitalSig();
              try
                   cXMLDigitalSig.loadCert();
                      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                      dbf.setNamespaceAware(true);
                   String cXML = readFileAsString("C:\\cxmlsign\\cxml.xml");
                      Document cxmlDocument = dbf.newDocumentBuilder()
                                                 .parse(new ByteArrayInputStream(cXML
                                                           .getBytes("UTF-8")));
                   System.out.println(cxmlDocument.getDocumentElement().getTagName());
                      cXMLDigitalSig.sign(cxmlDocument.getDocumentElement(), "55");
              catch(Exception e)
                   //System.out.println(e.getMessage());
                   System.out.println(getStackTrace(e));
                 System.out.println("end");
           public static String getStackTrace(Throwable aThrowable) {
                  final Writer result = new StringWriter();
                  final PrintWriter printWriter = new PrintWriter(result);
                  aThrowable.printStackTrace(printWriter);
                  return result.toString();
    }Edited by: sabre150 on Jan 18, 2012 1:57 PM
    Moderator action : added [ code ] tags to format source code

  • 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.

  • Problem validating XMl document

    Hi everyone,
    I'm facing a problem validating a XML document with Apache toolkit under windows XP and eclipse 3.0
    I generate a pair of public/private keys using the RSA algorithm. The keys are of arbitrary length, but satisfying RSA conditions, ie we can encrypt and decrypt.
    I can sign my XML document, but no way to validate it. Validation is only ok when I generate random keys using the KeyPairGenerator.
    Do you think that arbitrary length keys don't allow to validate XML document. And do you have any idea how to solve the problem ( I'm not allowed to generate fixed length keys) ?
    Thansk a lot for your precious help.

    solved!
    urghh...forgot to load th eschema..duh. (must be friday)
    here's the fixed code:
        // parse the xml document (validate the xml string using a schema  file)
        // the xml document does not specified the System ID or location of
        // schema..and use no namespace
        public void parse(HandlerType type, String xmldoc) throws SAXException, IOException {
            File           schema      = schemaMap.get(type);
            DefaultHandler handler     = handlerMap.get(yype);
            XMLReader   reader = XMLReaderFactory.createXMLReader(VENDOR);
            InputSource source = new InputSource(new StringReader(xmldoc));
            reader.setContentHandler(handler);
            reader.setFeature("http://xml.org/sax/features/validation", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema", true);
            reader.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
            reader.setProperty("http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            "file:///" + schema.getAbsolutePath());
            reader.parse(source);          
        }

  • Problem in digitally signing a particular element of an XML Document

    hi all!!
    I was trying to sign a particular element of an XML document using JSR105 (XML Digital Signatures) API.
    For which i used +#xpointer(id('idvalue'))+ and +#idvalue+ as the URI for the reference i create as below :
    Reference ref = fac.newReference("#xpointer(id('123')) ", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null)), null, null);
    NOTE: Here 123 is the value of the attribute 'id' of the element i wish to sign in the input XML document.
    But when i try to digest and sign the the above created reference, i get the following exception (which is strange! atleast for me!)
    Exception in thread "main" javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: Can't resolve ID: '123' in ''
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.calculateDigestValue(ReferenceImpl.java:327)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.sign(ReferenceImpl.java:237)
    at com.ibm.xml.crypto.dsig.dom.XMLSignatureImpl.sign(XMLSignatureImpl.java:158)
    at sent.Generate.main(Generate.java:103)
    Caused by: javax.xml.crypto.URIReferenceException: Can't resolve ID: '123' in ''
    at com.ibm.xml.crypto.dsig.dom.URIDereferencerImpl.dereference(URIDereferencerImpl.java:193)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.calculateDigestValue(ReferenceImpl.java:285)
    +... 3 more+
    javax.xml.crypto.URIReferenceException: Can't resolve ID: '123' in ''
    at com.ibm.xml.crypto.dsig.dom.URIDereferencerImpl.dereference(URIDereferencerImpl.java:193)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.calculateDigestValue(ReferenceImpl.java:285)
    at com.ibm.xml.crypto.dsig.dom.ReferenceImpl.sign(ReferenceImpl.java:237)
    at com.ibm.xml.crypto.dsig.dom.XMLSignatureImpl.sign(XMLSignatureImpl.java:158)
    at sent.Generate.main(Generate.java:103)
    I've given the whole Java code i used to generate the signature and the XML i used below for you to get a clear picture of what i tried...
    Any suggestions are very much welcome..
    thanks..
    ragu
    Generate.java
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.security.InvalidAlgorithmParameterException;
    import java.security.KeyException;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.security.NoSuchAlgorithmException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    import javax.xml.crypto.MarshalException;
    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.XMLSignatureException;
    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.KeyValue;
    import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
    import javax.xml.crypto.dsig.spec.TransformParameterSpec;
    import javax.xml.crypto.dsig.spec.XPathFilterParameterSpec;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.transform.Transformer;
    import javax.xml.transform.TransformerException;
    import javax.xml.transform.TransformerFactory;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.xml.sax.SAXException;
    public class Generate {
          * @param args
          * @throws NoSuchAlgorithmException
          * @throws InvalidAlgorithmParameterException
          * @throws KeyException
          * @throws ParserConfigurationException
          * @throws IOException
          * @throws SAXException
          * @throws FileNotFoundException
          * @throws XMLSignatureException
          * @throws MarshalException
          * @throws TransformerException
         public static void main(String[] args) throws NoSuchAlgorithmException,
                   InvalidAlgorithmParameterException, KeyException,
                   FileNotFoundException, SAXException, IOException,
                   ParserConfigurationException, MarshalException,
                   XMLSignatureException, TransformerException {
              java.security.Security
                        .addProvider(new com.ibm.xml.crypto.IBMXMLCryptoProvider());
              XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
                        new com.ibm.xml.crypto.IBMXMLCryptoProvider());
              //reference generation
              //its here where I point the URI to the element i want to digest
              Reference ref = fac.newReference("#xpointer(id('123'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null)), null, null);
              //signedinfo element generation
              SignedInfo si = fac
                        .newSignedInfo(fac.newCanonicalizationMethod(
                                  CanonicalizationMethod.INCLUSIVE,
                                  (C14NMethodParameterSpec) null), fac
                                  .newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                                  Collections.singletonList(ref));
              KeyInfoFactory kif = fac.getKeyInfoFactory();
              //Create a DSA KeyPair
              KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
              kpg.initialize(512);
              KeyPair kp = kpg.generateKeyPair();
              KeyValue kv = kif.newKeyValue(kp.getPublic());
              // Create a KeyInfo and add the KeyValue to it
              KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
              // Instantiate the document to be signed
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setNamespaceAware(true);
              Document doc = dbf.newDocumentBuilder().parse(
                        new FileInputStream(new File("shippedPedigree.xml")));
              // Create a DOMSignContext and specify the DSA PrivateKey and
              // location of the resulting XMLSignature's parent element
              DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), doc
                        .getDocumentElement());
              //Create the XMLSignature (but don't sign it yet)
              XMLSignature signature = fac.newXMLSignature(si, ki);
              // Marshal, generate (and sign) the enveloped signature
              signature.sign(dsc);
              //writing the signed document back to the file
              OutputStream os;
              os = new FileOutputStream(new File("shippedpedigree.xml"));
              TransformerFactory tf = TransformerFactory.newInstance();
              Transformer trans = tf.newTransformer();
              trans.transform(new DOMSource(doc), new StreamResult(os));
    the "shippedPedigree.xml" i used to sign:
    <?xml version="1.0" encoding="UTF-8"?>
    <ped:pedigree xmlns:ped="urn:epcGlobal:Pedigree:xsd:1" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ped:shippedPedigree id="123">
    <ped:documentInfo>
    <ped:serialNumber>2233</ped:serialNumber>
    <ped:version>ped:version</ped:version>
    </ped:documentInfo>
    <ped:signatureInfo>
    <ped:signerInfo>
    <ped:name>Joe Doe</ped:name>
    <ped:title>Manager</ped:title>
    <ped:telephone>800-521-6010</ped:telephone>
    <ped:email>[email protected]</ped:email>
    <ped:url>www.kittinginc.com</ped:url>
    </ped:signerInfo>
    <ped:signatureDate>2001-12-31T12:00:00</ped:signatureDate>
    <ped:signatureMeaning>Certified</ped:signatureMeaning>
    </ped:signatureInfo>
    <ped:itemInfo>
         <ped:lot>123</ped:lot></ped:itemInfo>
    </ped:shippedPedigree></ped:pedigree>
    ------------------------------------------------------------------------

    Sabarisri N wrote:
    Hi All,
    my xml is like below.
    <ns1:abcd>
    <ns2:a>1</ns2:a>
    <ns2:b>2</ns2:b>
    </ns1:abcd>
    If i try retrieving the value of the root element of this xml document,
    Node myroot=doc.getDocumentElement();
    String result=myroot.getNodeName();
    My output is ns1:abcd .. i want only "abcd"...
    The parser is returning the correct rootNodeName i.e ns1:abcd. rootNodeName always goes with the given input and returns the root element as is.
    >
    My xml will not always have same namespaces.. from the incoming xml i should first check, for the namespaces..Please give me some idea.
    I guess.. I need some namespace evaluation to be set..
    Refer below link it'll give idea of identifying XML-NAMESPACE-PREFIX
    http://java.sun.com/developer/Books/xmljava/ch03.pdf
    http://download.oracle.com/javaee/1.4/tutorial/doc/JAXPSAX9.html
    Please help me in this regard.
    Thanks,
    Sabarisri. N

  • Sign XML document without KeyPairGenerator

    Hi everyone -----> System.out.println("HEEEELP!");
    I have a problem for signing and validating an XML document, using the Apache toolkit and JWSDP.
    Example :
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);
    boolean coreValidity = signature.validate(valContext);
    When I genreate keys with KeyPairGenerator, everything works fine (The KeyPairGenerator uses crt coefficient). But If I use my own RSA keys (modulus, private and public exponent), I can sign but not validate the XML document, ie the signature value of the signedInfo. Strange thing : I'm sure the keys are correct. I can encyrpt and decrypt messages using my own validation program with these keys.
    Does anyone know how to sign and validate XML documents with its own keys ?
    I can reply more details if necessary ...
    Any help would be very very appreciated :)

    You're putting words in my mouth, I never mentioned DOM.
    What I'm saying is that JAXB is not of concern to your requirements. Whatever happens to the objects after they are created from XML is up to you. It has done its job, the XML has been transformed into object set A. Perhaps at some point in time it can do some more work for you, when you have an object set B that need to be written to an XML structure. How you get from A to B, that's up to you.
    But perhaps there is a more suited tool for the job that actually deals with XML transformations (hint hint). You could probably hack something together with basic SAX. Heck, if all you want to do is replace easy to identify lines of data with other lines of data a BufferedReader/BufferedWriter could already work.

  • Difference Btwn Trash Can and Red Minus Sign when Deleting Documents

    Hello, can someone please confirm for me the technical difference between the Trash Can button and the Red Minus sign button in the Documentation tabs? For instance, does the red minus sign delete the document from the project whereas the trash can also removes the document from the Knowledge Warehouse database? Also, how does this translate to deleting links to documents from the documentation tabs?
    Thank you,
    M. Neal

    Hello Megan,
    1. Trash can icon indicates basically as you stated it: With this button you can physically delete documents from the Knowledge Warehouse. Before doing so, however, the system automatically checks if the document to be deleted is still used by any other element in a structure, let's say another process (where-used). If so, you first have to detach this document from the affected processes - which takes us to the red minus icon.
    2.  Red minus icon: This translates to removing your document assignment from the documentation tabs (so basically to deleting document links). The document is not physically deleted - it stays in the Knowledge Warehouse database and can be re-assigned - if needed.
    I hope this answers your questions.
    Best regards,
    Doreen Baseler

  • Difference between two xml documents

    Hi,
    I have two xml documents docA and docB that loos like this,
    <root>
    <a>
        <b>...</b>
        <c>...</c>
        <d>...</d>
    </a>
    <a>
    </a>
    </root>I want to compare them and get a new xml document that consists of every <a> thats only in docB (I know that the only two cases is that a given <a> is either in both or only in docB) is there any library that can help me with this? I've looked at xmlunit but I could only get it to either just return true/false or give a complete list of differences.
    /Andreas

    You have not really specified precisely what you want to compare on. XQuery 1.0 and XPath 2.0 have a function deep-equal that might be able to do what you want so an XQuery like
    <root>{
      doc('docB.xml')/root/a[not(some $a in doc('docA.xml')/root/a satisfies deep-equal(., $a))]
    </root>could give you the result you want, depending on whether the [specification of deep-equal|http://www.w3.org/TR/xpath-functions/#func-deep-equal] matches your expectation.
    As the SUN Java JRE has no XQuery support you need a third party library such as [Saxon 9|http://saxon.sourceforge.net/] .

  • Difference between facelets and jsp xml in Document Type

    I want difference between facelets and jsp in Document Type in JDeveloper 11gR2 (11.1.2)
    Thanks
    Edited by: Amr Ahmed on Jun 8, 2011 7:46 AM

    Let's see.
    Facelets creates a facelets page
    JSP creates a JSP page
    {noformat}:){noformat}
    Facelets is the "official" view language for JSF 2.0
    http://www.realdevelopers.com/blog/development/facelets-vs-jsp should give you some more insight as well.
    John

  • 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?

  • XMLSig: validating an XML document incl. all certificates

    Hello,
    I have created a XML document signed with a certificate. I have added whole certification chain (first entry the users certificate, last CA) in the document:
    X509Data x509d = kif.newX509Data(Arrays.asList(myChain));
    ki = kif.newKeyInfo(Collections.singletonList(x509d));
    ...The document validates perfectly with XMLSignature.validate method but I am not sure if this method validates the certificates. I suppose not.
    Are there any standard processes to validate X509 certification chain from XML-signed document? Or do I have to retrive and verify all certificates myself? If so how? I have my very own KeySelector but I do not have idea how to use it to retreive my certificates:
        private static class X509CertKeySelector extends KeySelector {
            @SuppressWarnings({"LoopStatementThatDoesntLoop"})
            public KeySelectorResult select(KeyInfo keyInfo,
                                            KeySelector.Purpose purpose,
                                            AlgorithmMethod method,
                                            XMLCryptoContext context)
                    throws KeySelectorException {
                if (keyInfo == null) {
                    throw new KeySelectorException("Null KeyInfo object!");
                List list = keyInfo.getContent();
                for (Object aList : list) {
                    XMLStructure xmlStructure = (XMLStructure) aList;
                    if (xmlStructure instanceof X509Data) {
                        try {
                            X509Data xd = (X509Data) xmlStructure;
                            X509Certificate[] certs = (X509Certificate[]) xd.getContent().toArray(new X509Certificate[0]);
                            return new X509CertChainSelectorResult(certs);
                        } catch (ClassCastException e) {
                            throw new KeySelectorException("X509Data must contain X509 certificate list", e);
                    } else {
                        throw new KeySelectorException("KeyInfo doesn`t contain X509Data");
                throw new KeySelectorException("No KeyValue element found!");
        private static class X509CertChainSelectorResult implements KeySelectorResult {
            private X509Certificate[] certificates;
            X509CertChainSelectorResult(X509Certificate[] certs) {
                this.certificates = certs;
                for (X509Certificate c: certificates) {
                    System.out.println(c);
            public X509Certificate[] getCertificates() {
                return certificates;
            public Key getKey() {
                if (certificates != null && certificates.length > 0) {
                    PublicKey publicKey = certificates[0].getPublicKey();
                    return publicKey;
                } else
                    return null;
        }ps - the certificates are stored in BASE64 encoding, I would prefer something "nicer" XMLSig allows to store certificates in the XML-way... whats the trick to store the certification chain in the XML human-readable format?

    Verifying
    the chain (with the root certificate in a secure
    store) is only part of the whole verifying process.
    You also need to verify that the signature is over
    the correct data, and that the correct
    transformations have taken place. This is missing
    from the documentation. You might also need a CRL or
    other way to revoke certificates, depending on the
    usage of the library.Thank you but what you mean with correct data and transformation? XMLDigSig will do it for me, wont it? You are abolutely right with CRLs, in my TODO list... :-D

  • Verifying OpenOffice document signature

    Hi all,
    When you sign an ODT document throught OpenOffice interface, an XML Signature file is generated inside ODT file structure: documentsignatures.xml.
    I'm trying to verify this XML Signature using JDK 6 JSR 105 implementation, but i have some problems ...
    I try a simple verification uncompressing ODT file (JAR file) and accessing documentsignatures.xml directly:
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document d = db.parse("documentsignatures.xml");
    NodeList nl = d.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    X509Certificate cert = X509Certificate.getInstance(new FileInputStream("rootca.der"));
    DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), nl.item(0));
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
    XMLSignature signature = fac.unmarshalXMLSignature(valContext);
    if (signature.validate(valContext)) {
        System.out.println("OK");
    else {
        System.out.println("BAD SIGNATURE");
    }But i get an exception:
    Exception in thread "main" javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: java.lang.NullPointerException
    at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(DOMReference.java:352)
    at org.jcp.xml.dsig.internal.dom.DOMReference.validate(DOMReference.java:311)
    at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.validate(DOMXMLSignature.java:230)
    at VerifyODTSignature.main(VerifyODTSignature.java:63)It seems like a problem with reference resolution ... So i modify the initial code to handle an "URIDereferencer":
    DOMValidateContext valContext = new DOMValidateContext(cert.getPublicKey(), nl.item(0));
    valContext.setURIDereferencer(new URIDereferencer() {
           public Data dereference(URIReference uriReference, XMLCryptoContext context) throws URIReferenceException
                    OctetStreamData osd = null;
                    try
                        osd = new OctetStreamData(new FileInputStream("/referenced_xml_files/" + uriReference.getURI()));
                    catch (Exception e)
                        e.printStackTrace();
                    return osd;
            });But i get an:
    Exception in thread "main" javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.dsig.TransformException: java.lang.ArrayIndexOutOfBoundsException: 23
    at org.jcp.xml.dsig.internal.dom.DOMReference.transform(DOMReference.java:390)
    at org.jcp.xml.dsig.internal.dom.DOMReference.validate(DOMReference.java:312)
    at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.validate(DOMXMLSignature.java:230)
    at VerifyODTSignature.main(VerifyODTSignature.java:62)I supose that i'm not usign URIDereferencer properly, but i could'n find documentation or samples regarding this issues :(
    Please, somebody can help me?
    Thanks in advance!!!!
    Edited by: borillo on Mar 4, 2008 8:23 AM

    Hi all,
    Finally Sean Mullan have found the problem. Here is his answer:
    I finally found some time to debug into this problem. It is a bug in the canonicalization code and I will open a bug to have it fixed in JDK 6. It is only triggered if an element has over 23 attributes and the
    office element in content.xml has 24 attributes!
    The only workaround I can think of is to use a Apache XMLSec jar and override the implementation in the JDK. You can do this with the endorsed override mechanism of the JDK. What you need to do is download the following jars:
    1) Java XMLSec (1.4 or later): http://xml.apache.org/security/dist/java-library/
    2) Commons Logging:
    http://commons.apache.org/downloads/download_logging.cgi
    You need the commons logging library because the Apache implementation uses that instead of the JDK logging mechanism.
    Put these two jars in a lib directory, and then specify that lib directory as the endorsed directory when running your application, for example:
    java -Djava.endorsed.dirs=lib ...
    This should work.
    HTH,
    Sean
    """

  • Add tags to an archieved XML document

    Hi experts :
      I'm archiving an invoice digitally signed in XML format.
      Due to legal restrictions with the signature method in Spain, the first 2 lines of the XML document (i.e, the lines including the format UTF-8 and the reference to the CSS file) have to be removed before signing the invoice.
      So, when users try to display the document using FB03, as there is no reference to the CSS file, the only they can see is the XML coding instead of the invoice.
      My first tought was to add the header with these 2 lines before archieving the XML, but it isn't possible due to audit requirements (the original XML and the one including the first 2 lines are differents, so can't change the invoice before archiving it).
      We're working with 4.6C version.
    Anyone knows the way to add these 2 lines when displaying the XML file in FB03?.
    Thanks in advance for your help.
    Regards,
    Carlos.

    Sorry, SAP version is 6.20

  • Parse and output XML document while preserving attribute order

    QUESTION: How can I take in an element with attributes from an XML and output the same element and attributes while preserving the order of those attributes?
    The following code will parse and XML document and generate (practically) unchanged output. However, all attributes are ordered a-z
    Example: The following element
    <work_item_type work_item_db_site="0000000000000000" work_item_db_id="0" work_item_type_code="3" user_tag_ident="Step" name="Work Step" gmt_last_updated="2008-12-31T18:00:00.000000000" last_upd_db_site="0000000000000000" last_upd_db_id="0" rstat_type_code="1">
    </work_item_type>is output as:
    <work_item_type gmt_last_updated="2008-12-31T18:00:00.000000000" last_upd_db_id="0" last_upd_db_site="0000000000000000" name="Work Step" rstat_type_code="1" user_tag_ident="Step" work_item_db_id="0" work_item_db_site="0000000000000000" work_item_type_code="3">
    </work_item_type>As you may notice, there is no difference in these besides order of the attributes!
    I am convened that the problem is not in the stylesheet.xslt but if you are not then it is posted bellow.
    Please, someone help me out with this! I have a feeling the solution is simple
    The following take the XML from source.xml and outputs it to DEST_filename with attributes in a-z order
    Code:
    private void OutputFile(String DEST_filename, String style_filename){
         //StreamSource stylesheet = new StreamSource(style_filename);
         try{
              File dest_file = new File(DEST_filename);
              if(!dest_file.exists())
                  dest_file.createNewFile();
              TransformerFactory tranFactory = TransformerFactory.newInstance();
              Transformer aTransformer = tranFactory.newTransformer();
              aTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
              Source src = new DOMSource("source.xml");
              Result dest = new StreamResult(dest_file);
              aTransformer.transform(src, dest);
              System.out.println("Finished");
         catch(Exception e){
              System.err.print(e);
              System.exit(-1);
        }

    You can't. The reason is, the XML Recommendation explicitly says the order of attributes is not significant. Therefore conforming XML serializers won't treat it as if it were significant.
    If you have an environment where you think that the order of attributes is significant, your first step should be to reconsider. Possibly it isn't really significant and you are over-reaching in some way. Or possibly someone writing requirements is ignorant of this fact and the requirement can be discarded.
    Or possibly your output is being given to somebody else who has a defective parser which expects the attributes to be in a particular order. You could quote the XML Recommendation to those people but often XML bozos are resistant to change. If you're stuck writing for that parser then you'll have to apply some non-XML processing to your output to fix it up on their behalf.

Maybe you are looking for

  • Upload Error message: HTTPS protocol is not supported

    Hi,    Whenever I do a quick par upload i'm getting an 'Operation failed' message to check sap-plugin.log.    Log says Upload Error message: HTTPS protocol is not supported, please ensure this server is not using HTTPS. My webdynpro applications are

  • Videos in email have sound but no picture since I updated to Lion

    I recently updated to Lion and now when I open videos in email I have sound but no picture.

  • Equivalent of POST_COMMIT in BC4J

    In Oracle Forms there is the post-commit trigger. In it we write code that needs to be called after records have been committed to the database. How do we achieve the equivalent functionality in BC4J using JDEV 3.1? I tried to put the code in the doD

  • How to edit tool bar?

    How to edit tool bar? thanks!

  • T61 Warranty Status

    One day after  i purchased this laptop i checked the warranty status ( in http://www-307.ibm.com/pc/support/site.wss/document.do?lndocid=LOOK-WARNTY#sw ) and it was said the warrany will expired onJuly  2011 , and then i went to IBM service center to