Camel Components

XML Security Verify

Since Camel 2.12

Only producer is supported

With this Apache Camel component, you can generate and validate XML signatures as described in the W3C standard XML Signature Syntax and Processing or as described in the successor version 1.1. For XML Encryption support, please refer to the XML Security Data Format.

You can find an introduction to XML signature here. The implementation of the component is based on JSR 105, the Java API corresponding to the W3C standard and supports the Apache Santuario and the JDK provider for JSR 105. The implementation will first try to use the Apache Santuario provider; if it does not find the Santuario provider, it will use the JDK provider. Further, the implementation is DOM based.

We also provide support for XAdES-BES/EPES for the signer endpoint; see subsection "XAdES-BES/EPES for the Signer Endpoint".

Maven users will need to add the following dependency to their pom.xml for this component:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-xmlsecurity</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

URI Format

The camel component consists of two endpoints which have the following URI format:

xmlsecurity-sign:name[?options]
xmlsecurity-verify:name[?options]
  • With the signer endpoint, you can generate a XML signature for the body of the in-message, which can be either a XML document or a plain text. The enveloped, enveloping, or detached (as of 12.14) XML signature(s) will be set to the body of the out-message.

  • With the verifier endpoint, you can validate an enveloped or enveloping XML signature or even several detached XML signatures contained in the body of the in-message; if the validation is successful, then the original content is extracted from the XML signature and set to the body of the out-message.

  • The name part in the URI can be chosen by the user to distinguish between different signer/verifier endpoints within the camel context.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The XML Security Verify component supports the following options which are listed below.

Name Description Default Type

baseUri (producer)

The base URI that relative URIs of the references are resolved against, set on the XMLSignContext of the signer and the XMLValidateContext of the verifier (XMLCryptoContext.setBaseURI).

String

clearHeaders (producer)

Whether to remove the CamelXmlSignature headers of this component from the message after signing or verifying. The CamelCharsetName header is kept.

true

Boolean

cryptoContextProperties (producer)

Properties that are set on the XMLSignContext of the signer and the XMLValidateContext of the verifier, see XMLCryptoContext.setProperty and the properties that the XML signature provider supports. The verifier sets javax.xml.crypto.dsig.cacheReference and org.jcp.xml.dsig.validateManifests to true itself; these properties are set after that, so a value given here replaces the value that the verifier sets for the same property.

Map

disallowDoctypeDecl (producer)

Whether the parser rejects a message body that contains a DOCTYPE declaration. If false, a DOCTYPE declaration is allowed; external entities stay disabled either way.

true

Boolean

keySelector (producer)

The javax.xml.crypto.KeySelector that provides the key to validate each Signature element with. Required: the verifier fails without it. DefaultKeySelector of the package org.apache.camel.component.xmlsecurity.api returns the public key of the certificate of an alias in a java.security.KeyStore, regardless of the KeyInfo of the signature.

KeySelector

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

omitXmlDeclaration (producer)

Whether to leave out the XML declaration of the output body. Has no effect when the output of the verifier is text. The CamelXmlSignatureOmitXmlDeclaration header replaces this option.

false

Boolean

outputNodeSearch (producer)

The value that the output node search of outputNodeSearchType uses: for ElementName a String in the form {namespace}localName, or localName for an element without a namespace, and for XPath a javax.xml.crypto.dsig.spec.XPathFilterParameterSpec. The search must find exactly one node. Not used by the Default search.

Object

outputNodeSearchType (producer)

How the default xmlSignature2Message finds the node that becomes the output body: Default, ElementName (the element that outputNodeSearch names) or XPath (the element, text or document node that the XPath of outputNodeSearch selects). Default returns the content of the single referenced Object element of an enveloping signature, and the whole document without its Signature elements for an enveloped or detached signature.

Default

String

outputXmlEncoding (producer)

The character encoding of the output body. If not set, UTF-8 is used. If set, the CamelCharsetName header is also set to it; for the verifier, the default xmlSignature2Message does this.

String

removeSignatureElements (producer)

Whether the default xmlSignature2Message removes all Signature elements of the namespace http://www.w3.org/2000/09/xmldsig# from the document before the output node is serialized. For the ElementName and XPath searches of an enveloped signature; the Default search always removes them for an enveloped or detached signature.

false

Boolean

schemaResourceUri (producer)

The XML schema that the message body is validated against while it is parsed, loaded as a resource from the classpath by default. The schema also declares which attributes are of type ID, so it is required for a detached signature and when a reference URI points to an ID. The CamelXmlSignatureSchemaResourceUri header replaces this option.

String

secureValidation (producer)

Whether the verifier sets the properties org.apache.jcp.xml.dsig.secureValidation and org.jcp.xml.dsig.secureValidation to true, which makes the XML signature provider reject, for example, MD5 algorithms, more than 30 references and more than 5 transforms per reference. If false, the verifier does not set them and the default of the provider applies, which for the Apache Santuario provider is also secure validation.

