List of usage examples for org.w3c.dom Document createElementNS
public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;
From source file:org.apache.ws.security.message.WSSecEncryptedKey.java
/** * Create DOM subtree for <code>xenc:EncryptedKey</code> * /*from w w w .j a va2s. c om*/ * @param doc the SOAP envelope parent document * @param keyTransportAlgo specifies which algorithm to use to encrypt the symmetric key * @return an <code>xenc:EncryptedKey</code> element */ protected Element createEncryptedKey(Document doc, String keyTransportAlgo) { Element encryptedKey = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptedKey"); WSSecurityUtil.setNamespace(encryptedKey, WSConstants.ENC_NS, WSConstants.ENC_PREFIX); Element encryptionMethod = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptionMethod"); encryptionMethod.setAttributeNS(null, "Algorithm", keyTransportAlgo); encryptedKey.appendChild(encryptionMethod); return encryptedKey; }
From source file:org.apache.ws.security.message.WSSecEncryptedKey.java
protected Element createCipherValue(Document doc, Element encryptedKey) { Element cipherData = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherData"); Element cipherValue = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherValue"); cipherData.appendChild(cipherValue); encryptedKey.appendChild(cipherData); return cipherValue; }
From source file:org.apache.ws.security.message.WSSecSignatureBase.java
/** * Create an STRTransformationParameters element *//*from ww w . j a v a 2 s.c om*/ public Element createSTRParameter(Document doc) { Element transformParam = doc.createElementNS(WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX + ":TransformationParameters"); Element canonElem = doc.createElementNS(WSConstants.SIG_NS, WSConstants.SIG_PREFIX + ":CanonicalizationMethod"); canonElem.setAttributeNS(null, "Algorithm", WSConstants.C14N_EXCL_OMIT_COMMENTS); transformParam.appendChild(canonElem); return transformParam; }
From source file:org.apache.ws.security.saml.SAMLUtil.java
/** * Create a TimeStamp object from the SAML assertion. * @param assertion//from www .ja v a 2 s . c o m * @return * @throws WSSecurityException */ public static Timestamp getTimestampForSAMLAssertion(Element assertion) throws WSSecurityException { String[] validityPeriod = getValidityPeriod(assertion); // If either of the timestamps are missing, then return a null if (validityPeriod[0] == null || validityPeriod[1] == null) { return null; } try { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); Document document = dbFactory.newDocumentBuilder().newDocument(); Element element = document.createElement("SAMLTimestamp"); Element createdElement = document.createElementNS(WSConstants.WSU_NS, WSConstants.CREATED_LN); createdElement.setTextContent(validityPeriod[0]); element.appendChild(createdElement); Element expiresElement = document.createElementNS(WSConstants.WSU_NS, WSConstants.EXPIRES_LN); expiresElement.setTextContent(validityPeriod[1]); element.appendChild(expiresElement); return new Timestamp(element); } catch (ParserConfigurationException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "SAMLTimeStampBuildError", null, e); } catch (WSSecurityException e) { throw new WSSecurityException(WSSecurityException.FAILURE, "SAMLTimeStampBuildError", null, e); } }
From source file:org.apache.ws.security.saml.WSSecSignatureSAML.java
/** * Initialize a WSSec SAML Signature./*from w ww . j a v a 2s .co m*/ * * The method sets up and initializes a WSSec SAML Signature structure after * the relevant information was set. After setup of the references to * elements to sign may be added. After all references are added they can be * signed. * * This method does not add the Signature element to the security header. * See <code>prependSignatureElementToHeader()</code> method. * * @param doc * The SOAP envelope as <code>Document</code> * @param uCrypto * The user's Crypto instance * @param assertion * the complete SAML assertion * @param iCrypto * An instance of the Crypto API to handle keystore SAML token * issuer and to generate certificates * @param iKeyName * Private key to use in case of "sender-Vouches" * @param iKeyPW * Password for issuer private key * @param secHeader * The Security header * @throws WSSecurityException */ public void prepare(Document doc, Crypto uCrypto, SAMLAssertion assertion, Crypto iCrypto, String iKeyName, String iKeyPW, WSSecHeader secHeader) throws WSSecurityException { if (doDebug) { log.debug("Beginning ST signing..."); } userCrypto = uCrypto; issuerCrypto = iCrypto; document = doc; issuerKeyName = iKeyName; issuerKeyPW = iKeyPW; // // Get some information about the SAML token content. This controls how // to deal with the whole stuff. First get the Authentication statement // (includes Subject), then get the _first_ confirmation method only // thats if "senderVouches" is true. // SAMLSubjectStatement samlSubjS = null; Iterator it = assertion.getStatements(); while (it.hasNext()) { SAMLObject so = (SAMLObject) it.next(); if (so instanceof SAMLSubjectStatement) { samlSubjS = (SAMLSubjectStatement) so; break; } } SAMLSubject samlSubj = null; if (samlSubjS != null) { samlSubj = samlSubjS.getSubject(); } if (samlSubj == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLToken", new Object[] { "for Signature" }); } String confirmMethod = null; it = samlSubj.getConfirmationMethods(); if (it.hasNext()) { confirmMethod = (String) it.next(); } if (SAMLSubject.CONF_SENDER_VOUCHES.equals(confirmMethod)) { senderVouches = true; } // // Gather some info about the document to process and store it for // retrieval // wsDocInfo = new WSDocInfo(doc); X509Certificate[] certs = null; PublicKey publicKey = null; if (senderVouches) { certs = issuerCrypto.getCertificates(issuerKeyName); wsDocInfo.setCrypto(issuerCrypto); } // // in case of key holder: - get the user's certificate that _must_ be // included in the SAML token. To ensure the cert integrity the SAML // token must be signed (by the issuer). Just check if its signed, but // don't verify this SAML token's signature here (maybe later). // else { if (userCrypto == null || !assertion.isSigned()) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity", new Object[] { "for SAML Signature (Key Holder)" }); } Element e = samlSubj.getKeyInfo(); try { KeyInfo ki = new KeyInfo(e, null); if (ki.containsX509Data()) { X509Data data = ki.itemX509Data(0); if (data != null && data.containsCertificate()) { XMLX509Certificate certElem = data.itemCertificate(0); if (certElem != null) { X509Certificate cert = certElem.getX509Certificate(); certs = new X509Certificate[1]; certs[0] = cert; } } else if (data != null && data.containsIssuerSerial()) { XMLX509IssuerSerial issuerSerial = data.itemIssuerSerial(0); String alias = userCrypto.getAliasForX509Cert(issuerSerial.getIssuerName(), issuerSerial.getSerialNumber()); certs = userCrypto.getCertificates(alias); } } else if (ki.containsKeyValue()) { publicKey = ki.getPublicKey(); } // TODO: get alias name for cert, check against username set by // caller } catch (XMLSecurityException e3) { throw new WSSecurityException(WSSecurityException.FAILURE, "invalidSAMLsecurity", new Object[] { "cannot get certificate (key holder)" }, e3); } wsDocInfo.setCrypto(userCrypto); } if ((certs == null || certs.length == 0 || certs[0] == null) && publicKey == null) { throw new WSSecurityException(WSSecurityException.FAILURE, "noCertsFound", new Object[] { "SAML signature" }); } if (sigAlgo == null) { PublicKey key = null; if (certs != null && certs[0] != null) { key = certs[0].getPublicKey(); } else if (publicKey != null) { key = publicKey; } String pubKeyAlgo = key.getAlgorithm(); log.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_DSA; } else if (pubKeyAlgo.equalsIgnoreCase("RSA")) { sigAlgo = XMLSignature.ALGO_ID_SIGNATURE_RSA; } else { throw new WSSecurityException(WSSecurityException.FAILURE, "unknownSignatureAlgorithm", new Object[] { pubKeyAlgo }); } } sig = null; if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) { Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD); canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo); if (wssConfig.isWsiBSPCompliant()) { Set prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false); InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(doc, prefixes); canonElem.appendChild(inclusiveNamespaces.getElement()); } try { SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo); sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } else { try { sig = new XMLSignature(doc, null, sigAlgo, canonAlgo); } catch (XMLSecurityException e) { log.error("", e); throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e); } } EnvelopeIdResolver resolver = (EnvelopeIdResolver) EnvelopeIdResolver.getInstance(); resolver.setWsDocInfo(wsDocInfo); sig.addResourceResolver(resolver); String sigUri = wssConfig.getIdAllocator().createId("Signature-", sig); sig.setId(sigUri); keyInfo = sig.getKeyInfo(); keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", keyInfo); keyInfo.setId(keyInfoUri); secRef = new SecurityTokenReference(doc); strUri = wssConfig.getIdAllocator().createSecureId("STRId-", secRef); secRef.setID(strUri); if (certs != null && certs.length != 0) { certUri = wssConfig.getIdAllocator().createSecureId("CertId-", certs[0]); } // // If the sender vouches, then we must sign the SAML token _and_ at // least one part of the message (usually the SOAP body). To do so we // need to - put in a reference to the SAML token. Thus we create a STR // and insert it into the wsse:Security header - set a reference of the // created STR to the signature and use STR Transform during the // signature // Transforms transforms = null; try { if (senderVouches) { secRefSaml = new SecurityTokenReference(doc); String strSamlUri = wssConfig.getIdAllocator().createSecureId("STRSAMLId-", secRefSaml); secRefSaml.setID(strSamlUri); if (WSConstants.X509_KEY_IDENTIFIER == keyIdentifierType) { Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); keyId.setAttributeNS(null, "ValueType", WSConstants.WSS_SAML_KI_VALUE_TYPE); keyId.appendChild(doc.createTextNode(assertion.getId())); Element elem = secRefSaml.getElement(); elem.appendChild(keyId); } else { Reference ref = new Reference(doc); ref.setURI("#" + assertion.getId()); ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); secRefSaml.setReference(ref); } Element ctx = createSTRParameter(doc); transforms = new Transforms(doc); transforms.addTransform(STRTransform.implementedTransformURI, ctx); sig.addDocument("#" + strSamlUri, transforms); wsDocInfo.setSecurityTokenReference(secRefSaml.getElement()); } } catch (TransformationException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } catch (XMLSignatureException e1) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1); } if (senderVouches) { switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); ref.setURI("#" + certUri); bstToken = new X509Security(doc); ((X509Security) bstToken).setX509Certificate(certs[0]); bstToken.setID(certUri); wsDocInfo.setBst(bstToken.getElement()); ref.setValueType(bstToken.getValueType()); secRef.setReference(ref); break; case WSConstants.X509_KEY_IDENTIFIER: secRef.setKeyIdentifier(certs[0]); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } } else { switch (keyIdentifierType) { case WSConstants.BST_DIRECT_REFERENCE: Reference ref = new Reference(doc); ref.setURI("#" + assertion.getId()); ref.setValueType(WSConstants.WSS_SAML_KI_VALUE_TYPE); secRef.setReference(ref); break; case WSConstants.X509_KEY_IDENTIFIER: Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier"); keyId.setAttributeNS(null, "ValueType", WSConstants.WSS_SAML_KI_VALUE_TYPE); keyId.appendChild(doc.createTextNode(assertion.getId())); Element elem = secRef.getElement(); elem.appendChild(keyId); break; default: throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId"); } } keyInfo.addUnknownElement(secRef.getElement()); wsDocInfo.setSecurityTokenReference(secRef.getElement()); Element keyInfoElement = keyInfo.getElement(); keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS); try { samlToken = (Element) assertion.toDOM(doc); } catch (SAMLException e2) { throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noSAMLdoc", null, e2); } wsDocInfo.setAssertion(samlToken); }
From source file:org.apache.ws.security.transform.STRTransformUtil.java
protected static Element createBSTX509(Document doc, X509Certificate cert, Element secRefE) throws WSSecurityException { byte data[];/* w w w . j a v a 2s . c o m*/ try { data = cert.getEncoded(); } catch (CertificateEncodingException e) { throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE, "encodeError", null, e); } String prefix = WSSecurityUtil.getPrefixNS(WSConstants.WSSE_NS, secRefE); Element elem = doc.createElementNS(WSConstants.WSSE_NS, prefix + ":BinarySecurityToken"); WSSecurityUtil.setNamespace(elem, WSConstants.WSSE_NS, prefix); // elem.setAttributeNS(WSConstants.XMLNS_NS, "xmlns", ""); elem.setAttributeNS(null, "ValueType", X509Security.X509_V3_TYPE); Text certText = doc.createTextNode(Base64.encode(data)); // no line wrap elem.appendChild(certText); return elem; }
From source file:org.apache.xml.security.samples.encryption.Encrypter.java
private static Document createSampleDocument() throws Exception { javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);/* ww w. ja v a 2s . com*/ javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.newDocument(); /** * Build a sample document. It will look something like: * * <apache:RootElement xmlns:apache="http://www.apache.org/ns/#app1"> * <apache:foo>Some simple text</apache:foo> * </apache:RootElement> */ Element root = document.createElementNS("http://www.apache.org/ns/#app1", "apache:RootElement"); root.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:apache", "http://www.apache.org/ns/#app1"); document.appendChild(root); root.appendChild(document.createTextNode("\n")); Element childElement = document.createElementNS("http://www.apache.org/ns/#app1", "apache:foo"); childElement.appendChild(document.createTextNode("Some simple text")); root.appendChild(childElement); root.appendChild(document.createTextNode("\n")); return document; }
From source file:org.apache.xml.security.samples.signature.CreateCollectableSignature.java
/** * Method main// w ww . j a v a 2s.c o m * * @param unused * @throws Exception */ public static void main(String unused[]) throws Exception { //J- File signatureFile = new File("collectableSignature.xml"); String BaseURI = signatureFile.toURL().toString(); //J+ javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); Element rootElement = doc.createElementNS(null, "root"); doc.appendChild(rootElement); /* Element signedResourceElement = doc.createElementNS("http://custom/", "custom:signedContent"); signedResourceElement.setAttributeNS(Constants.NamespaceNS, "xmlns:custom", "http://custom/"); signedResourceElement.setAttributeNS(null, "Id", "id0"); */ Element signedResourceElement = doc.createElementNS(null, "signedContent"); signedResourceElement.appendChild(doc.createTextNode("Signed Text\n")); rootElement.appendChild(signedResourceElement); XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_MAC_HMAC_SHA1); signedResourceElement.appendChild(sig.getElement()); { String rootnamespace = signedResourceElement.getNamespaceURI(); boolean rootprefixed = (rootnamespace != null) && (rootnamespace.length() > 0); String rootlocalname = signedResourceElement.getNodeName(); Transforms transforms = new Transforms(doc); XPathContainer xpath = new XPathContainer(doc); xpath.setXPathNamespaceContext("ds", Constants.SignatureSpecNS); if (rootprefixed) { xpath.setXPathNamespaceContext("root", rootnamespace); } //J- String xpathStr = "\n" + "count( " + "\n" + " ancestor-or-self::" + (rootprefixed ? "root:" : "") + rootlocalname + "" + "\n" + " | " + "\n" + " here()/ancestor::" + (rootprefixed ? "root:" : "") + rootlocalname + "[1] " + "\n" + ") <= count( " + "\n" + " ancestor-or-self::" + (rootprefixed ? "root:" : "") + rootlocalname + "" + "\n" + ") " + "\n" + " and " + "\n" + "count( " + "\n" + " ancestor-or-self::ds:Signature " + "\n" + " | " + "\n" + " here()/ancestor::ds:Signature[1] " + "\n" + ") > count( " + "\n" + " ancestor-or-self::ds:Signature " + "\n" + ") " + "\n" ; //J+ xpath.setXPath(xpathStr); transforms.addTransform(Transforms.TRANSFORM_XPATH, xpath.getElementPlusReturns()); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { sig.getKeyInfo().add(new KeyName(doc, CreateCollectableSignature.passphrase)); System.out.println("Start signing"); sig.sign(sig.createSecretKey(CreateCollectableSignature.passphrase.getBytes())); System.out.println("Finished signing"); } FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); System.out.println("Wrote signature to " + BaseURI); SignedInfo s = sig.getSignedInfo(); for (int i = 0; i < s.getSignedContentLength(); i++) { System.out.println("################ Signed Resource " + i + " ################"); System.out.println(new String(s.getSignedContentItem(i))); System.out.println(); } }
From source file:org.apache.xml.security.samples.signature.CreateDonaldsAdditionalURISignature.java
static Document createDocument(DocumentBuilder db) throws Exception { Document doc = db.newDocument(); Element root = doc.createElementNS(null, "container"); Element contents = doc.createElementNS(null, "signedContents"); doc.appendChild(root);/*from ww w . jav a 2 s. co m*/ XMLUtils.addReturnToElement(root); root.appendChild(contents); XMLUtils.addReturnToElement(root); contents.appendChild(doc.createTextNode( "\nSigned item\n\nfor questions, contact geuer-pollmann@nue.et-inf.uni-siegen.de\n")); return doc; }
From source file:org.apache.xml.security.samples.signature.CreateMerlinsExampleSixteen.java
/** * Method main/*w w w .j a v a2 s. co m*/ * * @param unused * @throws Exception */ public static void main(String unused[]) throws Exception { Constants.setSignatureSpecNSprefix("ds"); //J- String keystoreType = "JKS"; String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks"; String keystorePass = "xmlsecurity"; String privateKeyAlias = "test"; String privateKeyPass = "xmlsecurity"; String certificateAlias = "test"; File signatureFile = new File("merlinsSixteenRecreatedNoRetrievalMethod.xml"); //J+ KeyStore ks = KeyStore.getInstance(keystoreType); FileInputStream fis = new FileInputStream(keystoreFile); ks.load(fis, keystorePass.toCharArray()); PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); if (privateKey == null) { throw new RuntimeException("Private key is null"); } X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias); javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); org.w3c.dom.Document doc = db.newDocument(); ////////////////////////////////////////////////// Element envelope = doc.createElementNS("http://www.usps.gov/", "Envelope"); envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "http://www.usps.gov/"); envelope.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:foo", "http://www.usps.gov/foo"); envelope.appendChild(doc.createTextNode("\n")); doc.appendChild(doc.createComment(" Preamble ")); doc.appendChild(envelope); doc.appendChild(doc.createComment(" Postamble ")); Element dearSir = doc.createElementNS("http://www.usps.gov/", "DearSir"); dearSir.appendChild(doc.createTextNode("foo")); envelope.appendChild(dearSir); envelope.appendChild(doc.createTextNode("\n")); Element body = doc.createElementNS("http://www.usps.gov/", "Body"); body.appendChild(doc.createTextNode("bar")); envelope.appendChild(body); envelope.appendChild(doc.createTextNode("\n")); Element YoursSincerely = doc.createElementNS("http://www.usps.gov/", "YoursSincerely"); YoursSincerely.appendChild(doc.createTextNode("\n")); envelope.appendChild(YoursSincerely); Element PostScript = doc.createElementNS("http://www.usps.gov/", "PostScript"); PostScript.appendChild(doc.createTextNode("bar")); envelope.appendChild(PostScript); Element Notaries = doc.createElementNS(null, "Notaries"); Notaries.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); Notaries.setAttributeNS(null, "Id", "notaries"); IdResolver.registerElementById(Notaries, "Id"); { Element Notary = doc.createElementNS(null, "Notary"); Notary.setAttributeNS(null, "name", "Great, A. T."); Notaries.appendChild(Notary); } { Element Notary = doc.createElementNS(null, "Notary"); Notary.setAttributeNS(null, "name", "Hun, A. T."); Notaries.appendChild(Notary); } envelope.appendChild(Notaries); envelope.appendChild(doc.createComment(" Commentary ")); ////////////////////////////////////////////////// String BaseURI = signatureFile.toURL().toString(); XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA); YoursSincerely.appendChild(sig.getElement()); sig.setId("signature"); /* * Add the Objects */ // object-1 { ObjectContainer object1 = new ObjectContainer(doc); object1.setId("object-1"); object1.setMimeType("text/plain"); object1.appendChild(doc.createTextNode("I am the text.")); sig.appendObject(object1); } // object-2 { ObjectContainer object2 = new ObjectContainer(doc); object2.setId("object-2"); object2.setMimeType("text/plain"); object2.setEncoding("http://www.w3.org/2000/09/xmldsig#base64"); object2.appendChild(doc.createTextNode("SSBhbSB0aGUgdGV4dC4=")); sig.appendObject(object2); } // object-3 { ObjectContainer object = new ObjectContainer(doc); object.setId("object-3"); Element nonc = doc.createElementNS(null, "NonCommentandus"); nonc.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); nonc.appendChild(doc.createComment(" Commentandum ")); object.appendChild(doc.createTextNode("\n ")); object.appendChild(nonc); object.appendChild(doc.createTextNode("\n ")); sig.appendObject(object); } // object number 4 { ObjectContainer object = new ObjectContainer(doc); object.appendChild(createObject4(sig)); sig.appendObject(object); } // object number 4 { ObjectContainer object = new ObjectContainer(doc); SignatureProperties sps = new SignatureProperties(doc); sps.setId("signature-properties-1"); SignatureProperty sp = new SignatureProperty(doc, "#signature"); Element signedAdress = doc.createElementNS("urn:demo", "SignedAddress"); signedAdress.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", "urn:demo"); Element IP = doc.createElementNS("urn:demo", "IP"); IP.appendChild(doc.createTextNode("192.168.21.138")); signedAdress.appendChild(IP); sp.appendChild(signedAdress); sps.addSignatureProperty(sp); object.appendChild(sps.getElement()); sig.appendObject(object); } { ObjectContainer object = new ObjectContainer(doc); object.setId("object-4"); X509Data x509data = new X509Data(doc); x509data.add(new XMLX509SubjectName(doc, cert)); x509data.add(new XMLX509IssuerSerial(doc, cert)); x509data.add(new XMLX509Certificate(doc, cert)); object.appendChild(x509data.getElement()); sig.appendObject(object); } /* * Add References */ sig.getSignedInfo() .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver()); sig.addDocument("http://www.w3.org/TR/xml-stylesheet"); { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE); sig.addDocument("http://xmldsig.pothole.com/xml-stylesheet.txt", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { Transforms transforms = new Transforms(doc); XPathContainer xpathC = new XPathContainer(doc); xpathC.setXPath("self::text()"); transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns()); sig.addDocument("#object-1", transforms, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } /* { Transforms transforms = new Transforms(doc); XPathContainer xpathC = new XPathContainer(doc); //J- xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS); xpathC.setXPath("\n" + " ancestor-or-self::ds:SignedInfo " + "\n" + " and " + "\n" + " count(ancestor-or-self::ds:Reference | " + "\n" + " here()/ancestor::ds:Reference[1]) > " + "\n" + " count(ancestor-or-self::ds:Reference) " + "\n" + " or " + "\n" + " count(ancestor-or-self::node() | " + "\n" + " id('notaries')) = " + "\n" + " count(ancestor-or-self::node()) " + "\n"); //J+ transforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElementPlusReturns()); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } */ { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_BASE64_DECODE); sig.addDocument("#object-2", transforms, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } sig.addDocument("#manifest-1", null, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Manifest"); sig.addDocument("#signature-properties-1", null, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#SignatureProperties"); { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("#xpointer(/)", transforms, Constants.ALGO_ID_DIGEST_SHA1); } { sig.addDocument("#object-3", null, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("#object-3", transforms, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } { sig.addDocument("#xpointer(id('object-3'))", null, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } { Transforms transforms = new Transforms(doc); transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS); sig.addDocument("#xpointer(id('object-3'))", transforms, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Object"); } { sig.addDocument("#manifest-reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-1", "http://www.w3.org/2000/09/xmldsig#Reference"); } { sig.addDocument("#reference-1", null, Constants.ALGO_ID_DIGEST_SHA1, "reference-2", "http://www.w3.org/2000/09/xmldsig#Reference"); } { sig.addDocument("#reference-2", null, Constants.ALGO_ID_DIGEST_SHA1, null, "http://www.w3.org/2000/09/xmldsig#Reference"); } /* * Add KeyInfo and sign() */ { Transforms retrievalTransforms = new Transforms(doc); XPathContainer xpathC = new XPathContainer(doc); xpathC.setXPathNamespaceContext("ds", Constants.SignatureSpecNS); xpathC.setXPath("ancestor-or-self::ds:X509Data"); retrievalTransforms.addTransform(Transforms.TRANSFORM_XPATH, xpathC.getElement()); sig.getKeyInfo().add(new RetrievalMethod(doc, "#object-4", retrievalTransforms, "http://www.w3.org/2000/09/xmldsig#X509Data")); /* X509Data x509data = new X509Data(doc); x509data.add(new XMLX509SubjectName(doc, cert)); x509data.add(new XMLX509IssuerSerial(doc, cert)); x509data.add(new XMLX509Certificate(doc, cert)); sig.getKeyInfo().add(x509data); */ System.out.println("Start signing"); sig.sign(privateKey); System.out.println("Finished signing"); } FileOutputStream f = new FileOutputStream(signatureFile); XMLUtils.outputDOMc14nWithComments(doc, f); f.close(); System.out.println("Wrote signature to " + BaseURI); SignedInfo s = sig.getSignedInfo(); for (int i = 0; i < s.getLength(); i++) { Reference r = s.item(i); String fn = "merlin16_" + i + ".html"; System.out.println("Wrote Reference " + i + " to file " + fn); JavaUtils.writeBytesToFilename(fn, r.getHTMLRepresentation().getBytes()); } /* for (int i=0; i<s.getSignedContentLength(); i++) { if (s.item(i).getType().equals(Reference.MANIFEST_URI)) { System.out.println("################ Signed Manifest " + i + " ################"); } else { System.out.println("################ Signed Resource " + i + " ################"); } System.out.println(new String(s.getSignedContentItem(i))); System.out.println(); } */ }