@SuppressWarnings("rawtypes") private static boolean isSignatureGlobal(XMLSignature signature, String rootID) { LOG.debug("Starting signature globality check..."); LOG.debug("Signature: {}", signature); LOG.debug("Root ID: {}", rootID); boolean isGlobal = false; // We check each Reference. One must be the rootId or be "" String refRootID = "#" + rootID; for (Object o : signature.getSignedInfo().getReferences()) { String uri = ((Reference) o).getURI(); if ("".equals(uri) || refRootID.equals(uri)) { isGlobal = true; break; } } LOG.debug("Signature globality check result: {}", isGlobal); return isGlobal; }
private static String explainValidationProblem( DOMValidateContext context, XMLSignature signature) throws XMLSignatureException { @SuppressWarnings("unchecked") // Safe by specification. List<Reference> references = signature.getSignedInfo().getReferences(); StringBuilder builder = new StringBuilder(); builder.append("Signature failed core validation\n"); boolean sv = signature.getSignatureValue().validate(context); builder.append("Signature validation status: " + sv + "\n"); for (Reference ref : references) { builder.append("references["); builder.append(ref.getURI()); builder.append("] validity status: "); builder.append(ref.validate(context)); builder.append("\n"); } return builder.toString(); }
protected List<XMLObject> getReferencedSameDocumentObjects(List<Reference> relevantReferences, List<XMLObject> relevantObjects) { List<XMLObject> referencedObjects = new ArrayList<XMLObject>(1); for (Reference ref : relevantReferences) { String refUri = getSameDocumentReferenceUri(ref); if (refUri == null) { continue; } XMLObject referencedOb = getReferencedObject(relevantObjects, refUri); if (referencedOb != null) { referencedObjects.add(referencedOb); continue; } // content could also be indirectly referenced via manifest addManifestReferencedObjects(relevantObjects, referencedObjects, refUri); } return referencedObjects; }
@SuppressWarnings("unchecked") protected void addManifestReferencedObjects(List<XMLObject> allObjects, List<XMLObject> referencedObjects, String manifestId) { Manifest manifest = getReferencedManifest(allObjects, manifestId); if (manifest == null) { return; } for (Reference manifestRef : (List<Reference>) manifest.getReferences()) { String manifestRefUri = getSameDocumentReferenceUri(manifestRef); if (manifestRefUri == null) { continue; } XMLObject manifestReferencedOb = getReferencedObject(allObjects, manifestRefUri); if (manifestReferencedOb != null) { referencedObjects.add(manifestReferencedOb); } } }
@Override public Output get(Input input) throws Exception { Transform transform = input.getSignatureFactory().newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); Reference ref = input.getSignatureFactory().newReference("#propertiesObject", input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null), Collections.singletonList(transform), null, null); String doc2 = "<ts:timestamp xmlns:ts=\"http:/timestamp\">" + System.currentTimeMillis() + "</ts:timestamp>"; InputStream is = new ByteArrayInputStream(doc2.getBytes("UTF-8")); Document doc = XmlSignatureHelper.newDocumentBuilder(Boolean.TRUE).parse(is); DOMStructure structure = new DOMStructure(doc.getDocumentElement()); SignatureProperty prop = input.getSignatureFactory().newSignatureProperty(Collections.singletonList(structure), input.getSignatureId(), "property"); SignatureProperties properties = input.getSignatureFactory().newSignatureProperties(Collections.singletonList(prop), "properties"); XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(properties), "propertiesObject", null, null); XmlSignatureProperties.Output result = new Output(); result.setReferences(Collections.singletonList(ref)); result.setObjects(Collections.singletonList(propertiesObject)); return result; }
private void addDigestInfosAsReferences(List<DigestInfo> digestInfos, XMLSignatureFactory signatureFactory, List<Reference> references) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MalformedURLException { if (null == digestInfos) { return; } for (DigestInfo digestInfo : digestInfos) { byte[] documentDigestValue = digestInfo.digestValue; DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo), null); String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile()); Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null, documentDigestValue); references.add(reference); } }
private SignedInfo initSignedInfo(XMLSignatureFactory fac) throws Exception { Reference ref = initReference(fac); String cm = null; cm = map.getProperty(CANONICALIZATIONMETHOD); String sigmethod = null; sigmethod = map.getProperty(SIGNATURE_METHOD); if (sigmethod == null) { sigmethod = SignatureMethod.RSA_SHA1; } if (cm == null) { cm = CanonicalizationMethod.EXCLUSIVE; } SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod( cm, (C14NMethodParameterSpec) null), fac.newSignatureMethod(sigmethod, null), Collections.singletonList(ref)); return si; }
public synchronized void sign() throws MarshalException, XMLSignatureException, KeyException { if (this.document == null) throw new RuntimeException("Can't sign a NULL document"); Reference reference = this.signatureFactory.newReference( referenceUri, this.digestMethod, this.transformList, null, null); SignedInfo signedInfo = this.signatureFactory.newSignedInfo( this.canonicalizationMethod, this.signatureMethod, Collections.singletonList(reference)); // Create the KeyInfo containing the X509Data. X509Data xd = this.keyInfoFactory.newX509Data( Collections.singletonList(this.certificateWithKey.certificate)); KeyInfo keyInfo = this.keyInfoFactory.newKeyInfo(Collections.singletonList(xd)); XMLSignature signature = this.signatureFactory.newXMLSignature( signedInfo, keyInfo); DOMSignContext signingContext = new DOMSignContext( this.certificateWithKey.privateKey, document.getDocumentElement()); signature.sign(signingContext); }
public synchronized boolean validate() throws MarshalException, XMLSignatureException { // Find Signature element. NodeList list = document.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); if (list.getLength() == 0) { throw new RuntimeException("Cannot find Signature element"); } // Create a DOMValidateContext and specify a KeySelector // and document context. DOMValidateContext validateContext = new DOMValidateContext(new X509CertificateKeySelector(), list.item(0)); // Unmarshal the XMLSignature. XMLSignature signature = this.signatureFactory.unmarshalXMLSignature(validateContext); // Validate the XMLSignature. if (signature.validate(validateContext)) { return true; } else { Iterator<?> i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { System.out.print("ref[" + j + "] -> "); Reference ref = (Reference) i.next(); System.out.print(ref.getURI()); System.out.print(", "); System.out.print(ref.getDigestMethod().toString()); System.out.print(", "); System.out.print(ref.getId()); boolean refValid = ref.validate(validateContext); System.out.print(", validity status: " + refValid + "\r\n"); } return false; } }
/** * Sign SAML element. * * @param element the element * @param privKey the priv key * @param pubKey the pub key * @return the element */ private static org.jdom.Element signSamlElement(final org.jdom.Element element, final PrivateKey privKey, final PublicKey pubKey) { try { final String providerName = System.getProperty("jsr105Provider", SIGNATURE_FACTORY_PROVIDER_CLASS); final XMLSignatureFactory sigFactory = XMLSignatureFactory .getInstance("DOM", (Provider) Class.forName(providerName).newInstance()); final List<Transform> envelopedTransform = Collections.singletonList(sigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); final Reference ref = sigFactory.newReference(StringUtils.EMPTY, sigFactory .newDigestMethod(DigestMethod.SHA1, null), envelopedTransform, null, null); // Create the SignatureMethod based on the type of key final SignatureMethod signatureMethod; final String algorithm = pubKey.getAlgorithm(); switch (algorithm) { case "DSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null); break; case "RSA": signatureMethod = sigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); break; default: throw new RuntimeException("Error signing SAML element: Unsupported type of key"); } final CanonicalizationMethod canonicalizationMethod = sigFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); // Create the SignedInfo final SignedInfo signedInfo = sigFactory.newSignedInfo( canonicalizationMethod, signatureMethod, Collections.singletonList(ref)); // Create a KeyValue containing the DSA or RSA PublicKey final KeyInfoFactory keyInfoFactory = sigFactory.getKeyInfoFactory(); final KeyValue keyValuePair = keyInfoFactory.newKeyValue(pubKey); // Create a KeyInfo and add the KeyValue to it final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(keyValuePair)); // Convert the JDOM document to w3c (Java XML signature API requires w3c representation) final Element w3cElement = toDom(element); // Create a DOMSignContext and specify the DSA/RSA PrivateKey and // location of the resulting XMLSignature's parent element final DOMSignContext dsc = new DOMSignContext(privKey, w3cElement); final Node xmlSigInsertionPoint = getXmlSignatureInsertLocation(w3cElement); dsc.setNextSibling(xmlSigInsertionPoint); // Marshal, generate (and sign) the enveloped signature final XMLSignature signature = sigFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(dsc); return toJdom(w3cElement); } catch (final Exception e) { throw new RuntimeException("Error signing SAML element: " + e.getMessage(), e); } }
public Document sign(FileInputStream fileStream, KeyPair keyPair) throws ParserConfigurationException, SAXException, IOException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException, XMLSignatureException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.parse(fileStream); DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document.getDocumentElement()); XMLSignatureFactory signFactory = XMLSignatureFactory .getInstance("DOM"); Reference ref = signFactory.newReference("", signFactory .newDigestMethod(digestMethod, null), Collections .singletonList(signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null); SignedInfo si = signFactory.newSignedInfo(signFactory .newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), signFactory .newSignatureMethod(signatureMethod, null), Collections .singletonList(ref)); KeyInfoFactory kif = signFactory.getKeyInfoFactory(); KeyValue kv = kif.newKeyValue(keyPair.getPublic()); KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature signature = signFactory.newXMLSignature(si, ki); signature.sign(signContext); return document; }
private void test_create_signature_enveloping( SignatureMethod sm, DigestMethod dm, KeyInfo ki, Key signingKey, KeySelector ks ) throws Exception { // create reference Reference ref = fac.newReference("#DSig.Object_1", dm, null, XMLObject.TYPE, null); // create SignedInfo SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref)); Document doc = db.newDocument(); // create Objects Element webElem = doc.createElementNS(null, "Web"); Text text = doc.createTextNode("up up and away"); webElem.appendChild(text); XMLObject obj = fac.newXMLObject(Collections.singletonList (new DOMStructure(webElem)), "DSig.Object_1", "text/xml", null); // create XMLSignature XMLSignature sig = fac.newXMLSignature (si, ki, Collections.singletonList(obj), null, null); DOMSignContext dsc = new DOMSignContext(signingKey, doc); dsc.setDefaultNamespacePrefix("dsig"); sig.sign(dsc); TestUtils.validateSecurityOrEncryptionElement(doc.getDocumentElement()); // XMLUtils.outputDOM(doc.getDocumentElement(), System.out); DOMValidateContext dvc = new DOMValidateContext (ks, doc.getDocumentElement()); XMLSignature sig2 = fac.unmarshalXMLSignature(dvc); assertTrue(sig.equals(sig2)); assertTrue(sig2.validate(dvc)); }
public String assinarDocumento(final String conteudoXml) throws Exception { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); try (InputStream certificadoStream = new ByteArrayInputStream(this.config.getCertificado())) { keyStore.load(certificadoStream, this.config.getCertificadoSenha().toCharArray()); } final KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(keyStore.aliases().nextElement(), new KeyStore.PasswordProtection(this.config.getCertificadoSenha().toCharArray())); final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); final List<Transform> transforms = new ArrayList<>(2); transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transforms.add(signatureFactory.newTransform(AssinaturaDigital.C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); final KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory(); final X509Data x509Data = keyInfoFactory.newX509Data(Collections.singletonList((X509Certificate) keyEntry.getCertificate())); final KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data)); final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); try (StringReader stringReader = new StringReader(conteudoXml)) { final Document document = documentBuilderFactory.newDocumentBuilder().parse(new InputSource(stringReader)); for (final String elementoAssinavel : AssinaturaDigital.ELEMENTOS_ASSINAVEIS) { final NodeList elements = document.getElementsByTagName(elementoAssinavel); for (int i = 0; i < elements.getLength(); i++) { final Element element = (Element) elements.item(i); final String id = element.getAttribute("Id"); element.setIdAttribute("Id", true); final Reference reference = signatureFactory.newReference("#" + id, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transforms, null, null); final SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); final XMLSignature signature = signatureFactory.newXMLSignature(signedInfo, keyInfo); signature.sign(new DOMSignContext(keyEntry.getPrivateKey(), element.getParentNode())); } } return this.converteDocumentParaXml(document); } }
protected Node getNodeForMessageBodyInEnvelopingCase(Input input) throws Exception { //NOPMD Node node; List<Reference> relevantReferences = getReferencesForMessageMapping(input); List<XMLObject> relevantObjects = getObjectsForMessageMapping(input); DOMStructure domStruc = getDomStructureForMessageBody(relevantReferences, relevantObjects); node = domStruc.getNode(); return node; }
/** * Returns the DOM structure which is transformed to a byte array and set to * the camel message body. * * @param relevantReferences * input from method * {@link #getReferencesForMessageMapping(ReferencesAndObjects)} * @param relevantObjects * input from method * {@link #getObjectsForMessageMapping(ReferencesAndObjects)} * @return dom structure * @throws Exception * if an error occurs */ protected DOMStructure getDomStructureForMessageBody(List<Reference> relevantReferences, List<XMLObject> relevantObjects) throws Exception { //NOPMD List<XMLObject> referencedObjects = getReferencedSameDocumentObjects(relevantReferences, relevantObjects); if (referencedObjects.isEmpty()) { throw new XmlSignatureException( String.format("Unsupported XML signature document: Content object not found in the enveloping XML signature.")); } if (referencedObjects.size() > 1) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < referencedObjects.size(); i++) { XMLObject xmlOb = referencedObjects.get(i); sb.append(xmlOb.getId()); if (i < referencedObjects.size() - 1) { sb.append(", "); } } throw new XmlSignatureException(String.format( "Unsupported XML signature document: More than one content objects found. Object IDs: %s", sb.toString())); } @SuppressWarnings("unchecked") List<XMLStructure> structures = referencedObjects.get(0).getContent(); if (structures.size() == 0) { throw new XmlSignatureException( "Unsupported XML signature: XML signature is not enveloping; content not found in XML signature: structure list is empty."); } if (structures.size() > 1) { throw new XmlSignatureException("Unsupported XML signature: more than one structure elements in referenced content object."); } XMLStructure structure = structures.get(0); // only dom currently supported DOMStructure domStruc = (DOMStructure) structure; return domStruc; }
protected String getSameDocumentReferenceUri(Reference ref) { String refUri = ref.getURI(); if (refUri == null) { LOG.warn("Ignoring reference {} which has no URI", ref); return null; } if (!refUri.startsWith("#")) { LOG.warn("Ignoring non-same document reference {}", refUri); return null; } return refUri.substring(1); }
@Override public void referenceValidationFailed(Reference ref) throws Exception { //NOPMD error.append(String .format("The calculated digest value of the document %s is not equal to the value specified in the XML signature. The document may have been tampered.", getReferenceUriOrId(ref))); throw new XmlSignatureInvalidContentHashException(error.toString()); }
@Override public void manifestReferenceValidationFailed(Reference ref) throws Exception { //NOPMD error.append(String .format("The calculated digest value of the manifest %s is not equal to the value specified in the XML signature. The document may have been tampered.", getReferenceUriOrId(ref))); throw new XmlSignatureInvalidContentHashException(error.toString()); }
private String getReferenceUriOrId(Reference ref) { String docId = ref.getURI(); if (docId == null) { docId = ref.getId(); } return docId; }
protected Reference createReference(XMLSignatureFactory fac, String uri, String type, SignatureType sigType, String id, Message message) throws InvalidAlgorithmParameterException, XmlSignatureException { try { List<Transform> transforms = getTransforms(fac, sigType, message); Reference ref = fac.newReference(uri, fac.newDigestMethod(getDigestAlgorithmUri(), null), transforms, type, id); return ref; } catch (NoSuchAlgorithmException e) { throw new XmlSignatureException("Wrong algorithm specified in the configuration.", e); } }
protected Reference createKeyInfoReference(XMLSignatureFactory fac, String keyInfoId, String digestAlgorithm) throws Exception { //NOPMD if (keyInfoId == null) { return null; } if (getConfiguration().getAddKeyInfoReference() == null) { return null; } if (!getConfiguration().getAddKeyInfoReference()) { return null; } LOG.debug("Creating reference to key info element with Id: {}", keyInfoId); List<Transform> transforms = new ArrayList<Transform>(1); Transform transform = fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null); transforms.add(transform); return fac.newReference("#" + keyInfoId, fac.newDigestMethod(digestAlgorithm, null), transforms, null, null); }
protected List<Reference> getReferencesForMessageMapping(Input input) throws Exception { List<Reference> result = new ArrayList<Reference>(1); for (Reference ref : input.getReferences()) { if (ref.getURI() != null && ref.getURI().contains("propert")) { // do not add } else { result.add(ref); } } return result; }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Map<String, String> xpathNamespaceMap = new HashMap<String, String>(); xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#"); // XPath v1 - slow... // Transform envelopedTransform = signatureFactory.newTransform( // CanonicalizationMethod.XPATH, new XPathFilterParameterSpec( // "not(ancestor-or-self::ds:Signature)", // xpathNamespaceMap)); // XPath v2 - fast... List<XPathType> types = new ArrayList<XPathType>(1); types.add(new XPathType("/descendant::*[name()='ds:Signature']", XPathType.Filter.SUBTRACT, xpathNamespaceMap)); Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.XPATH2, new XPathFilter2ParameterSpec(types)); transforms.add(envelopedTransform); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, this.dsReferenceId); references.add(reference); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); List<Transform> transforms = new LinkedList<Transform>(); Transform envelopedTransform = signatureFactory.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null); transforms.add(envelopedTransform); Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null); transforms.add(exclusiveTransform); Reference reference = signatureFactory.newReference("", digestMethod, transforms, null, null); references.add(reference); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("pre sign"); Element dateElement = document.createElementNS("", "dc:date"); dateElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:dc", "http://purl.org/dc/elements/1.1/"); DateTime dateTime = new DateTime(DateTimeZone.UTC); DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis(); String now = fmt.print(dateTime); now = now.substring(0, now.indexOf("Z")); LOG.debug("now: " + now); dateElement.setTextContent(now); String signaturePropertyId = "sign-prop-" + UUID.randomUUID().toString(); List<XMLStructure> signaturePropertyContent = new LinkedList<XMLStructure>(); signaturePropertyContent.add(new DOMStructure(dateElement)); SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(signaturePropertyContent, "#" + signatureId, signaturePropertyId); List<XMLStructure> objectContent = new LinkedList<XMLStructure>(); List<SignatureProperty> signaturePropertiesContent = new LinkedList<SignatureProperty>(); signaturePropertiesContent.add(signatureProperty); SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertiesContent, null); objectContent.add(signatureProperties); objects.add(signatureFactory.newXMLObject(objectContent, null, null, null)); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Reference reference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod); references.add(reference); }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { LOG.debug("pre sign"); addManifestObject(signatureFactory, document, signatureId, references, objects); addSignatureInfo(signatureFactory, document, signatureId, references, objects); }
private void addManifestObject(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { Manifest manifest = constructManifest(signatureFactory, document); String objectId = "idPackageObject"; // really has to be this value. List<XMLStructure> objectContent = new LinkedList<XMLStructure>(); objectContent.add(manifest); addSignatureTime(signatureFactory, document, signatureId, objectContent); objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null)); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null, "http://www.w3.org/2000/09/xmldsig#Object", null); references.add(reference); }
private Manifest constructManifest(XMLSignatureFactory signatureFactory, Document document) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { List<Reference> manifestReferences = new LinkedList<Reference>(); try { addManifestReferences(signatureFactory, document, manifestReferences); } catch (Exception e) { throw new RuntimeException("error: " + e.getMessage(), e); } return signatureFactory.newManifest(manifestReferences); }
private void addSignatureInfo(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { List<XMLStructure> objectContent = new LinkedList<XMLStructure>(); Element signatureInfoElement = document.createElementNS(OFFICE_DIGSIG_NS, "SignatureInfoV1"); signatureInfoElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", OFFICE_DIGSIG_NS); Element manifestHashAlgorithmElement = document.createElementNS(OFFICE_DIGSIG_NS, "ManifestHashAlgorithm"); manifestHashAlgorithmElement.setTextContent("http://www.w3.org/2000/09/xmldsig#sha1"); signatureInfoElement.appendChild(manifestHashAlgorithmElement); List<XMLStructure> signatureInfoContent = new LinkedList<XMLStructure>(); signatureInfoContent.add(new DOMStructure(signatureInfoElement)); SignatureProperty signatureInfoSignatureProperty = signatureFactory.newSignatureProperty(signatureInfoContent, "#" + signatureId, "idOfficeV1Details"); List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>(); signaturePropertyContent.add(signatureInfoSignatureProperty); SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent, null); objectContent.add(signatureProperties); String objectId = "idOfficeObject"; objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null)); DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null); Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null, "http://www.w3.org/2000/09/xmldsig#Object", null); references.add(reference); }
private Reference findReferenceFromURI(List<Reference> refs, String referenceURI) { for (Reference ref : refs) { if (ref.getURI().equals(referenceURI)) { LOG.debug("Found \"" + referenceURI + "\" ds:reference"); return ref; } } return null; }
public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId, List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); for (String uri : this.uris) { Reference reference = signatureFactory.newReference(uri, digestMethod); references.add(reference); } }
@Test public void testJsr105ReferenceUri() throws Exception { String uri = FilenameUtils.getName(new File("foo bar.txt").toURI().toURL().getFile()); KeyPair keyPair = generateKeyPair(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.newDocument(); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI()); XMLSignContext signContext = new DOMSignContext(keyPair.getPrivate(), document); byte[] externalDocument = "hello world".getBytes(); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(externalDocument); byte[] documentDigestValue = messageDigest.digest(); DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA1, null); Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null, documentDigestValue); SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null); CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null); javax.xml.crypto.dsig.SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, Collections.singletonList(reference)); javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null); xmlSignature.sign(signContext); }
/** * Validates if the first XML Signature of the given document is valid * Only used for test purposes * * @param document * Document with signature to validate * @return true if valid, else false */ public boolean validateSignature(Document document) throws Exception { setIDAttribute(document); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM"); // Find Signature element. NodeList nl = document.getElementsByTagNameNS(javax.xml.crypto.dsig.XMLSignature.XMLNS, "Signature"); if (nl.getLength() == 0) { throw new Exception("Cannot find Signature element"); } // Create a DOMValidateContext and specify a KeySelector // and document context. DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0)); // Unmarshal the XMLSignature javax.xml.crypto.dsig.XMLSignature signature = fac.unmarshalXMLSignature(valContext); // Validate the XMLSignature. boolean coreValidity = signature.validate(valContext); // Check core validation status. if (coreValidity == false) { boolean sv = signature.getSignatureValue().validate(valContext); if (sv == false) { if(Flags.DEBUG){ // Check the validation status of each Reference. @SuppressWarnings("rawtypes") 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); } } } } return coreValidity; }
private SecurityTokenReference createSecurityTokenReference(BinarySecurityToken bst) { SecurityTokenReference str = SAMLUtil.buildXMLObject(SecurityTokenReference.class); org.opensaml.ws.wssecurity.Reference ref = SAMLUtil.buildXMLObject(org.opensaml.ws.wssecurity.Reference.class); ref.setValueType(bst.getValueType()); ref.setURI("#" + bst.getWSUId()); str.getUnknownXMLObjects().add(ref); return str; }
private Element signSignature(String id, Element env, KeyInfoFactory keyInfoFactory, X509Credential credential) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException, XMLSignatureException { if (endorsingToken == null) return env; NodeList nl = env.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); for (int i = 0; i < nl.getLength(); i++) { Element e = (Element) nl.item(i); if (e.hasAttributeNS(null, "Id")) { e.setAttributeNS(WSSecurityConstants.WSU_NS, "Id", e.getAttribute("Id")); e.setIdAttributeNS(WSSecurityConstants.WSU_NS, "Id", true); } } env = SAMLUtil.loadElementFromString(XMLHelper.nodeToString(env)); DigestMethod digestMethod = xsf.newDigestMethod(DigestMethod.SHA1, null); List<Transform> transforms = new ArrayList<Transform>(2); transforms.add(xsf.newTransform("http://www.w3.org/2001/10/xml-exc-c14n#",new ExcC14NParameterSpec(Collections.singletonList("xsd")))); List<Reference> refs = new ArrayList<Reference>(); Reference r = xsf.newReference("#"+id, digestMethod, transforms, null, null); refs.add(r); CanonicalizationMethod canonicalizationMethod = xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null); SignatureMethod signatureMethod = xsf.newSignatureMethod(SignatureMethod.RSA_SHA1, null); SignedInfo signedInfo = xsf.newSignedInfo(canonicalizationMethod, signatureMethod, refs); KeyInfo ki = generateKeyInfo(credential, keyInfoFactory, false); XMLSignature signature = xsf.newXMLSignature(signedInfo, ki); Node security = env.getElementsByTagNameNS(WSSecurityConstants.WSSE_NS, "Security").item(0); DOMSignContext signContext = new DOMSignContext(credential.getPrivateKey(), security); signContext.putNamespacePrefix(SAMLConstants.XMLSIG_NS, SAMLConstants.XMLSIG_PREFIX); signContext.putNamespacePrefix(SAMLConstants.XMLENC_NS, SAMLConstants.XMLENC_PREFIX); signature.sign(signContext); return env; }
public <T extends Node> T sign(T node) { checkNotNull(node); checkArgument(node instanceof Document || node instanceof Element); try { Element element = node instanceof Document ? ((Document) node).getDocumentElement() : (Element) node; DOMSignContext dsc = new DOMSignContext(privateKey, element); XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM"); List<Transform> transformList = new LinkedList<>(); transformList.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)); transformList.add(signatureFactory.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null)); Node child = findFirstElementChild(element); ((Element) child).setIdAttribute("Id", true); String id = child.getAttributes().getNamedItem("Id").getNodeValue(); String uri = String.format("#%s", id); Reference reference = signatureFactory.newReference(uri, signatureFactory.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null); SignedInfo signedInfo = signatureFactory.newSignedInfo(signatureFactory.newCanonicalizationMethod( CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), signatureFactory .newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(reference)); KeyInfoFactory kif = signatureFactory.getKeyInfoFactory(); X509Data x509Data = kif.newX509Data(Collections.singletonList(certificateChain[0])); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(x509Data)); XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo); xmlSignature.sign(dsc); return node; } catch (Exception ex) { throw new IllegalArgumentException("Erro ao assinar XML.", ex); } }
private void sign(KeyStore keyStore, KeyPair keyPair, String alias, Document document, List<EbMSDataSource> dataSources) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, KeyException, MarshalException, XMLSignatureException, KeyStoreException { //XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance("DOM"); XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(); DigestMethod sha1DigestMethod = signFactory.newDigestMethod(DigestMethod.SHA1,null); List<Transform> transforms = new ArrayList<Transform>(); transforms.add(signFactory.newTransform(Transform.ENVELOPED,(TransformParameterSpec)null)); Map<String,String> m = new HashMap<String,String>(); m.put("soap","http://schemas.xmlsoap.org/soap/envelope/"); transforms.add(signFactory.newTransform(Transform.XPATH,new XPathFilterParameterSpec("not(ancestor-or-self::node()[@soap:actor=\"urn:oasis:names:tc:ebxml-msg:service:nextMSH\"]|ancestor-or-self::node()[@soap:actor=\"http://schemas.xmlsoap.org/soap/actor/next\"])",m))); transforms.add(signFactory.newTransform(CanonicalizationMethod.INCLUSIVE,(TransformParameterSpec)null)); List<Reference> references = new ArrayList<Reference>(); references.add(signFactory.newReference("",sha1DigestMethod,transforms,null,null)); for (EbMSDataSource dataSource : dataSources) references.add(signFactory.newReference("cid:" + dataSource.getContentId(),sha1DigestMethod,Collections.emptyList(),null,null,DigestUtils.sha(IOUtils.toByteArray(dataSource.getInputStream())))); SignedInfo signedInfo = signFactory.newSignedInfo(signFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,(C14NMethodParameterSpec)null),signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1,null),references); List<XMLStructure> keyInfoElements = new ArrayList<XMLStructure>(); KeyInfoFactory keyInfoFactory = signFactory.getKeyInfoFactory(); keyInfoElements.add(keyInfoFactory.newKeyValue(keyPair.getPublic())); Certificate[] certificates = keyStore.getCertificateChain(alias); //keyInfoElements.add(keyInfoFactory.newX509Data(Arrays.asList(certificates))); keyInfoElements.add(keyInfoFactory.newX509Data(Collections.singletonList(certificates[0]))); KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoElements); XMLSignature signature = signFactory.newXMLSignature(signedInfo,keyInfo); Element soapHeader = getFirstChildElement(document.getDocumentElement()); DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(),soapHeader); signContext.putNamespacePrefix(XMLSignature.XMLNS,"ds"); signature.sign(signContext); }