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.

Similar Messages

  • 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 signing XML when applying XPATH2 filer

    I have a problem when applying XPATH2 filter to a XML Signature, because it inserts the namespaces from the main XML node to all descendants. I'm doing this:
    1. XMLSignatureFactory fac = XMLSignatureFactory.getInstance(AppConstants.DOM);
    2. XPathType tipoFiltro = new XPathType("//mainNode", Filter.INTERSECT);
         3. ArrayList<XPathType> lista = new ArrayList<XPathType>();
         4. lista.add(tipoFiltro);
         5. XPathFilter2ParameterSpec listaXPath = new XPathFilter2ParameterSpec(lista);
         6. Transform filtro = fac.newTransform(Transform.XPATH2, listaXPath);
         7. Transform enveloped = fac.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null);
         8. ArrayList<Transform> listaTransformadas = new ArrayList<Transform>();
         9. listaTransformadas.add(filtro); //If comented, no problem
         10. listaTransformadas.add(enveloped);
         11. ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), listaTransformadas,null,null);     
         12. SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,(C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
         ... more code (KeyInfo,...)
         13. DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
         14. XMLSignature signature = fac.newXMLSignature(si, ki);
         15. signature.sign(dsc);
         If I do the same without XPATH2 filter (Line 9 commented), it doesn't insert the namespaces in any node (they're only in the main node). The objetive of applying this xpath2 filter is to exclude XSLT reference (<?xml-stylesheet type="text/xsl" href=".\xsl\myTemplate.xsl"?>) from the signature.
         How can I avoid this situation? Is there another method for signing XML documents that allows this? Is there another way to exclude XLST reference that doesn't insert namespaces in all nodes?

    I have a problem when applying XPATH2 filter to a XML Signature, because it inserts the namespaces from the main XML node to all descendants. I'm doing this:
    1. XMLSignatureFactory fac = XMLSignatureFactory.getInstance(AppConstants.DOM);
    2. XPathType tipoFiltro = new XPathType("//mainNode", Filter.INTERSECT);
         3. ArrayList<XPathType> lista = new ArrayList<XPathType>();
         4. lista.add(tipoFiltro);
         5. XPathFilter2ParameterSpec listaXPath = new XPathFilter2ParameterSpec(lista);
         6. Transform filtro = fac.newTransform(Transform.XPATH2, listaXPath);
         7. Transform enveloped = fac.newTransform(Transform.ENVELOPED,(TransformParameterSpec) null);
         8. ArrayList<Transform> listaTransformadas = new ArrayList<Transform>();
         9. listaTransformadas.add(filtro); //If comented, no problem
         10. listaTransformadas.add(enveloped);
         11. ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), listaTransformadas,null,null);     
         12. SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,(C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
         ... more code (KeyInfo,...)
         13. DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
         14. XMLSignature signature = fac.newXMLSignature(si, ki);
         15. signature.sign(dsc);
         If I do the same without XPATH2 filter (Line 9 commented), it doesn't insert the namespaces in any node (they're only in the main node). The objetive of applying this xpath2 filter is to exclude XSLT reference (<?xml-stylesheet type="text/xsl" href=".\xsl\myTemplate.xsl"?>) from the signature.
         How can I avoid this situation? Is there another method for signing XML documents that allows this? Is there another way to exclude XLST reference that doesn't insert namespaces in all nodes?

  • How to extract the actual XML document from soap message?

    My problem is " how to extract the actual XML document from soap message? "
    i just want to extract the attachment i.e. (pure XML document without any soap header or envolope).
    i could be ver thank full if u could solve my problem.
    [email protected]

    Hi,
    This is some skeleton code for extracting an attachment from a SOAPMessage.
    import javax.activation.DataHandler.;
    import javax.xml.soap.*;
    import javax.xml.message.*;
    Iterator allAttachments = message.getAttachments();
    AttachmentPart ap1 = null;
    while(allAttachments.hasNext()){
    ap1 = (AttachmentPart)allAttachments.next();
    //Check that the attachment is correct one. By looking at its mime headers
    //Convert the attachment part into its DOM representation:
    if(ap1.getContentType() == "text/xml"){
    //Use the activation dataHandler class to extract the content, then create a StreamSource from
    //the content.
    DataHandler attachmentContent = ap1.getDataHandler();
    StreamSource attachmentStream = new StreamSource(attachmentContent.getInputStream());
    DOMResult domAttachment = getDOMResult(attachmentStream);
    domAttachment holds an xml representation of the attachment.
    Hope this helps.

  • XML-Document with extern DTD

    Hello!
    How can the Oracle XML-Parser parse a XML-Document without the
    XML-Declaration. There is no information about the Version and
    the DTD in the XML-Document. Can I use an extern DTD?
    Thanks,
    Peter
    null

    Peter Roemer (guest) wrote:
    : Hello!
    : How can the Oracle XML-Parser parse a XML-Document without the
    : XML-Declaration. There is no information about the Version and
    : the DTD in the XML-Document. Can I use an extern DTD?
    : Thanks,
    : Peter
    Have you tried oracle.xml.parser.v2.XMLParser.setDoctype(DTD)?
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    null

  • XML document  -  attribute

    Is it possible to retrieve the value of a certain attribute within a certain tag i a XML document without parsing the entire document ?
    // The_Iceman

    If you used SAX, you could throw a SAXException when you reached the element in question, thus ending the parse abnormally.

  • 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

  • Copy Signed XML without altering it

    Hi everyone,
    I have a windows 2003 svr with JRE 1.6.0_18, and xmlsec v1.2.97 jar imported.
    I'm building a new module of an existing application, which creates xml for invoices, signs them, and sends them to another company. This signed XMLs are stored on the filesystem.
    I need to copy one of such xml files, lets call it A.xml (with valid signature, I checked using DOM's security validation tools) into another xml, lets say B.xml, without altering the contents of A.xml ( therefore voiding the signature ).
    Then I have to sign B.xml
    I have tried the following so far:
    1. using Filereader to copy byte by byte to B.xml.
    2. using inputstreamreaders (with apropriate encoding parameter) and copy line by line.
    3. using DOM to add new node, and Transformer API to generate B.xml (proper enconding parameters are being set)
    when I run a signature validation on B.xml, the signature has become invalid.
    One intresting thing though, is that if I use method 1 to copy A.xml to another xml having only A's tree, this new XML has a valid signature.
    Has anyone gone through something similar?
    I'm I missing something?
    or is it that whenever I insert an XML into another, it's signature will become void?
    Thank you in advance for your help and time!
    Regards,
    Reynod

    Well, #1 should work. Although I didn't understand what you said about "A's tree". Either you copy the file byte for byte (in which case you don't break the signature) or you produce something different (in which case you break the signature).
    Anything which changes the contents of the XML should generate a document whose signature is invalid. That's the main point of signing a document.

  • 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

  • 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

  • Signing a document multiple times without saving it?

    Hello all,
    Can someone please tell me how do we sign a document multiple times without having to save the document after each signature?
    For instance, I am a realtor and have to sign the contract about 3-4 times. However, when I sign it, Acrobat 8 prompts me to sign after each signature.
    When I was using Acrobat 7, I could sign as much as I want and then save it. This is much more efficient and practical.
    Can anyone advise me?
    Thanks in advance.
    Geo

    Hi Geo,
    It may be more cumbersome in version 8 (and 9), but it's safer. In version 7 and earlier when you signed, Acrobat did everything in memory. You weren't prompted to save the file to disk until you wanted to close the file. The problem is computer memory is where the bad guys get into to make changes. The majority of computer vulnerabilities occur when the hacker escapes the allotted memory space (aka buffer overflows) and reads and writes to memory address that they shouldn't be in. Think of memory being divided up like a row of houses along a block. The bad guy gets out of his house and into yours, and that's where bad things happen.
    Beginning with version 8, signature operation all take place on disk, not in memory. It's slower, and as you pointed out it's more cumbersome, but it's safer. The file is committed to disk (the hard drive) before the signature is created and the signed bytes cannot be manipulated in the middle of the signing procedure.
    Interestingly (at least to me), when we had this discussion four or five years ago when the change was made, the example used was of mortgage contact being signed where any of the terms could be changed in memory prior to the signature being completed. It was just a bunch of geeky engineers sitting around a table discussing possible vulnerabilities with the current signing operation (i.e. signing in memory). To see the theoretical example in actual use is kind of exciting (granted I don't get out much ).
    Steve

  • Sign documents without entering a signature password?

    On the PC version of Acrobat you can sign documents very easily without entering in a password every time you want to sign a document.  On the mac version it appears that you have to enter a pwd every single time you sign a document... this is very frustrating when signing 20-30 docs at a time.  Is there a way to disable the pwd requirement in Acrobat X for Mac?

    Hi sojourner166,
    For the sake of discussion lets limit how a digital ID is access to either directly from a file or through the operating system (OS). Both the file & the OS methods allow the user to access the private key (that's the part that is password protected) without having to enter the password each time.
    On Windows the OS loads the digital ID into the Windows Certificate Store an on the Mac OS it uses Keychain Access. On Windows when you import a digital ID, if you don't select High Assurance (which is off by default) the OS assumes that if you could log in using your password that's good enough and will allow access to the private key without prompting you for the password. On the Mac, Keychain Access has UI which lets you control whether you need to confirm the password or not.
    When you are signing with a digital ID in either of the OS based systems Acrobat say to the OS "give me access to the private key so I can do a signature operation". The OS then checks the setting and either grants access without further ado, or, it says to Acrobat "before I'll give you access to the private key you've got to tell me the password". Acrobat in turn puts up a dialog asking the user for the password. You type it in, hit the Sign button and Acrobat says to the OS, "okay here you go, now can I get access to the private key so I can finish this signing operation?". The OS checks the password that Acrobat sent along and if it's correct grants access to the private key, and if it's not correct returns an error code, which causes the signing operation to abort.
    If the digital ID is residing in a file then the OS sits on the sideline and Acrobat handles the password work itself. If you are using a digital ID that resides in a file you can set the password timeout option through the Acrobat UI. In the Security Setting dialog expand Digital IDs in the tree view and then select Digital ID Files. From there you can click on the Password Timeout button and adjust how often you want to be prompted for a password to access the private key.
    Here's a picture of what you are looking for:
    If you are using a digital ID listed under Keychain Digital IDs let me know and I'll work up those steps for you.
    Hope this helps,
    Steve

  • Cannot unmarshal an XML document to a JavaBean without its XML Schema?

    Hi,
    2 questions:
    1. I have an XML document and have the corresponding JavaBean (the 2 already exist). I tried to unmarshall the XML document using JAXB but I get a strange error of duplicate attributes/elements no matter if I use the annotations @XmlElement, @XmlAttribute etc. The code I use is simply:
    JAXBContext jc = JAXBContext.newInstance("MyClass.class");
    Unmarshaller u = jc.createUnmarshaller();
    MyClass myClass = (MyClass) u.unmarshal(new File("myxml.xml"));Do I always have to create the .xsd file of my xml, create the JavaBean using xjc and then run the above?
    2. Can I use JAXB to parse an XML file to a JavaBean but, because the xml file is a complicated one, to use xpaths to get the attributes?
    E.g. to use something like this?
    @XmlAttribute ("xpath/to/attribute")Thank you in advance for your replies.
    Best regards,
    John.

    Hi,
    2 questions:
    1. I have an XML document and have the corresponding JavaBean (the 2 already exist). I tried to unmarshall the XML document using JAXB but I get a strange error of duplicate attributes/elements no matter if I use the annotations @XmlElement, @XmlAttribute etc. The code I use is simply:
    JAXBContext jc = JAXBContext.newInstance("MyClass.class");
    Unmarshaller u = jc.createUnmarshaller();
    MyClass myClass = (MyClass) u.unmarshal(new File("myxml.xml"));Do I always have to create the .xsd file of my xml, create the JavaBean using xjc and then run the above?
    2. Can I use JAXB to parse an XML file to a JavaBean but, because the xml file is a complicated one, to use xpaths to get the attributes?
    E.g. to use something like this?
    @XmlAttribute ("xpath/to/attribute")Thank you in advance for your replies.
    Best regards,
    John.

  • 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);          
        }

  • Encoding Type XML Document

    Hi,
    I have an XML document which is essentially data pulled from the craigs list website. It contains alot of Ampersands and pound signs and other stuff which i have been told does not follow the UTF-8 encoding which i put in the tag at the top of the document. Could someone tell me what the correct encoding would be so that i can parse the file using the Java DOM parser without it throwing out errors such as;
    Invalid byte 1 of 1-byte UTF-8 sequence.
    Thanks Alot
    Richard.

    Sounds like you don't know too much about XML and encoding. Try reading this tutorial, it's long but it's thorough:
    [http://skew.org/xml/tutorial/|http://skew.org/xml/tutorial/]
    That should take care of the XML part. Now you need to know the Java part: the simple rule is to not create XML documents if you don't know what encoding they will have. Your best bet is to write them using UTF-8 in the first place. I don't know how you're writing the documents but my bet is you're using plain old Java I/O. In that case use an OutputStreamWriter which specifies UTF-8 for the encoding. Here's a link to the Java I/O tutorial if you don't know how to do that:
    [http://java.sun.com/docs/books/tutorial/essential/io/|http://java.sun.com/docs/books/tutorial/essential/io/]

Maybe you are looking for

  • Changing Non key field to Key field in a custom table

    Hello Abap gurus: I have a requirement in which i need to change a non key field in my custom table(Z TABLE) to key field. For example; i have field sequence as field 1  key field field 2 key field field 3 key field field 4 non-key field field 5 non-

  • Cannot install windows support software

    1 month old MBP running 10.7.1 trying to BootCamp  Win7 Ultimate x64 (all OSX updates have been installed that were found prior to attempted install) Some help would be greatly appreciated. I have installed Windows to a BootCamp partition but I'm una

  • BSOD every 20 minutes running windows XP in boot camp partition

    Has anyone else had this problem? Everything was running fine for a couple of months on my new mac OS X until around the time I installed the recommended updater to Boot Camp 2.1, then Windows XP started crashing every 20 minutes exactly, BCCode : 10

  • USB alert

    As I begin to sync music into my Nano I am alerted that my USB connection is 1.0 and I should connect to a USB 2.0 port to improve performance (speed). If theUSB ports on my computer are 1.0 port is it possible to upgrade to 2.0?

  • Windows Explorer error when downloading through USB cable

    Moved for greater exposure