true

Boolean

validationFailedHandler (producer)

Called when the core validation of a signature fails or throws an XMLSignatureException. The default DefaultValidationFailedHandler throws an XmlSignatureInvalidValueException when the signature value is invalid, an XmlSignatureInvalidContentHashException when the digest of a reference or of a manifest reference does not match, and an XmlSignatureInvalidKeyException or XmlSignatureException for an XMLSignatureException. If a custom handler returns true from ignoreCoreValidationFailure, the verifier treats the signature as valid.

ValidationFailedHandler

xmlSignature2Message (producer)

Maps the verified document to the body of the output message. The default DefaultXmlSignature2Message selects the output node with outputNodeSearchType, outputNodeSearch and removeSignatureElements. Its Default search returns the content of the single referenced Object element of an enveloping signature, and the whole document without its Signature elements for an enveloped or detached signature, which can contain content that no reference covers unless its enforceReferenceCoverage is set.

XmlSignature2Message

xmlSignatureChecker (producer)

A bean that implements org.apache.camel.component.xmlsecurity.api.XmlSignatureChecker, which the verifier calls for each Signature element before its core validation, to check that the signature covers the content that the route expects (see http://www.w3.org/TR/xmldsig-bestpractices/#check-what-is-signed). An exception that it throws fails the exchange. If not set, no such check is done.

XmlSignatureChecker

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

uriDereferencer (advanced)

To use a custom javax.xml.crypto.URIDereferencer that resolves the URIs of the references, for example to control which resources can be read. If not set, the dereferencer of the XML signature provider is used; the Apache Santuario provider, which the component uses, resolves only same-document URIs (fragments and XPointer) by default.

URIDereferencer

verifierConfiguration (advanced)

A shared XmlVerifierConfiguration that the endpoints of the component start from: the component copies it for each new endpoint and then sets the options of the endpoint URI on the copy.

XmlVerifierConfiguration

Endpoint Options

The XML Security Verify endpoint is configured using URI syntax:

xmlsecurity-verify:name

With the following path and query parameters:

Path Parameters

Name Description Default Type

name (producer)

Required The name of the endpoint, chosen freely to tell endpoints apart. The component does not use it otherwise.

String

Query Parameters

Name Description Default Type

baseUri (producer)

The base URI that relative URIs of the references are resolved against, set on the XMLSignContext of the signer and the XMLValidateContext of the verifier (XMLCryptoContext.setBaseURI).

String

clearHeaders (producer)

Whether to remove the CamelXmlSignature headers of this component from the message after signing or verifying. The CamelCharsetName header is kept.

true

Boolean

cryptoContextProperties (producer)

Properties that are set on the XMLSignContext of the signer and the XMLValidateContext of the verifier, see XMLCryptoContext.setProperty and the properties that the XML signature provider supports. The verifier sets javax.xml.crypto.dsig.cacheReference and org.jcp.xml.dsig.validateManifests to true itself; these properties are set after that, so a value given here replaces the value that the verifier sets for the same property.

Map

disallowDoctypeDecl (producer)

Whether the parser rejects a message body that contains a DOCTYPE declaration. If false, a DOCTYPE declaration is allowed; external entities stay disabled either way.

true

Boolean

keySelector (producer)

The javax.xml.crypto.KeySelector that provides the key to validate each Signature element with. Required: the verifier fails without it. DefaultKeySelector of the package org.apache.camel.component.xmlsecurity.api returns the public key of the certificate of an alias in a java.security.KeyStore, regardless of the KeyInfo of the signature.

KeySelector

omitXmlDeclaration (producer)

Whether to leave out the XML declaration of the output body. Has no effect when the output of the verifier is text. The CamelXmlSignatureOmitXmlDeclaration header replaces this option.

false

Boolean

outputNodeSearch (producer)

The value that the output node search of outputNodeSearchType uses: for ElementName a String in the form {namespace}localName, or localName for an element without a namespace, and for XPath a javax.xml.crypto.dsig.spec.XPathFilterParameterSpec. The search must find exactly one node. Not used by the Default search.

Object

outputNodeSearchType (producer)

How the default xmlSignature2Message finds the node that becomes the output body: Default, ElementName (the element that outputNodeSearch names) or XPath (the element, text or document node that the XPath of outputNodeSearch selects). Default returns the content of the single referenced Object element of an enveloping signature, and the whole document without its Signature elements for an enveloped or detached signature.

Default

String

outputXmlEncoding (producer)

The character encoding of the output body. If not set, UTF-8 is used. If set, the CamelCharsetName header is also set to it; for the verifier, the default xmlSignature2Message does this.

String

removeSignatureElements (producer)

Whether the default xmlSignature2Message removes all Signature elements of the namespace http://www.w3.org/2000/09/xmldsig# from the document before the output node is serialized. For the ElementName and XPath searches of an enveloped signature; the Default search always removes them for an enveloped or detached signature.

false

Boolean

schemaResourceUri (producer)

The XML schema that the message body is validated against while it is parsed, loaded as a resource from the classpath by default. The schema also declares which attributes are of type ID, so it is required for a detached signature and when a reference URI points to an ID. The CamelXmlSignatureSchemaResourceUri header replaces this option.

String

secureValidation (producer)

Whether the verifier sets the properties org.apache.jcp.xml.dsig.secureValidation and org.jcp.xml.dsig.secureValidation to true, which makes the XML signature provider reject, for example, MD5 algorithms, more than 30 references and more than 5 transforms per reference. If false, the verifier does not set them and the default of the provider applies, which for the Apache Santuario provider is also secure validation.

true

Boolean

validationFailedHandler (producer)

Called when the core validation of a signature fails or throws an XMLSignatureException. The default DefaultValidationFailedHandler throws an XmlSignatureInvalidValueException when the signature value is invalid, an XmlSignatureInvalidContentHashException when the digest of a reference or of a manifest reference does not match, and an XmlSignatureInvalidKeyException or XmlSignatureException for an XMLSignatureException. If a custom handler returns true from ignoreCoreValidationFailure, the verifier treats the signature as valid.

ValidationFailedHandler

xmlSignature2Message (producer)

Maps the verified document to the body of the output message. The default DefaultXmlSignature2Message selects the output node with outputNodeSearchType, outputNodeSearch and removeSignatureElements. Its Default search returns the content of the single referenced Object element of an enveloping signature, and the whole document without its Signature elements for an enveloped or detached signature, which can contain content that no reference covers unless its enforceReferenceCoverage is set.

XmlSignature2Message

xmlSignatureChecker (producer)

A bean that implements org.apache.camel.component.xmlsecurity.api.XmlSignatureChecker, which the verifier calls for each Signature element before its core validation, to check that the signature covers the content that the route expects (see http://www.w3.org/TR/xmldsig-bestpractices/#check-what-is-signed). An exception that it throws fails the exchange. If not set, no such check is done.

XmlSignatureChecker

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

uriDereferencer (advanced)

To use a custom javax.xml.crypto.URIDereferencer that resolves the URIs of the references, for example to control which resources can be read. If not set, the dereferencer of the XML signature provider is used; the Apache Santuario provider, which the component uses, resolves only same-document URIs (fragments and XPointer) by default.

URIDereferencer

Message Headers

The XML Security Verify component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelXmlSignatureOmitXmlDeclaration (producer)

Constant: HEADER_OMIT_XML_DECLARATION

Whether to leave out the XML declaration of the output body. Replaces the omitXmlDeclaration option. The verifier reads it through the default xmlSignature2Message, and it has no effect when the output of the verifier is text.

Boolean

CamelXmlSignatureSchemaResourceUri (producer)

Constant: HEADER_SCHEMA_RESOURCE_URI

The XML schema that the message body is validated against while it is parsed. Replaces the schemaResourceUri option.

String

CamelXmlSignatureXpathsToIdAttributes (producer)

Constant: HEADER_XPATHS_TO_ID_ATTRIBUTES

A java.util.List of javax.xml.crypto.dsig.spec.XPathFilterParameterSpec that selects the ID attributes of the elements that get a detached signature. Replaces the xpathsToIdAttributes option. Only the signer reads it.

String

CamelXmlSignatureXAdESQualifyingPropertiesId (producer)

Constant: HEADER_XADES_QUALIFYING_PROPERTIES_ID

The Id attribute of the XAdES QualifyingProperties element. Only used by the signer when the properties option is an XAdESSignatureProperties. If not set, the element has no Id attribute.

String

CamelXmlSignatureXAdESSignedDataObjectPropertiesId (producer)

Constant: HEADER_XADES_SIGNED_DATA_OBJECT_PROPERTIES_ID

The Id attribute of the XAdES SignedDataObjectProperties element. Only used by the signer when the properties option is an XAdESSignatureProperties. If not set, the element has no Id attribute.

String

CamelXmlSignatureXAdESSignedSignaturePropertiesId (producer)

Constant: HEADER_XADES_SIGNED_SIGNATURE_PROPERTIES_ID

The Id attribute of the XAdES SignedSignatureProperties element. Only used by the signer when the properties option is an XAdESSignatureProperties. If not set, the element has no Id attribute.

String

CamelXmlSignatureXAdESDataObjectFormatEncoding (producer)

Constant: HEADER_XADES_DATA_OBJECT_FORMAT_ENCODING

The text of the Encoding element of the XAdES DataObjectFormat element. Only used by the signer when the properties option is an XAdESSignatureProperties that adds a DataObjectFormat element. If not set, there is no Encoding element.

String

CamelXmlSignatureXAdESNamespace (producer)

Constant: HEADER_XADES_NAMESPACE

The namespace of the XAdES elements, which selects the XAdES version: http://uri.etsi.org/01903/v1.1.1#, http://uri.etsi.org/01903/v1.2.2# or http://uri.etsi.org/01903/v1.3.2#. Replaces the namespace of the XAdESSignatureProperties of the properties option. Only used by the signer.

String

CamelXmlSignatureXAdESPrefix (producer)

Constant: HEADER_XADES_PREFIX

The namespace prefix of the XAdES elements; an empty value means no prefix. Replaces the prefix of the XAdESSignatureProperties of the properties option, which is etsi by default. Only used by the signer.

String

CamelCharsetName (producer)

Constant: CHARSET_NAME

The character encoding of the output body, which the signer and the default xmlSignature2Message of the verifier set when outputXmlEncoding is set. Not removed by clearHeaders.

String

Message Body

The message body at each side of the XML Security Verify component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Producer input

text, bytes, stream, file or pojo, as xml

The signed XML document: text, bytes, a stream, a file or a DOM Document. A document without a Signature element, a body that is not XML or no body fails.

Producer output

bytes (byte[])

The verified content as bytes, in the outputXmlEncoding when set: by default the document without its Signature for an enveloped or detached signature, and the content of the Object for an enveloping one, which is the plain text when it was signed with plainText; outputNodeSearchType picks another node. A signature that does not verify fails the exchange.

Not known when xmlSignature2Message is set.

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

XML Signature Wrapping Modes

XML Signature differs between enveloped, enveloping, and detached XML signature. In the enveloped XML signature case, the XML Signature is wrapped by the signed XML Document; which means that the XML signature element is a child element of a parent element, which belongs to the signed XML Document. In the enveloping XML signature case, the XML Signature contains the signed content. All other cases are called detached XML signatures.

In the enveloped XML signature case, the supported generated XML signature has the following structure (Variables are surrounded by []).

<[parent element]>
   ... <!-- Signature element is added as last child of the parent element-->
   <Signature Id="generated_unique_signature_id">
       <SignedInfo>
             <Reference URI="">
                   <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                   (<Transform>)* <!-- By default "http://www.w3.org/2006/12/xml-c14n11" is added to the transforms -->
                   <DigestMethod>
                   <DigestValue>
             </Reference>
             (<Reference URI="#[keyinfo_Id]">
                   <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
                   <DigestMethod>
                   <DigestValue>
             </Reference>)?
             <!-- further references possible, see option 'properties' below -->
      </SignedInfo>
      <SignatureValue>
      (<KeyInfo Id="[keyinfo_id]">)?
      <!-- Object elements possible, see option 'properties' below -->
  </Signature>
</[parent element]>

In the enveloping XML signature case, the supported generated XML signature has the structure:

<Signature Id="generated_unique_signature_id">
  <SignedInfo>
         <Reference URI="#generated_unique_object_id" type="[optional_type_value]">
               (<Transform>)* <!-- By default "http://www.w3.org/2006/12/xml-c14n11" is added to the transforms -->
               <DigestMethod>
               <DigestValue>
         </Reference>
         (<Reference URI="#[keyinfo_id]">
               <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
               <DigestMethod>
               <DigestValue>
         </Reference>)?
          <!-- further references possible, see option 'properties' below  -->
  </SignedInfo>
  <SignatureValue>
  (<KeyInfo Id="[keyinfo_id]">)?
  <Object Id="generated_unique_object_id"/> <!-- The Object element contains the in-message body; the object ID can either be generated or set by the option parameter "contentObjectId" -->
  <!-- Further Object elements possible, see option 'properties' below -->
</Signature>

Detached XML signatures with the following structure are supported (see also sub-chapter XML Signatures as Siblings of Signed Elements):

(<[signed element] Id="[id_value]">
<!-- signed element must have an attribute of type ID -->
      ...

</[signed element]>
<other sibling/>*
<!-- between the signed element and the corresponding signature element, there can be other siblings.
 Signature element is added as last sibling. -->
<Signature Id="generated_unique_ID">
   <SignedInfo>
      <CanonicalizationMethod>
      <SignatureMethod>
      <Reference URI="#[id_value]" type="[optional_type_value]">
      <!-- reference URI contains the ID attribute value of the signed element -->
            (<Transform>)* <!-- By default "http://www.w3.org/2006/12/xml-c14n11" is added to the transforms -->
            <DigestMethod>
            <DigestValue>
      </Reference>
      (<Reference URI="#[generated_keyinfo_Id]">
            <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
            <DigestMethod>
            <DigestValue>
      </Reference>)?
   </SignedInfo>
   <SignatureValue>
   (<KeyInfo Id="[generated_keyinfo_id]">)?
</Signature>)+

Correlating the Verified Output with the Signed Content

Signature validation proves that each Reference digest matches the content that Reference resolves to. It proves nothing about the rest of the document.

For an enveloped or detached signature the default output node search emits the whole document element. Where the signature covers only a sub-element, an attacker who obtains such a signed document can embed the signed fragment unchanged inside a document of their own: the same-document Reference URI still resolves to that fragment, validation still passes, and the verifier hands the whole surrounding document downstream as verified content. This is XML signature wrapping.

Whether that matters depends on what the route expects. A detached signature that deliberately covers a sub-element and emits the whole document — the pattern described in Detached XML Signatures as Siblings of the Signed Elements below — is doing exactly this on purpose, and nothing in the document distinguishes it from the wrapping case. Only the route knows which it is, so there is no safe default.

Two ways to correlate, in increasing order of specificity:

  • Set enforceReferenceCoverage on DefaultXmlSignature2Message when the signature is expected to cover the document element — a plain enveloped signature with URI="", or with the document element’s own id. Verification then fails if the validated References cover only sub-elements:

    DefaultXmlSignature2Message mapper = new DefaultXmlSignature2Message();
    mapper.setEnforceReferenceCoverage(true);
    // ... to("xmlsecurity-verify:verify?xmlSignature2Message=#mapper")

    A same-document reference is matched against the document element’s own id — an Id, ID or id attribute, an xml:id attribute, or an attribute a DTD or schema declared to be of type ID. A namespaced id from another convention, notably WS-Security’s wsu:Id, is deliberately not matched by attribute name (matching it across any namespace would let an attacker put a matching id on their wrapper element), so select the signed content with an outputNodeSearch for those.

  • Configure an outputNodeSearch (by element name or XPath), so the output is the signed node rather than the document element, or supply an xmlSignatureChecker that inspects the References against what the route expects.

Leaving all three unset means the verified body may contain content no Reference covered.

Basic Example

The following example shows the basic usage of the component.

  • Java

  • XML

  • YAML

from("direct:enveloping")
    .to("xmlsecurity-sign://enveloping?keyAccessor=#accessor")
    .to("xmlsecurity-verify://enveloping?keySelector=#selector")
    .to("mock:result");
<route>
  <from uri="direct:enveloping"/>
  <to uri="xmlsecurity-sign://enveloping?keyAccessor=#accessor"/>
  <to uri="xmlsecurity-verify://enveloping?keySelector=#selector"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:enveloping
      steps:
        - to:
            uri: xmlsecurity-sign://enveloping
            parameters:
              keyAccessor: "#accessor"
        - to:
            uri: xmlsecurity-verify://enveloping
            parameters:
              keySelector: "#selector"
        - to:
            uri: mock:result

For the signing process, a private key is necessary. You specify a key accessor bean which provides this private key. For the validation, the corresponding public key is necessary; you specify a key selector bean which provides this public key.

The key accessor bean must implement the KeyAccessor interface. The package org.apache.camel.component.xmlsecurity.api contains the default implementation class DefaultKeyAccessor which reads the private key from a Java keystore.

The key selector bean must implement the javax.xml.crypto.KeySelector interface. The package org.apache.camel.component.xmlsecurity.api contains the default implementation class DefaultKeySelector which reads the public key from a keystore.

In the example, the default signature algorithm http://www.w3.org/2000/09/xmldsig#rsa-sha1 is used. You can set the signature algorithm of your choice by the option signatureAlgorithm (see below). The signer endpoint creates an enveloping XML signature. If you want to create an enveloped XML signature, then you must specify the parent element of the Signature element; see option parentLocalName for more details.

For creating detached XML signatures, see sub-chapter "Detached XML Signatures as Siblings of the Signed Elements".

Detached XML Signatures as Siblings of the Signed Elements

You can create detached signatures where the signature is a sibling of the signed element. The following example contains two detached signatures. The first signature is for the element C and the second signature is for element A. The signatures are nested; the second signature is for the element A which also contains the first signature.

Example Detached XML Signatures

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <A ID="IDforA">
        <B>
            <C ID="IDforC">
                <D>dvalue</D>
            </C>
            <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
                Id="_6bf13099-0568-4d76-8649-faf5dcb313c0">
                <ds:SignedInfo>
                    <ds:CanonicalizationMethod
                        Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
                    <ds:SignatureMethod
                        Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
                    <ds:Reference URI="#IDforC">
                        ...
                    </ds:Reference>
                </ds:SignedInfo>
                <ds:SignatureValue>aUDFmiG71</ds:SignatureValue>
            </ds:Signature>
        </B>
    </A>
    <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"Id="_6b02fb8a-30df-42c6-ba25-76eba02c8214">
        <ds:SignedInfo>
            <ds:CanonicalizationMethod
                Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
            <ds:SignatureMethod
                Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
            <ds:Reference URI="#IDforA">
                ...
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>q3tvRoGgc8cMUqUSzP6C21zb7tt04riPnDuk=</ds:SignatureValue>
    </ds:Signature>
<root>

The example shows that you can sign several elements and that for each element a signature is created as sibling. The elements to be signed must have an attribute of type ID. The ID type of the attribute must be defined in the XML schema (see option schemaResourceUri). You specify a list of XPATH expressions pointing to attributes of type ID (see option xpathsToIdAttributes). These attributes determine the elements to be signed. The elements are signed by the same key given by the keyAccessor bean. Elements with higher (i.e. deeper) hierarchy level are signed first. In the example, the element C is signed before the element A.

Java DSL Example

  • Java

  • XML

  • YAML

from("direct:detached")
  .to("xmlsecurity-sign://detached?keyAccessor=#keyAccessorBeant&xpathsToIdAttributes=#xpathsToIdAttributesBean&schemaResourceUri=Test.xsd")
  .to("xmlsecurity-verify://detached?keySelector=#keySelectorBean&schemaResourceUri=org/apache/camel/component/xmlsecurity/Test.xsd")
  .to("mock:result");
<route>
  <from uri="direct:detached"/>
  <to uri="xmlsecurity-sign://detached?keyAccessor=#keyAccessorBeant&amp;xpathsToIdAttributes=#xpathsToIdAttributesBean&amp;schemaResourceUri=Test.xsd"/>
  <to uri="xmlsecurity-verify://detached?keySelector=#keySelectorBean&amp;schemaResourceUri=org/apache/camel/component/xmlsecurity/Test.xsd"/>
  <to uri="mock:result"/>
</route>
- route:
    from:
      uri: direct:detached
      steps:
        - to:
            uri: xmlsecurity-sign://detached
            parameters:
              keyAccessor: "#keyAccessorBeant"
              xpathsToIdAttributes: "#xpathsToIdAttributesBean"
              schemaResourceUri: Test.xsd
        - to:
            uri: xmlsecurity-verify://detached
            parameters:
              keySelector: "#keySelectorBean"
              schemaResourceUri: org/apache/camel/component/xmlsecurity/Test.xsd
        - to:
            uri: mock:result

Spring Example

XML-only: Spring bean configuration for detached XML signature verification
<bean id="xpathsToIdAttributesBean" class="java.util.ArrayList">
      <constructor-arg type="java.util.Collection">
          <list>
              <bean
                  class="org.apache.camel.component.xmlsecurity.api.XmlSignatureHelper"
                  factory-method="getXpathFilter">
                  <constructor-arg type="java.lang.String"
                      value="/ns:root/a/@ID" />
                  <constructor-arg>
                      <map key-type="java.lang.String" value-type="java.lang.String">
                          <entry key="ns" value="http://test" />
                      </map>
                  </constructor-arg>
              </bean>
          </list>
      </constructor-arg>
  </bean>
...
 <from uri="direct:detached" />
      <to
          uri="xmlsecurity-sign://detached?keyAccessor=#keyAccessorBean&amp;xpathsToIdAttributes=#xpathsToIdAttributesBean&amp;schemaResourceUri=Test.xsd" />
      <to
          uri="xmlsecurity-verify://detached?keySelector=#keySelectorBean&amp;schemaResourceUri=Test.xsd" />
      <to uri="mock:result" />

XAdES-BES/EPES for the Signer Endpoint

XML Advanced Electronic Signatures (XAdES) defines extensions to XML Signature. This standard was defined by the European Telecommunication Standards Institute and allows you to create signatures which are compliant to the European Union Directive (1999/93/EC) on a Community framework for electronic signatures. XAdES defines different sets of signature properties which are called signature forms. We support the signature forms Basic Electronic Signature (XAdES-BES) and Explicit Policy Based Electronic Signature (XAdES-EPES) for the Signer Endpoint. The forms Electronic Signature with Validation Data XAdES-T and XAdES-C are not supported.

We support the following properties of the XAdES-EPES form ("?" denotes zero or one occurrence):

Supported XAdES-EPES Properties

<QualifyingProperties Target>
    <SignedProperties>
        <SignedSignatureProperties>
            (SigningTime)?
            (SigningCertificate)?
            (SignaturePolicyIdentifier)
            (SignatureProductionPlace)?
            (SignerRole)?
        </SignedSignatureProperties>
        <SignedDataObjectProperties>
            (DataObjectFormat)?
            (CommitmentTypeIndication)?
        </SignedDataObjectProperties>
    </SignedProperties>
</QualifyingProperties>

The properties of the XAdES-BES form are the same except that the SignaturePolicyIdentifier property is not part of XAdES-BES.

You can configure the XAdES-BES/EPES properties via the bean org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties or org.apache.camel.component.xmlsecurity.api.DefaultXAdESSignatureProperties. XAdESSignatureProperties does support all properties mentioned above except the SigningCertificate property. To get the SigningCertificate property, you must overwrite either the method XAdESSignatureProperties.getSigningCertificate() or XAdESSignatureProperties.getSigningCertificateChain(). The class DefaultXAdESSignatureProperties overwrites the method getSigningCertificate() and allows you to specify the signing certificate via a keystore and alias. The following example shows all parameters you can specify. If you do not need certain parameters, you can just omit them.

XAdES-BES/EPES Example in Java DSL

Java-only: programmatic XAdES signature properties configuration
 Keystore keystore = ... // load a keystore
DefaultKeyAccessor accessor = new DefaultKeyAccessor();
accessor.setKeyStore(keystore);
accessor.setPassword("password");
accessor.setAlias("cert_alias"); // signer key alias

DefaultXAdESSignatureProperties props = new DefaultXAdESSignatureProperties();
props.setNamespace("http://uri.etsi.org/01903/v1.3.2#"); // sets the namespace for the XAdES elements; the namespace is related to the XAdES version, default value is "http://uri.etsi.org/01903/v1.3.2#", other possible values are "http://uri.etsi.org/01903/v1.1.1#" and "http://uri.etsi.org/01903/v1.2.2#"
props.setPrefix("etsi"); // sets the prefix for the XAdES elements, default value is "etsi"

// signing certificate
props.setKeystore(keystore));
props.setAlias("cert_alias"); // specify the alias of the signing certificate in the keystore = signer key alias
props.setDigestAlgorithmForSigningCertificate(DigestMethod.SHA256); // possible values for the algorithm are "http://www.w3.org/2000/09/xmldsig#sha1", "http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmldsig-more#sha384", "http://www.w3.org/2001/04/xmlenc#sha512", default value is "http://www.w3.org/2001/04/xmlenc#sha256"
props.setSigningCertificateURIs(Collections.singletonList("http://certuri"));

// signing time
props.setAddSigningTime(true);

// policy
props.setSignaturePolicy(XAdESSignatureProperties.SIG_POLICY_EXPLICIT_ID);
// also the values XAdESSignatureProperties.SIG_POLICY_NONE ("None"), and XAdESSignatureProperties.SIG_POLICY_IMPLIED ("Implied")are possible, default value is XAdESSignatureProperties.SIG_POLICY_EXPLICIT_ID ("ExplicitId")
// For "None" and "Implied" you must not specify any further policy parameters
props.setSigPolicyId("urn:oid:1.2.840.113549.1.9.16.6.1");
props.setSigPolicyIdQualifier("OIDAsURN"); //allowed values are empty string, "OIDAsURI", "OIDAsURN"; default value is empty string
props.setSigPolicyIdDescription("invoice version 3.1");
props.setSignaturePolicyDigestAlgorithm(DigestMethod.SHA256);// possible values for the algorithm are "http://www.w3.org/2000/09/xmldsig#sha1", http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmldsig-more#sha384", "http://www.w3.org/2001/04/xmlenc#sha512", default value is http://www.w3.org/2001/04/xmlenc#sha256"
props.setSignaturePolicyDigestValue("Ohixl6upD6av8N7pEvDABhEL6hM=");
// you can add  qualifiers for the signature policy either by specifying text or an XML fragment with the root element "SigPolicyQualifier"
props.setSigPolicyQualifiers(Arrays
    .asList(new String[] {
        "<SigPolicyQualifier xmlns=\"http://uri.etsi.org/01903/v1.3.2#\"><SPURI>http://test.com/sig.policy.pdf</SPURI><SPUserNotice><ExplicitText>display text</ExplicitText>"
            + "</SPUserNotice></SigPolicyQualifier>", "category B" }));
props.setSigPolicyIdDocumentationReferences(Arrays.asList(new String[] {"http://test.com/policy.doc.ref1.txt",
    "http://test.com/policy.doc.ref2.txt" }));

// production place
props.setSignatureProductionPlaceCity("Munich");
props.setSignatureProductionPlaceCountryName("Germany");
props.setSignatureProductionPlacePostalCode("80331");
props.setSignatureProductionPlaceStateOrProvince("Bavaria");

//role
// you can add claimed roles either by specifying text or an XML fragment with the root element "ClaimedRole"
props.setSignerClaimedRoles(Arrays.asList(new String[] {"test",
    "<a:ClaimedRole xmlns:a=\"http://uri.etsi.org/01903/v1.3.2#\"><TestRole>TestRole</TestRole></a:ClaimedRole>" }));
props.setSignerCertifiedRoles(Collections.singletonList(new XAdESEncapsulatedPKIData("Ahixl6upD6av8N7pEvDABhEL6hM=",
    "http://uri.etsi.org/01903/v1.2.2#DER", "IdCertifiedRole")));

// data object format
props.setDataObjectFormatDescription("invoice");
props.setDataObjectFormatMimeType("text/xml");
props.setDataObjectFormatIdentifier("urn:oid:1.2.840.113549.1.9.16.6.2");
props.setDataObjectFormatIdentifierQualifier("OIDAsURN"); //allowed values are empty string, "OIDAsURI", "OIDAsURN"; default value is empty string
props.setDataObjectFormatIdentifierDescription("identifier desc");
props.setDataObjectFormatIdentifierDocumentationReferences(Arrays.asList(new String[] {
    "http://test.com/dataobject.format.doc.ref1.txt", "http://test.com/dataobject.format.doc.ref2.txt" }));

//commitment
props.setCommitmentTypeId("urn:oid:1.2.840.113549.1.9.16.6.4");
props.setCommitmentTypeIdQualifier("OIDAsURN"); //allowed values are empty string, "OIDAsURI", "OIDAsURN"; default value is empty string
props.setCommitmentTypeIdDescription("description for commitment type ID");
props.setCommitmentTypeIdDocumentationReferences(Arrays.asList(new String[] {"http://test.com/commitment.ref1.txt",
    "http://test.com/commitment.ref2.txt" }));
// you can specify a commitment type qualifier either by simple text or an XML fragment with root element "CommitmentTypeQualifier"
props.setCommitmentTypeQualifiers(Arrays.asList(new String[] {"commitment qualifier",
    "<c:CommitmentTypeQualifier xmlns:c=\"http://uri.etsi.org/01903/v1.3.2#\"><C>c</C></c:CommitmentTypeQualifier>" }));

beanRegistry.bind("xmlSignatureProperties",props);
beanRegistry.bind("keyAccessorDefault",keyAccessor);

// you must reference the properties bean in the "xmlsecurity" URI
from("direct:xades").to("xmlsecurity-sign://xades?keyAccessor=#keyAccessorDefault&properties=#xmlSignatureProperties")
             .to("mock:result");

XAdES-BES/EPES Example in Spring XML

XML-only: Spring bean configuration for XAdES signature properties
...
<from uri="direct:xades" />
    <to
        uri="xmlsecurity-sign://xades?keyAccessor=#accessorRsa&amp;properties=#xadesProperties" />
    <to uri="mock:result" />
...
<bean id="xadesProperties"
    class="org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties">
    <!-- For more properties see the previous Java DSL example.
         If you want to have a signing certificate then use the bean class DefaultXAdESSignatureProperties (see the previous Java DSL example). -->
    <property name="signaturePolicy" value="ExplicitId" />
    <property name="sigPolicyId" value="http://www.test.com/policy.pdf" />
    <property name="sigPolicyIdDescription" value="factura" />
    <property name="signaturePolicyDigestAlgorithm" value="http://www.w3.org/2000/09/xmldsig#sha1" />
    <property name="signaturePolicyDigestValue" value="Ohixl6upD6av8N7pEvDABhEL1hM=" />
    <property name="signerClaimedRoles" ref="signerClaimedRoles_XMLSigner" />
    <property name="dataObjectFormatDescription" value="Factura electrónica" />
    <property name="dataObjectFormatMimeType" value="text/xml" />
</bean>
<bean class="java.util.ArrayList" id="signerClaimedRoles_XMLSigner">
    <constructor-arg>
        <list>
            <value>Emisor</value>
            <value>&lt;ClaimedRole
                xmlns=&quot;http://uri.etsi.org/01903/v1.3.2#&quot;&gt;&lt;test
                xmlns=&quot;http://test.com/&quot;&gt;test&lt;/test&gt;&lt;/ClaimedRole&gt;</value>
        </list>
    </constructor-arg>
</bean>

Limitations with regard to XAdES version 1.4.2

  • No support for signature form XAdES-T and XAdES-C

  • Only signer part implemented. Verifier part currently not available.

  • No support for the QualifyingPropertiesReference element (see section 6.3.2 of spec).

  • No support for the Transforms element contained in the SignaturePolicyId element contained in the SignaturePolicyIdentifier element

  • No support of the CounterSignature element → no support for the UnsignedProperties element

  • At most one DataObjectFormat element. More than one DataObjectFormat element makes no sense because we have only one data object which is signed (this is the incoming message body to the XML signer endpoint).

  • At most one CommitmentTypeIndication element. More than one CommitmentTypeIndication element makes no sense because we have only one data object which is signed (this is the incoming message body to the XML signer endpoint).

  • A CommitmentTypeIndication element contains always the AllSignedDataObjects element. The ObjectReference element within CommitmentTypeIndication element is not supported.

  • The AllDataObjectsTimeStamp element is not supported

  • The IndividualDataObjectsTimeStamp element is not supported