Java XML Digital Signature API, how to sign different files

Hello,
I need to sign several files: binary and/or xml (in some cases just part of xml), and to implement digitla signatures in xAdes standard. So I'm looking to use Java XML Digital signature API, but can't find any examples, that would cover issues I encountered:
How to sign binary file?
Just to sign some simple "aaa.png" file and have it's signature in XML. How in right way to create referece?
(should it be something like: Reference ref = fac.newReference("aaa.png", fac.newDigestMethod(DigestMethod.SHA1, null), null, null, null); )
And how to pass file for signing? what to add/change to this code:
Document doc = dbf.newDocumentBuilder().parse(new FileInputStream("aaa.png"));
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());
(I have only found some information about needing to "dereference" or so - but no examples, how to make things work.)
How to sing several different files?
As I wrote before, several files needs to be signed, but in all examples, it's only one Document object (and only one file), how/where to add more files and if API will be capable to deal with such thing?
In one of examples what I have to achive was such code:
<Reference URI="aaa.png" xmlns="http://www.w3.org/2000/09/xmldsig#">
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
<DigestValue>8rl/xzjAnE4yQQ2LTBvFTU2JH+c=</DigestValue>
</Reference>
If I do write code like: "fac.newReference("aaa.png", <...> );
I'll get an error during signing: signature.sign(dsc);
*"java.net.MalformedURLException: no protocol: aaa.png"*
How to avoid this?
Also, from exmaple (what to reach) above:
<Reference URI="aaa.png" xmlns="http://www.w3.org/2000/09/xmldsig#">
There is additional attribute "xmlns=<...>" - the question is if it is possible to add it by XMLSignatureFactory.newReference ?
Java API adds a lot of prefixes "ds:" , like:
<...>
<ds:Reference URI="file:/D:/try5/SignableMetadata0.xml">
<ds:Transforms>
<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
</ds:Transforms>
<...>
Is it possible to avoid them?
Any help on any of these questions would be very appreciated

