title | ms.date | ms.technology | dev_langs | helpviewer_keywords | ms.assetid | |
---|---|---|---|---|---|---|
How to: Sign XML Documents with Digital Signatures | dotnet-standard |
| 99692ac1-d8c9-42d7-b1bf-2737b01037e4 |
Signature
> element. The example creates an RSA signing key, adds the key to a secure key container, and then uses the key to digitally sign an XML document. The key can then be retrieved to verify the XML digital signature, or can be used to sign another XML document.'
.Signature
> element) and save it to a new xref:System.Xml.XmlElement object.test.xml
exists in the same directory as the compiled program. You can place the following XML into a file called test.xml
and use it with this example.System.Security.dll
.http://jcp.org/en/jsr/detail?id=105
).http://www.w3.org/TR/xmldsig-core/
). Theresulting signature is represented in XML. An XML Signature can beused to secure your data and provide data integrity, messageauthentication, and signer authentication.JCAprovider
javax.xml.crypto.dsig
javax.xml.crypto.dsig.spec
javax.xml.crypto.dsig.dom
javax.xml.crypto
package contains commonclasses that are used to perform XML cryptographic operations, suchas generating an XML signature or encrypting XML data. Two notableclasses in this package are the KeySelector
class, which allows developers tosupply implementations that locate and optionally validate keysusing the information contained in a KeyInfo
object, and the URIDereferencer
class, which allows developersto create and specify their own URI dereferencingimplementations.javax.xml.crypto.dsig
package includesinterfaces that represent the core elements defined in the W3C XMLdigital signature specification. Of primary significance is theXMLSignature
class, which allows you to signand validate an XML digital signature. Most of the XML signaturestructures or elements are represented by a corresponding interface(except for the KeyInfo
structures,which are included in their own package and are discussed in thenext paragraph). These interfaces include: SignedInfo
, CanonicalizationMethod
, SignatureMethod
, Reference
, Transform
, DigestMethod
, XMLObject
, Manifest
, SignatureProperty
, and SignatureProperties
. The XMLSignatureFactory
class is an abstractfactory that is used to create objects that implement theseinterfaces.javax.xml.crypto.dsig.keyinfo
packagecontains interfaces that represent most of the KeyInfo
structures defined in the W3C XML digitalsignature recommendation, including KeyInfo
, KeyName
, KeyValue
, X509Data
, X509IssuerSerial
, RetrievalMethod
, and PGPData
. The KeyInfoFactory
class is an abstractfactory that is used to create objects that implement theseinterfaces.javax.xml.crypto.dsig.spec
packagecontains interfaces and classes representing input parameters forthe digest, signature, transform, or canonicalization algorithmsused in the processing of XML signatures.javax.xml.crypto.dom
and javax.xml.crypto.dsig.dom
packagescontains DOM-specific classes for the javax.xml.crypto
and javax.xml.crypto.dsig
packages,respectively. Only developers and users who are creating or using aDOM-based XMLSignatureFactory
or KeyInfoFactory
implementation will needto make direct use of these packages.XMLSignatureFactory
and KeyInfoFactory
classes and isresponsible for creating objects and algorithms that parse,generate and validate XML Signatures and KeyInfo
structures. A concrete implementation ofXMLSignatureFactory
must provide support for each of the required algorithms as specified by the W3Crecommendation for XML Signatures. It can optionally support otheralgorithms as defined by the W3C recommendation or otherspecifications.XMLSignatureFactory
and KeyInfoFactory
implementations.XMLSignatureFactory
or KeyInfoFactory
implementation supports a specificXML mechanism type that identifies the XML processing mechanismthat an implementation uses internally to parse and generate XMLsignature and KeyInfo
structures. ThisJSR supports one standard type, DOM. The XML Digital Signatureprovider implementation that is bundled with Java SE supports theDOM mechanism. Support for new standard types, such as JDOM, may beadded in the future.java.security.Signature
and java.security.MessageDigest
, to performcryptographic operations.XMLSignatureFactory
and KeyInfoFactory
classes, JSR 105 supports a serviceprovider interface for transform and canonicalization algorithms.The TransformService
class allows you todevelop and plug in an implementation of a specific transform orcanonicalization algorithm for a particular XML mechanism type. TheTransformService
class uses the standardJCA provider model for registering and loading implementations.Each JSR 105 implementation should usethe TransformService
class to find aprovider that supports transform and canonicalization algorithms inXML Signatures that it is generating or validating.Signature
elementhas been inserted inside the content that it is signing, therebymaking it an enveloped signature. The required SignedInfo
element contains the information that isactually signed:CanonicalizationMethod
element defines the algorithmused to canonicalize the SignedInfo
element before it is signed or validated. Canonicalization is theprocess of converting XML content to a canonical form, to take intoaccount changes that can invalidate a signature over that data.Canonicalization is necessary due to the nature of XML and the wayit is parsed by different processors and intermediaries, which canchange the data such that the signature is no longer valid but thesigned data is still logically equivalent.SignatureMethod
element defines the digitalsignature algorithm used to generate the signature, in this caseDSA with SHA-1.Reference
elements identify the data that is digested. Each Reference
element identifies the data via a URI. Inthis example, the value of the URI is the empty String('), which indicates the root of the document. Theoptional Transforms
element contains alist of one or more Transform
elements,each of which describes a transformation algorithm used totransform the data before it is digested. In this example, there isone Transform
element for the envelopedtransform algorithm. The enveloped transform is required forenveloped signatures so that the signature element itself isremoved before calculating the signature value. The requiredDigestMethod
element defines thealgorithm used to digest the data, in this case SHA1. Finally therequired DigestValue
element containsthe actual base64-encoded digested value.SignatureValue
element contains the base64-encodedsignature value of the signature over the SignedInfo
element.KeyInfo
element contains information about the key that is needed tovalidate the signature:KeyInfo
elementcontains a KeyValue
element, which inturn contains a DSAKeyValue
elementconsisting of the public key needed to validate the signature.KeyInfo
can contain various content suchas X.509 certificates and PGP key identifiers. See the KeyInfo section
of the XML SignatureRecommendation for more information on the different KeyInfo
types.Validate.java
file in the docs/technotes/guides/security/xmldsig
directory.The file on which it operates, envelopedSignature.xml
, is in the samedirectory.docs/technotes/guides/security/xmldsig
directory:$ javac Validate.java
$ java Validate signature.xml
signature.xml
in the current working directory. DocumentBuilderFactory
to parse the XML documentcontaining the Signature. An application obtains the defaultimplementation for DocumentBuilderFactory
by calling the following lineof code:DocumentBuilder
, which is used to parsethe document:Signature
element that we want to validate, sincethere could be more than one in the document. We use the DOM methodDocument.getElementsByTagNameNS
, passingit the XML Signature namespace URI and the tag name of theSignature
element, as shown:Signature
elements in the document. In this example,there is only one Signature
element.XMLValidateContext
instance containing inputparameters for validating the signature. Since we are using DOM, weinstantiate a DOMValidateContext
instance (a subclass of XMLValidateContext
), and pass it two parameters, aKeyValueKeySelector
object and areference to the Signature
element to bevalidated (which is the first entry of the NodeList
we generated earlier):KeyValueKeySelector
is explained in greater detail in UsingKeySelectors.Signature
element into an XMLSignature
object. This process is calledunmarshalling. The Signature
element isunmarshalled using an XMLSignatureFactory
object. An application canobtain a DOM implementation of XMLSignatureFactory
by calling the following line ofcode:unmarshalXMLSignature
method of the factory tounmarshal an XMLSignature
object, andpass it the validation context we created earlier:validate
method onthe XMLSignature
object, and pass it thevalidation context as follows:validate
methodreturns 'true' if the signature validates successfullyaccording to the core validation rules
in the W3C XML Signature Recommendation
,and false otherwise.XMLSignature.validate
method returns false, we cantry to narrow down the cause of the failure. There are two phasesin core XML Signature validation:Signature validation
(thecryptographic verification of the signature)Reference validation
(theverification of the digest of each reference in the signature)KeySelectors
are usedto find and select keys that are needed to validate anXMLSignature. Earlier, when we created a DOMValidateContext
object, we passed a KeySelector
object as the first argument:PublicKey
as the first argument if we already knewwhat key is needed to validate the signature. However, we oftendon't know.KeyValueKeySelector
is a concrete implementation of the abstract KeySelector
class. The KeyValueKeySelector
implementation tries to find anappropriate validation key using the data contained in KeyValue
elements of the KeyInfo
element of an XMLSignature
. It does not determine if the key istrusted. This is a very simple KeySelector
implementation, designed forillustration rather than real-world usage. A more practical exampleof a KeySelector
is one that searches aKeyStore
for trusted keys that matchX509Data
information (for example,X509SubjectName
, X509IssuerSerial
, X509SKI
, or X509Certificate
elements) contained in aKeyInfo
.KeyValueKeySelector
is as follows:GenEnveloped.java
file in the docs/technotes/guides/security/xmldsig
directory. Thefile on which it operates, envelope.xml
,is in the same directory. It generates the file envelopedSignature.xml.
docs/technotes/guides/security/xmldsig
directory:$ javac GenEnveloped.java
$ java GenEnveloped envelope.xmlenvelopedSignature.xml
envelopedSignature.xml
in the current workingdirectory.http://www.w3.org/TR/xmldsig-core/
for moreinformation.DocumentBuilderFactory
to parse the XML documentthat we want to sign. An application obtains the defaultimplementation for DocumentBuilderFactory
by calling the following lineof code:DocumentBuilder
, which is used to parsethe document:KeyPairGenerator
. In this example, we will create aDSA KeyPair
with a length of 2048 bytes:KeyStore
filewith an associated public key certificate.XMLSignContext
containing input parameters forgenerating the signature. Since we are using DOM, we instantiate aDOMSignContext
(a subclass ofXMLSignContext
), and pass it twoparameters, the private key that will be used to sign the documentand the root of the document to be signed:Signature
element into an XMLSignature
object. These objects are all createdand assembled using an XMLSignatureFactory
object. An application obtains aDOM implementation of XMLSignatureFactory
by calling the following line ofcode:XMLSignature
object as shown below. We create a Reference
object, passing to it the following:Transform
, the envelopedTransform
, which is required forenveloped signatures so that the signature itself is removed beforecalculating the signature valueSignedInfo
object, which is the object that isactually signed, as shown below. When creating the SignedInfo
, we pass as parameters:CanonicalizationMethod
(we useinclusive and preserve comments)References
(in this case,only one)KeyInfo
object, which contains information thatenables the recipient to find the key needed to validate thesignature. In this example, we add a KeyValue
object containing the public key. To createKeyInfo
and its various subtypes, we usea KeyInfoFactory
object, which can beobtained by invoking the getKeyInfoFactory
method of the XMLSignatureFactory
, as follows:KeyInfoFactory
to create the KeyValue
object and add it to a KeyInfo
object:XMLSignature
object, passing as parameters theSignedInfo
and KeyInfo
objects that we created earlier:sign
method on theXMLSignature
object, and pass it thesigning context as follows: