List of usage examples for javax.xml.crypto.dsig XMLSignature sign
void sign(XMLSignContext signContext) throws MarshalException, XMLSignatureException;
XMLSignature
. From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java
/** * This will sign a SAMLR2 Identity artifact (assertion, request or response) represeted as a DOM tree * The signature will be inserted as the first child of the root element. * * @param doc/* w w w . j a v a 2 s . co m*/ * @param id * @return */ protected Document sign(Document doc, String id) throws SamlR2SignatureException { try { Certificate cert = keyResolver.getCertificate(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider); if (logger.isDebugEnabled()) logger.debug("Creating XML DOM Digital Siganture (not signing yet!)"); // Create a Reference to the enveloped document and // also specify the SHA1 digest algorithm and the ENVELOPED Transform. // The URI must be the assertion ID List<Transform> transforms = new ArrayList<Transform>(); transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); // Magically, this solves assertion DS validation when embedded in a signed response :) transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)); Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); // Use signature method based on key algorithm. String signatureMethod = SignatureMethod.DSA_SHA1; if (keyResolver.getPrivateKey().getAlgorithm().equals("RSA")) signatureMethod = SignatureMethod.RSA_SHA1; logger.debug("Using signature method " + signatureMethod); // Create the SignedInfo, with the X509 Certificate /* SignedInfo si = fac.newSignedInfo (fac.newCanonicalizationMethod (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); */ SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref)); // Create a KeyInfo and add the Certificate to it KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); //KeyValue kv = kif.newKeyValue(keyResolver.getCertificate().getPublicKey()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); if (logger.isDebugEnabled()) logger.debug("Signing SAMLR2 Identity Artifact ..."); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(keyResolver.getPrivateKey(), doc.getDocumentElement(), doc.getDocumentElement().getFirstChild()); // Sign the assertion signature.sign(dsc); if (logger.isDebugEnabled()) logger.debug("Signing SAMLR2 Identity Artifact ... DONE!"); return doc; } catch (NoSuchAlgorithmException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (XMLSignatureException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (MarshalException e) { throw new SamlR2SignatureException(e.getMessage(), e); } catch (SSOKeyResolverException e) { throw new SamlR2SignatureException(e.getMessage(), e); } }
From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java
/** * Sign a simple DOM document using the configured JSR 105 Provider *///from w w w . j a va2 s .co m @Test public void simpleDocumentSign() throws Exception { //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "src/test/resources/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("target/signature.xml"); KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); //load the keystore ks.load(fis, keystorePass.toCharArray()); //get the private key for signing. PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); PublicKey publicKey = cert.getPublicKey(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature 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("#12345", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Instantiate the document to be signed javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); //Build a sample document. It will look something like: //<!-- Comment before --> //<apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1" ID="12345">Some simple text //</apache:RootElement> //<!-- Comment after --> doc.appendChild(doc.createComment(" Comment before ")); Element root = doc.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement"); root.setAttributeNS(null, "ID", "12345"); root.setAttributeNS(null, "attr1", "test1"); root.setAttributeNS(null, "attr2", "test2"); root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:foo", "http://example.org/#foo"); root.setAttributeNS("http://example.org/#foo", "foo:attr1", "foo's test"); root.setAttributeNS(org.apache.xml.security.utils.Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1"); doc.appendChild(root); root.appendChild(doc.createTextNode("Some simple text\n")); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement()); // Create the XMLSignature (but don't sign it yet) KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); // TODO : Verify signature ? // output the resulting document FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); }
From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java
/** * Sign a SAMLR2 Assertion using the configured JSR 105 Provider */// ww w.jav a 2 s.c om @Test public void assertionSign() throws Exception { //All the parameters for the keystore String keystoreType = "JKS"; String keystoreFile = "src/test/resources/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File assertionFile = new File("src/test/resources/assertion-001.xml"); File signatureFile = new File("target/assertion-signed-001.xml"); JAXBContext context = JAXBContext.newInstance("oasis.names.tc.saml._2_0.assertion"); Unmarshaller um = context.createUnmarshaller(); JAXBElement jaxbElement = (JAXBElement) um.unmarshal(assertionFile); AssertionType assertion = (AssertionType) jaxbElement.getValue(); // Unmarshall the assertion KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); //load the keystore ks.load(fis, keystorePass.toCharArray()); //get the private key for signing. PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); PublicKey publicKey = cert.getPublicKey(); // Create a DOM XMLSignatureFactory that will be used to generate the // enveloped signature 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("#" + assertion.getID(), fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); // Create the SignedInfo SignedInfo si = fac.newSignedInfo( fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); // Instantiate the document to be signed javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); //XML Signature needs to be namespace aware dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); Marshaller m = context.createMarshaller(); m.marshal(jaxbElement, doc); // Create a DOMSignContext and specify the DSA PrivateKey and // location of the resulting XMLSignature's parent element DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement(), doc.getDocumentElement().getFirstChild()); // Create the XMLSignature (but don't sign it yet) KeyInfoFactory kif = fac.getKeyInfoFactory(); X509Data kv = kif.newX509Data(Collections.singletonList(cert)); // Create a KeyInfo and add the KeyValue to it KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki); signature.sign(dsc); // output the resulting document FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static void digitalSign(XMLSignatureFactory factory, List<Reference> referenceList, DigestMethod digestMethod, X509Certificate certificate, Document docSignatures, Element rootSignatures, Key key) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { String signatureId = UUID.randomUUID().toString(); String signaturePropertyId = UUID.randomUUID().toString(); CanonicalizationMethod canMethod = factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signMethod = factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); Reference signaturePropertyReference = factory.newReference("#" + signaturePropertyId, digestMethod); referenceList.add(signaturePropertyReference); SignedInfo si = factory.newSignedInfo(canMethod, signMethod, referenceList); KeyInfo ki = getKeyInfo(factory, certificate); List<XMLObject> objectList = getXMLObjectList(factory, docSignatures, signatureId, signaturePropertyId); XMLSignature signature = factory.newXMLSignature(si, ki, objectList, signatureId, null); DOMSignContext signContext = new DOMSignContext(key, rootSignatures); signature.sign(signContext); }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static void digitalSign(XMLSignatureFactory factory, List<Reference> referenceList, DigestMethod digestMethod, X509Certificate certificate, Document docSignatures, Element rootSignatures, Key key) throws MarshalException, XMLSignatureException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { String signatureId = IdUtils.createUUID(); String signaturePropertyId = IdUtils.createUUID(); CanonicalizationMethod canMethod = factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signMethod = factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); Reference signaturePropertyReference = factory.newReference("#" + signaturePropertyId, digestMethod); referenceList.add(signaturePropertyReference); SignedInfo si = factory.newSignedInfo(canMethod, signMethod, referenceList); KeyInfo ki = getKeyInfo(factory, certificate); List<XMLObject> objectList = getXMLObjectList(factory, docSignatures, signatureId, signaturePropertyId); XMLSignature signature = factory.newXMLSignature(si, ki, objectList, signatureId, null); DOMSignContext signContext = new DOMSignContext(key, rootSignatures); signature.sign(signContext); }
From source file:org.warlock.itk.distributionenvelope.Payload.java
/** * Sign the payloadBody as-is. Note that this is going to be encrypted anyway * so we avoid any incompatibilities due to canonicalisation, and we don't * care if the payloadBody is text, compressed and so on. Re-writes payloadBody * with a serialised XML Digital Signature "Signature" element containing an * enveloping signature, or throws an exception to signal failure. * /*from www. j ava 2 s . c o m*/ * @param pk * @param cert * @throws Exception */ private void signPayload(PrivateKey pk, X509Certificate cert) throws Exception { if ((pk == null) || (cert == null)) { throw new Exception("Null signing material"); } cert.checkValidity(); XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM"); Reference ref = null; String objectRef = "uuid" + UUID.randomUUID().toString(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = null; DOMStructure payloadContent = null; if (compressed || base64 || !mimeType.contains("xml")) { ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null)); doc = dbf.newDocumentBuilder().newDocument(); payloadContent = new DOMStructure(doc.createTextNode(payloadBody)); } else { Transform t = xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#", (TransformParameterSpec) null); ref = xsf.newReference("#" + objectRef, xsf.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(t), null, null); doc = dbf.newDocumentBuilder().parse(new InputSource(new StringReader(payloadBody))); payloadContent = new DOMStructure(doc.getDocumentElement()); } XMLObject payloadObject = xsf.newXMLObject(Collections.singletonList(payloadContent), objectRef, null, null); SignedInfo si = xsf.newSignedInfo( xsf.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref)); KeyInfoFactory kif = xsf.getKeyInfoFactory(); ArrayList<Object> x509content = new ArrayList<Object>(); x509content.add(cert); X509Data xd = kif.newX509Data(x509content); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = xsf.newXMLSignature(si, ki, Collections.singletonList(payloadObject), null, null); DOMSignContext dsc = new DOMSignContext(pk, doc); signature.sign(dsc); StringWriter sw = new StringWriter(); StreamResult sr = new StreamResult(sw); Transformer tx = TransformerFactory.newInstance().newTransformer(); tx.transform(new DOMSource(doc), sr); if (sw.toString().indexOf("<?xml ") == 0) { payloadBody = sw.toString().substring(sw.toString().indexOf("?>") + "?>".length()); } else { payloadBody = sw.toString(); } }
From source file:test.be.fedict.eid.dss.DigitalSignatureServiceTest.java
private void signDocument(Document document) throws IOException, PKCS11Exception, InterruptedException, NoSuchFieldException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, CardException { Messages messages = new Messages(Locale.getDefault()); PcscEid pcscEid = new PcscEid(new TestView(), messages); if (false == pcscEid.isEidPresent()) { LOG.debug("insert eID..."); pcscEid.waitForEidPresent();//from w w w.ja va 2 s.com } // PrivateKeyEntry privateKeyEntry = pcscEid.getPrivateKeyEntry(); PrivateKeyEntry privateKeyEntry = null; // TODO: refactor once Commons eID has been released. XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignContext signContext = new DOMSignContext(privateKeyEntry.getPrivateKey(), document.getDocumentElement()); signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds"); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference("#id", digestMethod); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance(); List<Object> x509DataObjects = new LinkedList<Object>(); X509Certificate signingCertificate = (X509Certificate) privateKeyEntry.getCertificate(); x509DataObjects.add(signingCertificate); X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects); List<Object> keyInfoContent = new LinkedList<Object>(); keyInfoContent.add(x509Data); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(signContext); pcscEid.close(); }
From source file:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java
private void addSignature(Element wsSecurityHeaderElement, Element tsElement, Element bodyElement) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException, NoSuchProviderException, SOAPException { if (null == this.privateKey) { return;//from w w w .j av a 2 s.co m } DOMSignContext domSignContext = new DOMSignContext(this.privateKey, wsSecurityHeaderElement); domSignContext.setDefaultNamespacePrefix("ds"); domSignContext.setIdAttributeNS(tsElement, WSU_NAMESPACE, "Id"); domSignContext.setIdAttributeNS(bodyElement, WSU_NAMESPACE, "Id"); LOG.debug("Timestamp element found: " + (null != domSignContext.getElementById("TS"))); XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM"); List<Reference> references = new LinkedList<Reference>(); List<String> tsPrefixes = new LinkedList<String>(); tsPrefixes.add("wsse"); tsPrefixes.add("S"); ExcC14NParameterSpec tsTransformSpec = new ExcC14NParameterSpec(tsPrefixes); Reference tsReference = xmlSignatureFactory.newReference("#TS", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null), Collections.singletonList( xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, tsTransformSpec)), null, null); references.add(tsReference); if (this.signBody) { List<String> bodyPrefixes = new LinkedList<String>(); ExcC14NParameterSpec bodyTransformSpec = new ExcC14NParameterSpec(bodyPrefixes); Reference bodyReference = xmlSignatureFactory.newReference("#Body", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null), Collections.singletonList( xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, bodyTransformSpec)), null, null); references.add(bodyReference); } if (this.signBinarySecurityToken) { Reference bstReference = xmlSignatureFactory .newReference("#X509", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null), Collections.singletonList(xmlSignatureFactory .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null); references.add(bstReference); } SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo( xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xmlSignatureFactory.newSignatureMethod(this.signatureAlgorithm, null), references); KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory(); Document document = wsSecurityHeaderElement.getOwnerDocument(); Element securityTokenReferenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:SecurityTokenReference"); Element referenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:Reference"); referenceElement.setAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"); referenceElement.setAttribute("URI", "#X509"); securityTokenReferenceElement.appendChild(referenceElement); KeyInfo keyInfo = keyInfoFactory .newKeyInfo(Collections.singletonList(new DOMStructure(securityTokenReferenceElement))); XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, null, "SIG", null); xmlSignature.sign(domSignContext); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testCheckDigestedNode() throws Exception { // setup//w w w . ja va 2 s . co m Init.init(); KeyPair keyPair = PkiTestUtils.generateKeyPair(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElementNS("urn:test", "tns:root"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test"); document.appendChild(rootElement); Element dataElement = document.createElementNS("urn:test", "tns:data"); dataElement.setAttributeNS(null, "Id", "id-1234"); dataElement.setTextContent("data to be signed"); rootElement.appendChild(dataElement); Element data2Element = document.createElementNS("urn:test", "tns:data2"); rootElement.appendChild(data2Element); data2Element.setTextContent("hello world"); data2Element.setAttribute("name", "value"); Element data3Element = document.createElementNS("urn:test", "tns:data3"); data2Element.appendChild(data3Element); data3Element.setTextContent("data 3"); data3Element.appendChild(document.createComment("some comments")); Element emptyElement = document.createElementNS("urn:test", "tns:empty"); rootElement.appendChild(emptyElement); org.apache.xml.security.signature.XMLSignature xmlSignature = new org.apache.xml.security.signature.XMLSignature( document, "", org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1); rootElement.appendChild(xmlSignature.getElement()); Transforms transforms = new Transforms(document); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); xmlSignature.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); xmlSignature.addKeyInfo(keyPair.getPublic()); xmlSignature.sign(keyPair.getPrivate()); NodeList signatureNodeList = document.getDocumentElement() .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); Element signatureElement = (Element) signatureNodeList.item(0); // operate & verify assertTrue(isDigested(dataElement, signatureElement)); assertTrue(isDigested(data2Element, signatureElement)); assertTrue(isDigested(emptyElement, signatureElement)); }
From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java
@Test public void testCheckDigestedNode2() throws Exception { // setup/*from w ww .j a v a 2 s . c o m*/ Init.init(); KeyPair keyPair = PkiTestUtils.generateKeyPair(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); Element rootElement = document.createElementNS("urn:test", "tns:root"); rootElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:tns", "urn:test"); document.appendChild(rootElement); Element dataElement = document.createElementNS("urn:test", "tns:data"); dataElement.setAttributeNS(null, "Id", "id-1234"); dataElement.setIdAttributeNS(null, "Id", true); dataElement.setTextContent("data to be signed"); rootElement.appendChild(dataElement); Element data2Element = document.createElementNS("urn:test", "tns:data2"); rootElement.appendChild(data2Element); data2Element.setTextContent("hello world"); data2Element.setAttributeNS(null, "name", "value"); Element data3Element = document.createElementNS("urn:test", "tns:data3"); data2Element.appendChild(data3Element); data3Element.setTextContent("data 3"); data3Element.appendChild(document.createComment("some comments")); Element emptyElement = document.createElementNS("urn:test", "tns:empty"); rootElement.appendChild(emptyElement); org.apache.xml.security.signature.XMLSignature xmlSignature = new org.apache.xml.security.signature.XMLSignature( document, "", org.apache.xml.security.signature.XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1); rootElement.appendChild(xmlSignature.getElement()); Transforms transforms = new Transforms(document); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); xmlSignature.addDocument("#id-1234", transforms, Constants.ALGO_ID_DIGEST_SHA1); xmlSignature.addKeyInfo(keyPair.getPublic()); xmlSignature.sign(keyPair.getPrivate()); NodeList signatureNodeList = document.getDocumentElement() .getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#", "Signature"); Element signatureElement = (Element) signatureNodeList.item(0); // operate & verify assertTrue(isDigested(dataElement, signatureElement)); assertFalse(isDigested(data2Element, signatureElement)); }