Hi,
I would like to sign a specific part of a xml message [Only the contents under the <Buyer> tag]. I have also pasted the code which i used to do this. I am getting an output xml after the xml is signed, but when I validate the xml , the xml is valid even after I change the xml contents. Could you pls tell me what I am doing wrong here. I want to know whether the xpath implementation which I have done is correct.
<?xml version="1.0" encoding="UTF-8"?>
<PurchaseOrder>
<Item number="130046593231">
<Description>Video Game</Description>
<Price>10.29</Price>
</Item>
*<Buyer id="8492340">*
*<Name>My Name</Name>*
*<Address>*
*<Street>One Network Drive</Street>*
*<Town>Burlington</Town>*
*<State>MA</State>*
*<Country>United States</Country>*
*<PostalCode>01803</PostalCode>*
*</Address>*
*</Buyer>*</PurchaseOrder>
// The code which i have used to perform the xpath transformation.
          XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
     XPathFilterParameterSpec xpathFilter = new XPathFilterParameterSpec("PurchaseOrder/Buyer");
          javax.xml.crypto.dsig.Reference ref = fac.newReference
          ("", fac.newDigestMethod(DigestMethod.SHA1, null),
          Collections.singletonList
          (fac.newTransform
          (Transform.XPATH, xpathFilter)),
          null, null);
          SignedInfo si = fac.newSignedInfo
          (fac.newCanonicalizationMethod
          (CanonicalizationMethod.INCLUSIVE,
          (C14NMethodParameterSpec) null),
          fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
Collections.singletonList(ref));
// Load the KeyStore and get the signing key and certificate.
     KeyStore ks = KeyStore.getInstance("JKS");
     char[] password = "changeme".toCharArray();
     ks.load(new FileInputStream("c:\\KeyStore"), password);
     KeyStore.PrivateKeyEntry keyEntry =
     (KeyStore.PrivateKeyEntry) ks.getEntry
     ("EISKeys", new KeyStore.PasswordProtection(password));
     X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
     // System.out.println("X509Certificate:"+cert);
     // 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));
     // Instantiate the document to be signed.
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     dbf.setNamespaceAware(true);
     Document doc = dbf.newDocumentBuilder().parse
     (new FileInputStream("C:\\Life2012\\DigSign\\ACORD_Request.xml"));
     NodeList rootChildList = doc.getDocumentElement().getChildNodes();
     Node bodyNode = null;
     for(int i=0;i<rootChildList.getLength();i++){
          if("Buyer".equalsIgnoreCase(rootChildList.item(i).getLocalName())){
               bodyNode = rootChildList.item(i);
               System.out.println("Body Node is obtained"+bodyNode);
               break;
     // Create a DOMSignContext and specify the RSA PrivateKey and
     // location of the resulting XMLSignature's parent element.
     //DOMSignContext dsc = new DOMSignContext
     // (keyEntry.getPrivateKey(), doc.getDocumentElement());
          // Sign only the body node
     DOMSignContext dsc = new DOMSignContext
     (keyEntry.getPrivateKey(), bodyNode);
     // 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);

Similar Messages

  • Implementing XAdES in Java XML Digital Signature API

    Hi,
    I've got some problems with implementing XAdES standard with Java XML Digital Signature API. Below is a code (SignatureTest1), that produces a digital signature with some XAdES tags placed in <ds:Object> tag. The signature is later validated with a Validator class. Everything works fine, until I set a XAdES namespace (SignatureTest1.xadesNS="http://uri.etsi.org/01903/v1.3.2#"). In this case validation of XAdES elements fails.
    The reason of validation failture is a difference between arguments passed to a digest method when document is being signed and validated. When the document is being signed a log looks like this:
    FINER: Pre-digested input:
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.DigesterOutputStream write
    FINER: <SignedProperties xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SignP"></SignedProperties>
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference digest
    FINE: Reference object uri = #SignP
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference digest
    FINE: Reference digesting completed,but while validating:
    FINER: Pre-digested input:
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.DigesterOutputStream write
    FINER: <SignedProperties xmlns="http://uri.etsi.org/01903/v1.3.2#" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="SignP"></SignedProperties>
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference validate
    FINE: Expected digest: MAQ/vctdkyVHVzoQWnOnQdeBw8g=
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMReference validate
    FINE: Actual digest: D7WajkF0U5t1GnVJqj9g1IntLQg=
    2007-08-21 15:38:44 org.jcp.xml.dsig.internal.dom.DOMXMLSignature validate
    FINE: Reference[#SignP] is valid: falseHow can I fix this?
    Signer class:
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.security.KeyPair;
    import java.security.KeyPairGenerator;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.crypto.dom.DOMStructure;
    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.XMLObject;
    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.KeyValue;
    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.Element;
    import org.w3c.dom.NodeList;
    import com.sun.org.apache.xml.internal.security.utils.IdResolver;
    public class SignatureTest1 {
         public static String xadesNS=null;//"http://uri.etsi.org/01903/v1.3.2#";
         public static String signatureID="Sig1";
         public static String signedPropID="SignP";
         public static void main(String[] arg) {
            try{
              XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
              List<Reference> refs = new ArrayList<Reference>();
              Reference ref1 = fac.newReference
                  ("", fac.newDigestMethod(DigestMethod.SHA1, null),
                      Collections.singletonList
                    (fac.newTransform
                   (Transform.ENVELOPED, (TransformParameterSpec) null)),
                   null, null);
              refs.add(ref1);
              Reference ref2 = fac.newReference("#"+signedPropID,fac.newDigestMethod(DigestMethod.SHA1,null),null,"http://uri.etsi.org/01903/v1.3.2#SignedProperties",null);
              refs.add(ref2);
              SignedInfo si = fac.newSignedInfo
                  (fac.newCanonicalizationMethod
                   (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
                   fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
                   refs);
             KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
              kpg.initialize(512);
              KeyPair kp = kpg.generateKeyPair();
              KeyInfoFactory kif = fac.getKeyInfoFactory();
              KeyValue kv = kif.newKeyValue(kp.getPublic());
             KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
              DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
              dbf.setNamespaceAware(true);
              Document doc =
                  dbf.newDocumentBuilder().parse("purchaseOrder.xml");
              DOMSignContext dsc = new DOMSignContext
                  (kp.getPrivate(), doc.getDocumentElement());
              dsc.putNamespacePrefix(XMLSignature.XMLNS, "ds");
              Element QPElement = createElement(doc, "QualifyingProperties",null,xadesNS);
            QPElement.setAttributeNS(null, "Target", signatureID);
            Element SPElement = createElement(doc, "SignedProperties", null,xadesNS);
            SPElement.setAttributeNS(null, "Id", signedPropID);
            IdResolver.registerElementById(SPElement, signedPropID);
            QPElement.appendChild(SPElement);
            Element UPElement = createElement(doc, "UnsignedProperties", null,xadesNS);
            QPElement.appendChild(UPElement);
            DOMStructure qualifPropStruct = new DOMStructure(QPElement);
            List<DOMStructure> xmlObj = new ArrayList<DOMStructure>();
            xmlObj.add(qualifPropStruct);
            XMLObject object = fac.newXMLObject(xmlObj,"QualifyingInfos",null,null);
            List objects = Collections.singletonList(object);
            XMLSignature signature = fac.newXMLSignature(si, ki,objects,signatureID,null);
              signature.sign(dsc);
              OutputStream os = new FileOutputStream("signedPurchaseOrder.xml");
              TransformerFactory tf = TransformerFactory.newInstance();
              Transformer trans = tf.newTransformer();
              trans.transform(new DOMSource(doc), new StreamResult(os));
            }catch(Exception e){
                 e.printStackTrace();
            try{
            Validator.main(null);
            }catch(Exception e){
                 System.out.println("Validator exception");
                 e.printStackTrace();
         public static Element createElement(Document doc, String tag,String prefix, String nsURI) {
              String qName = prefix == null ? tag : prefix + ":" + tag;
             return doc.createElementNS(nsURI, qName);
    }Validator class:
    import javax.xml.crypto.*;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dom.*;
    import javax.xml.crypto.dsig.dom.DOMValidateContext;
    import javax.xml.crypto.dsig.keyinfo.*;
    import java.io.FileInputStream;
    import java.security.*;
    import java.util.Collections;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilderFactory;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    * This is a simple example of validating an XML
    * Signature using the JSR 105 API. It assumes the key needed to
    * validate the signature is contained in a KeyValue KeyInfo.
    public class Validator {
        // Synopsis: java Validate [document]
        //       where "document" is the name of a file containing the XML document
        //       to be validated.
        public static void main(String[] args) throws Exception {
         // Instantiate the document to be validated
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         Document doc =
                dbf.newDocumentBuilder().parse(new FileInputStream("signedPurchaseOrder.xml"));
         // Find Signature element
         NodeList nl =
             doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
         if (nl.getLength() == 0) {
             throw new Exception("Cannot find Signature element");
         // Create a DOM XMLSignatureFactory that will be used to unmarshal the
         // document containing the XMLSignature
         XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
         // Create a DOMValidateContext and specify a KeyValue KeySelector
            // and document context
         DOMValidateContext valContext = new DOMValidateContext
             (new KeyValueKeySelector(), nl.item(0));
         // unmarshal the XMLSignature
         XMLSignature signature = fac.unmarshalXMLSignature(valContext);
         // Validate the XMLSignature (generated above)
         boolean coreValidity = signature.validate(valContext);
         // 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);
             // 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("Signature passed core validation");
         * KeySelector which retrieves the public key out of the
         * KeyValue element and returns it.
         * NOTE: If the key algorithm doesn't match signature algorithm,
         * then the public key will be ignored.
        private static class KeyValueKeySelector extends KeySelector {
         public KeySelectorResult select(KeyInfo keyInfo,
                                            KeySelector.Purpose purpose,
                                            AlgorithmMethod method,
                                            XMLCryptoContext context)
                throws KeySelectorException {
                if (keyInfo == null) {
              throw new KeySelectorException("Null KeyInfo object!");
                SignatureMethod sm = (SignatureMethod) method;
                List list = keyInfo.getContent();
                for (int i = 0; i < list.size(); i++) {
              XMLStructure xmlStructure = (XMLStructure) list.get(i);
                     if (xmlStructure instanceof KeyValue) {
                        PublicKey pk = null;
                        try {
                            pk = ((KeyValue)xmlStructure).getPublicKey();
                        } catch (KeyException ke) {
                            throw new KeySelectorException(ke);
                        // make sure algorithm is compatible with method
                        if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
                            return new SimpleKeySelectorResult(pk);
                throw new KeySelectorException("No KeyValue element found!");
            //@@@FIXME: this should also work for key types other than DSA/RSA
         static boolean algEquals(String algURI, String algName) {
                if (algName.equalsIgnoreCase("DSA") &&
              algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
              return true;
                } else if (algName.equalsIgnoreCase("RSA") &&
                           algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
              return true;
                } else {
              return false;
        private static class SimpleKeySelectorResult implements KeySelectorResult {
         private PublicKey pk;
         SimpleKeySelectorResult(PublicKey pk) {
             this.pk = pk;
         public Key getKey() { return pk; }
    }PurchaseOrder.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <PurchaseOrder>
    <Item number="130046593231">
      <Description>Video Game</Description>
      <Price>10.29</Price>
    </Item>
    <Buyer id="8492340">
      <Name>My Name</Name>
      <Address>
       <Street>One Network Drive</Street>
       <Town>Burlington</Town>
       <State>MA</State>
       <Country>United States</Country>
       <PostalCode>01803</PostalCode>
      </Address>
    </Buyer>
    </PurchaseOrder>signedPurchaseOrder.xml with XAdES namespace:
    <?xml version="1.0" encoding="UTF-8" standalone="no"?><PurchaseOrder>
    <Item number="130046593231">
      <Description>Video Game</Description>
      <Price>10.29</Price>
    </Item>
    <Buyer id="8492340">
      <Name>My Name</Name>
      <Address>
       <Street>One Network Drive</Street>
       <Town>Burlington</Town>
       <State>MA</State>
       <Country>United States</Country>
       <PostalCode>01803</PostalCode>
      </Address>
    </Buyer>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#" Id="Sig1"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#dsa-sha1"/><ds:Reference URI=""><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>tVicGh6V+8cHbVYFIU91o5+L3OQ=</ds:DigestValue></ds:Reference><ds:Reference Type="http://uri.etsi.org/01903/v1.3.2#SignedProperties" URI="#SignP"><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>MAQ/vctdkyVHVzoQWnOnQdeBw8g=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>lSgzfZCRIlgrgr6YpNOdB3XWdF9P9TEiXfkNoqUpAru/I7IiyiFWJg==</ds:SignatureValue><ds:KeyInfo><ds:KeyValue><ds:DSAKeyValue><ds:P>/KaCzo4Syrom78z3EQ5SbbB4sF7ey80etKII864WF64B81uRpH5t9jQTxeEu0ImbzRMqzVDZkVG9
    xD7nN1kuFw==</ds:P><ds:Q>li7dzDacuo67Jg7mtqEm2TRuOMU=</ds:Q><ds:G>Z4Rxsnqc9E7pGknFFH2xqaryRPBaQ01khpMdLRQnG541Awtx/XPaF5Bpsy4pNWMOHCBiNU0Nogps
    QW5QvnlMpA==</ds:G><ds:Y>p48gU203NGPcs9UxEQQQzQ19KBtDRGfEs3BDt0cbCRJHMh3EoySpeqOnuTeKLXuFr96nzAPq4BEU
    dNAc7XpDvQ==</ds:Y></ds:DSAKeyValue></ds:KeyValue></ds:KeyInfo><ds:Object Id="QualifyingInfos"><QualifyingProperties Target="Sig1" xmlns="http://uri.etsi.org/01903/v1.3.2#"><SignedProperties Id="SignP"/><UnsignedProperties/></QualifyingProperties></ds:Object></ds:Signature></PurchaseOrder>

    I believe the problem is that you are not explicitly adding the xades namespace
    attribute to the SignedProperties element before generating the signature. Thus,
    the namespace attribute is not visible when canonicalizing, but when you serialize the
    DOM tree to an output stream, (for reasons I'm not entirely sure why), the namespace
    attribute is visible and is added to the SignedProperties element, which breaks the
    signature.
    You must always explicitly add namespace attributes using the Element.setAttributeNS
    method. Try changing the following code from:
    Element SPElement = createElement(doc, "SignedProperties", null,xadesNS);
    to:
    Element SPElement = createElement(doc, "SignedProperties", null,xadesNS);
    SPElement.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", xadesNS);

  • Xml digital signature api

    hello
    Has anyone tried to use the xml digital signature api on an application deployed on appserver 8.2 bundled with stucio?
    I am trying to,,but it seems i cannot work it out,.Here is what i do,,i ve built a sample application where when i clik a button the following code runs.I have imported the xmldsig.jar file i found on jwsdp-1.5 that includes the needed classes and i am using jdk 1.4.2.07.
    I should mention that when i deploy the application on tomcat 4.1.31 everything works fine and the xml file is properly signed.But it never works on when i run it on appserver.for ANY help i would be grateful!!!!!!!!
    the following code is on the click button action
    ypografi ob2 =new ypografi();
    boolean ok ;
    ok = ob2.ypegrapse("C:/attach.xml");
    the following code is the ypografi.java file
    package dokimi;
    import javax.xml.crypto.*;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dom.*;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.keyinfo.*;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.security.*;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    public class ypografi {
    /** Creates a new instance of ypografi */
    public ypografi() {
    public boolean ypegrapse(String nameoffile){
    // Create a DOM XMLSignatureFactory that will be used to generate the
              // enveloped signature
         try {     
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
              XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",(Provider) Class.forName(providerName).newInstance());
    // Create a Reference to the enveloped document (in this case we are
              // signing the whole document, so a URI of "" signifies that) and
              // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
              Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null),Collections.singletonList(fac.newTransform(Transform.ENVELOPED, null)),null, null);
              // Create the SignedInfo
              SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, null),fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),Collections.singletonList(ref));
    // Create a DSA KeyPair
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
              kpg.initialize(512);
    KeyPair kp = kpg.generateKeyPair();
    // Create a KeyValue containing the DSA PublicKey that was generated
              KeyInfoFactory kif = fac.getKeyInfoFactory();
    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(nameoffile));
    // 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);
              // output the resulting document
              OutputStream os;
         os = new FileOutputStream(nameoffile);
              TransformerFactory tf = TransformerFactory.newInstance();
              Transformer trans = tf.newTransformer();
              trans.transform(new DOMSource(doc), new StreamResult(os));
    }catch(Exception e){
    System.out.println(e);
    return false;
    return true;
    }

    Something like this should work:
            Text text = doc.createTextNode("testContent");
            SignatureProperty sp = fac.newSignatureProperty
                (Collections.singletonList(new DOMStructure(text)),
                "#testTarget", "testID");
            SignatureProperties sps = fac.newSignatureProperties
                (Collections.singletonList(sp), null);
            objs.add(fac.newXMLObject(Collections.singletonList(sps), null,
                null, null));

  • XML Digital Signature API: creation of SignatureProperties

    Hallo!
    I'm having problems using the XMLDigitalSignature API to create signature properties.
    I want my signature to contain the following
    <SignatureProperties>
                <SignatureProperty Id="testID" Target="testTarget">
                    testContent
                </SignatureProperty>
    </SignatureProperties>I already create a signature using the following code:
              List<XMLObject> objs = new ArrayList<XMLObject>();
              objs.add(fac.newXMLObject(Collections.singletonList(manifest), null, null, null));
              XMLSignature signature = fac.newXMLSignature(si, ki, objs, signatureID, null);I've already been messing around with the method newSignatureProperties of the XMLSignatureFactory but I haven't managed to get it working. Can somebody help, please.
    Thanks in advance
    alex

    Something like this should work:
            Text text = doc.createTextNode("testContent");
            SignatureProperty sp = fac.newSignatureProperty
                (Collections.singletonList(new DOMStructure(text)),
                "#testTarget", "testID");
            SignatureProperties sps = fac.newSignatureProperties
                (Collections.singletonList(sp), null);
            objs.add(fac.newXMLObject(Collections.singletonList(sps), null,
                null, null));

  • How to validate XML Digital Signature with XML DB (o PL/SQL) in Oracle 11g

    Hi,
    Do you know if there is possibility to validate XML Digital Signature using XML DB (or PL/SQL) in Oracle 11g?
    Let say I have CLOB/XMLType containing Digitally Signed XML, and I want to validate, that thsi is proper signature. I also have public key of signer (I could store it in CLOB or file or Oracle wallet).
    Is it possible to do?
    If there is need to install additional component - then which one?
    Regards,
    Paweł

    Hi,
    this is what i got from someone...
    but the links he gave are not opening up...
    u have to place a picture there and have to load the digital signatures as Jpegs on to the server to OA top
    and have to refer them in the XML for dynamically get the signature on the reports
    when u select the properties of the picture placed in the XML template,
    there will be one tab with "URL"... in that u have to give the path for that jpegs
    Pls refer the following documents for enabling digital signature on pdf documents.
    http://iasdocs.us.oracle.com/iasdl/bi_ee/doc/bi.1013/e12187/T421739T481159.htm#5013638    (refer section 'Adding or Designating a Field for Digital Signature'
    http://iasdocs.us.oracle.com/iasdl/bi_ee/doc/bi.1013/e12188/T421739T475591.htm#5013688
    (Implementing a Digital Signature
    Is the BI Publisher installed on your instance of version 10.1.3.4 or higher?
    Pls procure a digital signature as soon as possible. The process can take time. OR we could use any certificate that you already might have OR generate a certificate using Oracle Certificate Authority for demo.

  • XML Digital Signature Canonicalisation Error.

    Hi,
    I am writing JAVA code to perform XML Digital Signature and Verification. I am using jwsdp-2.0 jar files xmldsig.jar and xmlsec.jar.
    I am successfully able to sing the xml but still have few issues.
    1. Canoniclisation on SignedInfo is not happening. API is signing the SignedInfo Element without performing Canonicalisation. I turned on debugging and it shows FINE: Canonicalized SignedInfo:error. Because its not able to perform Canonicalisation verification fails on other end.
    fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,(C14NMethodParameterSpec)null) is the canonicalisation param I am passing to SI.
    2. Not able to specify XPointer in URI string when creating Reference object. It works fine with, just id of element as reference, but not with xpointer.
    Any help on these issue is greatly appreciated.
    Thanks for your help.
    Ajit Rathod
    CODE :
    ============================================================
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.xml.crypto.dsig.*;
    import javax.xml.crypto.dsig.dom.DOMSignContext;
    import javax.xml.crypto.dsig.spec.*;
    import java.io.ByteArrayOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.OutputStream;
    import java.net.URLEncoder;
    import java.security.*;
    import java.util.Collections;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.DOMSource;
    import javax.xml.transform.stream.StreamResult;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    public class GenEnveloped {
         public static void main(String[] args) throws Exception {
    String providerName = System.getProperty
    ("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");
         XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",(Provider) Class.forName(providerName).newInstance());
         String strRefURI = "";
         strRefURI = "#testID";     
         Transform trf = fac.newTransform(CanonicalizationMethod.EXCLUSIVE,(TransformParameterSpec)null);
    Reference ref = fac.newReference (strRefURI, fac.newDigestMethod(DigestMethod.SHA1,null), Collections.singletonList(trf),null,null);
         SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,(C14NMethodParameterSpec)null),fac.newSignatureMethod(SignatureMethod.HMAC_SHA1, null),Collections.singletonList(ref));     
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
         dbf.setNamespaceAware(true);
         Document doc = dbf.newDocumentBuilder().parse(new FileInputStream("testSamlData.xml"));     
         NodeList nlWSSESecurity = doc.getElementsByTagName("wsse:Security");
         String strKey = "asefasfsadfasdfsfasfdfsdasdfasdf";
         ByteArrayOutputStream baos = new ByteArrayOutputStream();     
         byte keyBytes[] = strKey.getBytes();     
         SecretKey sk = new SecretKeySpec(keyBytes,SignatureMethod.HMAC_SHA1);
         XMLSignature signature = fac.newXMLSignature(si,null);
         DOMSignContext dsc = new DOMSignContext     (sk,nlWSSESecurity.item(0));     
         //DOMSignContext dsc = new DOMSignContext     (sk,doc.getDocumentElement());
         dsc.setDefaultNamespacePrefix("ds");          
    signature.sign(dsc);
         OutputStream os;
         boolean blFile = true;
         if (blFile)
              os = new FileOutputStream("testSamlDataSigned.xml");
              System.out.println("Result is written out to File system");
         else
         os = System.out;
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer trans = tf.newTransformer();
         trans.transform(new DOMSource(doc), new StreamResult(os));
    }

    Charles_F wrote:
    Hi.
    I would appreciate any help regarding the topic.
    I need to create xml digital signature of files that are located in the same directory,
    let's say working directory (current directory) of application.
    I only get in the Reference tag with URI
    <Reference URI="file:/D:/projects/netbeans/CryptoHelpers/form.xml>
    althought I'd like to achieve
    <Reference URI="form.xml">To do that, just specify "form.xml" when creating the Reference and not the complete path. Change:
    Reference refList = xmlSignatureFactory.newReference(
    srcFile.toURI().toString(),
    digestMethod);
    referenceList.add(refList);to:
    Reference refList = xmlSignatureFactory.newReference(
    filePath, digestMethod);
    referenceList.add(refList);Also, make sure your baseURI is set to the directory that the file is located in and ends with a trailing slash. Change:
    signContext.setBaseURI("file:/");to
    signContext.setBaseURI("file:/D:/projects/netbeans/CryptoHelpers/");

  • XML Digital Signature and sun PKCS#11

    Hi,
    I am trying to use xmldsig/xmlsec from Java Web Services Developer's Pack to do signing of XML documents. My goal is to use the keys from the card via sunpkcs11 to perform this signature.
    At this stage, i'm able to get the correct key from the card via sun pkcs 11 (J2SE 5) and able to sign some data with it.
    However, when i try to sign a xml document via xmldsig, i get the error which i believe to occur while trying to read the private key from the card as a string, which results in a "not a byte[]" exception.
    At this stage, are there any ways to configure the xmldsig/xmlsec to use the pkcs11 provider?
    I understand that the current implementation of XML Digital signature is using apache XML libraries. Is the source code for the wsdp downloadable from SUN?
    If not, will it be possible to make use of the open-source apache XML jars, set it up for pkcs11 and use it instead?
    Finally, has anyone done what I'm trying to do? Will be glad to know
    Thank u in advance,
    Louis

    Hello
    Did you resolve yout problem, because i have the same when i try to sign message
    String testData = "Hello World";
    p11KeyStore = KeyStore.getInstance("PKCS11");
    p11KeyStore.load(null, new char[] {'1', '2', '3', '4'});
    sig = Signature.getInstance("SHA1withRSA");
    sig.initSign( (PrivateKey) p11KeyStore.getKey(myAlias, null));
    sig.update(testData.getBytes());
    signatureBytes = sig.sign()
    This code fails and i get java.lang.RuntimeException: Not a byte[]
         at sun.security.pkcs11.wrapper.CK_ATTRIBUTE.getBigInteger(CK_ATTRIBUTE.java:168)
         at sun.security.pkcs11.P11Key$P11RSAPrivateKey.fetchValues(P11Key.java:419)

  • XML digital signature universal validator

    Hello,
    I am looking into the xml digital signaturing and i have a few questions about this:
    1.I wondered if anybody had any idea's for making a universal validator.
    I made this validator that validates an example xml file. But i would like to hava a validator that works on all signed xml files.
    2.Also in the jwsdp examples they create an enveloping signed file from scratch with a sample program. I think with some modifications it should be possible to have a program that does this for random xml files.
    Just use an xml file as input, en get a signed xml file as output file.
    I am looking for ppl with the same problems or solutions.
    Idea's are welcome.

    Nevermind, the xml security suite of IBM takes care of that problem already :)

  • Acrobat Address Book methods in Digital Signature API

    Can anyone point me to code samples using the Acrobat Address Book methods in the Digital Signature API (AABFindCertsByName, AABGetCertTrust for example)?

    I don't remember seeing any, sorry.
    From: Adobe Forums <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Thu, 8 Dec 2011 16:32:46 -0800
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: Acrobat Address Book methods in Digital Signature API
    Acrobat Address Book methods in Digital Signature API
    created by jmmorgan11<http://forums.adobe.com/people/jmmorgan11> in Acrobat SDK - View the full discussion<http://forums.adobe.com/message/4072845#4072845

  • XML digital signature XAdES support

    Are there any plans for supporting XaDES Advanced electronic signature as specified by ETSI TS 101-93?
    It's a quite common format, and well acknowledged (for instance by italian and other EU countries regulations).
    Should i file or vote an RFE?

    Charles_F wrote:
    Hi.
    I would appreciate any help regarding the topic.
    I need to create xml digital signature of files that are located in the same directory,
    let's say working directory (current directory) of application.
    I only get in the Reference tag with URI
    <Reference URI="file:/D:/projects/netbeans/CryptoHelpers/form.xml>
    althought I'd like to achieve
    <Reference URI="form.xml">To do that, just specify "form.xml" when creating the Reference and not the complete path. Change:
    Reference refList = xmlSignatureFactory.newReference(
    srcFile.toURI().toString(),
    digestMethod);
    referenceList.add(refList);to:
    Reference refList = xmlSignatureFactory.newReference(
    filePath, digestMethod);
    referenceList.add(refList);Also, make sure your baseURI is set to the directory that the file is located in and ends with a trailing slash. Change:
    signContext.setBaseURI("file:/");to
    signContext.setBaseURI("file:/D:/projects/netbeans/CryptoHelpers/");

  • Digital signature: How to sign a file ( algorithm SHA1withRSA )

    Hi
    I need create and sign a File. I need some example how to do that.
    I Found this functions:
    ssfSign ( to sign )
    ssfEnvelop ( to encrypt )
    Thanks a lot!
    Mariano

    check program SSF01
    regards
    Prabhu

  • How to send digital signature from pdf form to fdf file?

    Hi...
    I already create the pdf form that contain digital signature field using ACROBAT XPRO...and now i would like to send data from pdf form to fdf file.I already manage to send data from other field except the digital signature.How to send the signature digital value to FDF file so that i can display it back to PDF file next time?Can anyone help me...i really need help right now...
    tq..

    hi....
    thanks for replying..
    George Johnson wrote:
    It did work with earlier versions that did not perform a full save when a signature was applied. Since Acrobat/Reader now do a Save As when a signature is applied, there are no incremental saves to include in the FDF. This can still be useful for forms that haven't been signed, oddly enough, but since you cannot control whether the user performs a full save, it shouldn't be relied on for general use. The big problem is extracting the appended saves from the FDF so you can concatenate it to original document. The FDF Toolkit is the only thing I'm aware of that helps with this.
    as u said that,Fdf tool kits can help to solve my problem.Can u send me the sample of code using java so that i can get the value using Fdf Tool kits?
    Thanks..

  • Using iText to generate a digital signature that can be signed in Adobe Reader

    I am able to create a digital signature in a pdf using iText.  Adobe Reader does not allow that digital signature to be signed.  Everything I have been reading suggests that I need to enabe Reader Usage Rights, but that requires using Adobe Pro.  I was hoping that I would only need Adobe Reader inorder to digitally sign the pdf, is that possible?

    Not without the required rights...

  • Is there a script for making a digital signature read-only after signing?

    When the user signs a PDF Form, the user can clear his own signature. I want to disable the "Clear Signature" feature. I noticed I can run a Javascript in the digital signature's property. Is it possible to execute a Javascript to make just that signature Read-only?
    Thanks.

    If the person who signed the document has Acrobat Pro, you could use the flattenPages() method, which lets you specify the page(s) to be flattened.
    For example:
    this.flattenPages(0)         //flattens page 1
    this.flattenPages(0, 2)     //flattens pages 1 - 3
    But if they have only Reader, they can't use flattenPages().

  • Digital signature field will not sign

    digital signature will not sign

    And that is why many responders use only the custom JavaScript calculation option.
    The UI for the select fields and simplified field nations are only a way to pass field names to a JavaScript function that performs the actual calculation. Sometimes these functions call other functions and pass the parameters can lead to errors in the attempted code.
    I would start to learn code JavaScript for Acrobat.
    The pick field dialog is for performing calculations involving sums, products, averages, minimum, and maximum. I am not sure how that would work with a digital signature. Once a signature is applied the form fields could be locked.

Maybe you are looking for