### Install SignXML Package Source: https://context7.com/xml-security/signxml/llms.txt Installs the SignXML library using pip. This is the first step to using the library for XML signing and verification. ```bash pip install signxml ``` -------------------------------- ### XML Structure Example Source: https://github.com/xml-security/signxml/blob/main/test/interop/merlin-xmldsig-twenty-three/signature-c14n-12.txt This snippet demonstrates a basic XML structure with namespaces and attributes, commonly used in applications requiring structured data exchange. ```xml foo bar bar ``` -------------------------------- ### Sign SAML Assertion with Schema-Compliant Placement Source: https://context7.com/xml-security/signxml/llms.txt Signs a SAML assertion while ensuring the signature is placed according to schema requirements. This example demonstrates how to create a SAML assertion string, parse it into an etree object, and then use XMLSigner to apply a signature, placing it at a placeholder ID. ```python from lxml import etree from signxml import XMLSigner saml_assertion = """ https://idp.example.com user@example.com """ root = etree.fromstring(saml_assertion) signed_assertion = XMLSigner().sign(root, key=key, cert=cert) ``` -------------------------------- ### Construct Detached XML Signatures with SignXML Source: https://github.com/xml-security/signxml/blob/main/docs/index.md This example demonstrates how to create a detached XML signature using SignXML. By specifying `method=signxml.methods.detached`, the signature is created separately from the data. The `reference_uri` can be customized, and for verification of detached signatures referring to external entities, a callable `uri_resolver` can be provided to `XMLVerifier().verify()`. ```python from lxml import etree from signxml import XMLSigner, XMLVerifier # Assuming root, key, and cert are defined as in the basic example signed_root = XMLSigner(method=signxml.methods.detached).sign(root, key=key, cert=cert) verified_data = XMLVerifier().verify(signed_root).signed_xml ``` -------------------------------- ### verify(data, x509_cert=None, cert_subject_name=None, cert_resolver=None, ca_pem_file=None, hmac_key=None, validate_schema=True, parser=None, uri_resolver=None, id_attribute=None, expect_config=SignatureConfiguration(require_x509=True, location='.//', expect_references=1, signature_methods=frozenset({SignatureMethod.HMAC_SHA512, SignatureMethod.SHA3_256_RSA_MGF1, SignatureMethod.ECDSA_SHA384, SignatureMethod.SHA3_224_RSA_MGF1, SignatureMethod.ECDSA_SHA512, SignatureMethod.RSA_SHA384, SignatureMethod.SHA256_RSA_MGF1, SignatureMethod.DSA_SHA256, SignatureMethod.HMAC_SHA224, SignatureMethod.ECDSA_SHA3_256, SignatureMethod.RSA_SHA224, SignatureMethod.SHA3_512_RSA_MGF1, SignatureMethod.SHA3_384_RSA_MGF1, SignatureMethod.ECDSA_SHA3_256, SignatureMethod.RSA_SHA256, SignatureMethod.HMAC_SHA384, SignatureMethod.SHA384_RSA_MGF1, SignatureMethod.RSA_SHA512, SignatureMethod.HMAC_SHA256, SignatureMethod.SHA512_RSA_MGF1, SignatureMethod.ECDSA_SHA224, SignatureMethod.ECDSA_SHA256, SignatureMethod.ECDSA_SHA3_384, SignatureMethod.ECDSA_SHA3_224, SignatureMethod.RSA_SHA224}), digest_algorithms=frozenset({DigestAlgorithm.SHA256, DigestAlgorithm.SHA3_384, DigestAlgorithm.SHA3_224, DigestAlgorithm.SHA3_256, DigestAlgorithm.SHA3_512, DigestAlgorithm.SHA384, DigestAlgorithm.SHA512, DigestAlgorithm.SHA224}), ignore_ambiguous_key_info=False, default_reference_c14n_method=CanonicalizationMethod.CANONICAL_XML_1_1), **deprecated_kwargs) Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Verifies an XML signature. This function checks the integrity and authenticity of the XML data by validating its signature. It can use X.509 certificates or HMAC keys for verification. By default, it requires a valid X.509 certificate. ```APIDOC ## POST /xml-security/signxml/verify ### Description Verifies the XML signature supplied in the data and returns a list of [`VerifyResult`](#signxml.VerifyResult) data structures representing the data signed by the signature, or raises an exception if the signature is not valid. By default, this requires the signature to be generated using a valid X.509 certificate. To enable other means of signature validation, set `expect_config` to a configuration with the **require_x509** parameter set to False. ### Method POST ### Endpoint /xml-security/signxml/verify ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (String, file-like object, or XML ElementTree Element API compatible object) - Required - Signature data to verify - **x509_cert** (str or Certificate or None) - Optional - A trusted external X.509 certificate, given as a PEM-formatted string or cryptography.x509.Certificate object, to use for verification. Overrides any X.509 certificate information supplied by the signature. If left set to `None`, requires that the signature supply a valid X.509 certificate chain that validates against the known certificate authorities. Implies **require_x509=True**. - **cert_subject_name** (str or None) - Optional - Subject Common Name to check the signing X.509 certificate against. Implies **require_x509=True**. - **cert_resolver** (Callable or None) - Optional - Function to use to resolve trusted X.509 certificates when X509IssuerSerial and X509Digest references are found in the signature. The function is called with the keyword arguments `x509_issuer_name`, `x509_serial_number` and `x509_digest`, and is expected to return an iterable of one or more strings containing a PEM-formatted certificate and a chain of intermediate certificates, if needed. Implies **require_x509=True**. - **ca_pem_file** (str or bytes or None) - Optional - Filename of a PEM file containing certificate authority information to use when verifying certificate-based signatures. - **hmac_key** (bytes or None) - Optional - If using HMAC, a string containing the shared secret. - **validate_schema** (bool) - Optional - Whether to validate **data** against the XML Signature schema. Defaults to True. - **parser** (lxml.etree.XMLParser compatible parser) - Optional - Custom XML parser instance to use when parsing **data**. The default parser arguments used by SignXML are: `resolve_entities=False`. - **uri_resolver** (Callable or None) - Optional - Function to use to resolve reference URIs that are not empty and don’t start with “#” (such references are only expected in detached signatures; if you don’t expect such signatures, leave this unset to prevent them from validating). The function is called with a single string argument containing the URI to be resolved, and is expected to return a [`lxml.etree._Element`](https://lxml.de/apidoc/lxml.etree.html#lxml.etree._Element) node or bytes. - **id_attribute** (str or None) - Optional - The attribute name to use for identifying elements within the XML document. - **expect_config** (SignatureConfiguration) - Optional - Configuration object specifying expectations for the signature, such as required certificate types and signature methods. ### Request Example ```json { "data": "...", "x509_cert": "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----", "hmac_key": "your_secret_key" } ``` ### Response #### Success Response (200) - **VerifyResult** (list) - A list of VerifyResult objects, each representing a signed data element. #### Response Example ```json { "signed_data": [ { "element": "...", "digest": "..." }, { "element": "...", "digest": "..." } ] } ``` ``` -------------------------------- ### Define XML Digital Signature Reference Elements Source: https://github.com/xml-security/signxml/blob/main/test/interop/merlin-xmldsig-twenty-three/signature-c14n-17.txt Examples of Reference elements used in XML Digital Signatures. These elements define the data to be signed, including digest algorithms, transformation rules, and URI-based resource identification. ```xml yamSIokKmjA3hB/s3Fu07wDO3vM= 419CYgyTWOTGYGBhzieWklNf7Bk= 7/9fR+NIDz9owc1Lfsxu1JBr8uo= ``` -------------------------------- ### Sign and Verify XAdES Signatures in Python Source: https://github.com/xml-security/signxml/blob/main/README.rst Demonstrates how to configure XAdES signing parameters, sign an XML document using a private key and certificate, and subsequently verify the signature while accessing parsed XAdES properties. ```python from signxml import DigestAlgorithm from signxml.xades import (XAdESSigner, XAdESVerifier, XAdESVerifyResult, XAdESSignaturePolicy, XAdESDataObjectFormat) signature_policy = XAdESSignaturePolicy( Identifier="MyPolicyIdentifier", Description="Hello XAdES", DigestMethod=DigestAlgorithm.SHA256, DigestValue="Ohixl6upD6av8N7pEvDABhEL6hM=", ) data_object_format = XAdESDataObjectFormat( Description="My XAdES signature", MimeType="text/xml", ) signer = XAdESSigner( signature_policy=signature_policy, claimed_roles=["signer"], data_object_format=data_object_format, c14n_algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315", ) signed_doc = signer.sign(doc, key=private_key, cert=certificate) verifier = XAdESVerifier() verify_results = verifier.verify( signed_doc, x509_cert=certificate, expect_references=3, expect_signature_policy=signature_policy ) for verify_result in verify_results: if isinstance(verify_result, XAdESVerifyResult): verify_result.signed_properties ``` -------------------------------- ### Implement XAdES Signing and Verification Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Shows how to create a XAdES signature with specific policies and data formats, and how to verify such signatures. It includes setting up signature policies and accessing signed properties after verification. ```python from signxml import DigestAlgorithm from signxml.xades import (XAdESSigner, XAdESVerifier, XAdESVerifyResult, XAdESSignaturePolicy, XAdESDataObjectFormat) signature_policy = XAdESSignaturePolicy( Identifier="MyPolicyIdentifier", Description="Hello XAdES", DigestMethod=DigestAlgorithm.SHA256, DigestValue="Ohixl6upD6av8N7pEvDABhEL6hM=", ) data_object_format = XAdESDataObjectFormat( Description="My XAdES signature", MimeType="text/xml", ) signer = XAdESSigner( signature_policy=signature_policy, claimed_roles=["signer"], data_object_format=data_object_format, c14n_algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315", ) signed_doc = signer.sign(doc, key=private_key, cert=certificate) verifier = XAdESVerifier() verify_results = verifier.verify( signed_doc, x509_cert=certificate, expect_references=3, expect_signature_policy=signature_policy ) for verify_result in verify_results: if isinstance(verify_result, XAdESVerifyResult): verify_result.signed_properties ``` -------------------------------- ### Initialize XMLSigner in Python Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Demonstrates the initialization of the XMLSigner class, which is used for creating XML signatures. It allows configuration of signature construction method, signature algorithm, digest algorithm, and canonicalization algorithm. ```python from signxml import XMLSigner signer = XMLSigner( method=SignatureConstructionMethod.enveloped, signature_algorithm=SignatureMethod.RSA_SHA256, digest_algorithm=DigestAlgorithm.SHA256, c14n_algorithm=CanonicalizationMethod.CANONICAL_XML_1_1 ) ``` -------------------------------- ### Initialize XAdESSigner in Python Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Demonstrates how to create an instance of the XAdESSigner class in Python. This class is used for signing XML documents with XAdES metadata. It supports optional parameters for signature policy, claimed roles, and data object format. ```python from signxml import XAdESSigner # Basic initialization signer = XAdESSigner() # With optional parameters signer_with_policy = XAdESSigner(signature_policy="policy_string", claimed_roles=["role1", "role2"]) ``` -------------------------------- ### Verify XML Signature with Location Configuration Source: https://github.com/xml-security/signxml/blob/main/README.rst Demonstrates how to configure the expected location for an XML signature during verification to ensure document integrity. ```python from signxml import XMLVerifier, SignatureConfiguration config = SignatureConfiguration(location="./") XMLVerifier(...).verify(..., expect_config=config) ``` -------------------------------- ### Sign Multiple XML Elements with SignatureReference Source: https://context7.com/xml-security/signxml/llms.txt Demonstrates how to sign multiple distinct elements within an XML document using individual SignatureReference objects with specific canonicalization methods. ```python from signxml import XMLSigner, SignatureReference, CanonicalizationMethod doc = etree.fromstring(""" Content """) references = [ SignatureReference( URI="#header", c14n_method=CanonicalizationMethod.EXCLUSIVE_XML_CANONICALIZATION_1_0 ), SignatureReference( URI="#body", c14n_method=CanonicalizationMethod.CANONICAL_XML_1_1, inclusive_ns_prefixes=["soap", "wsse"] ) ] signer = XMLSigner(method=SignatureConstructionMethod.detached) signed_doc = signer.sign(doc, key=key, cert=cert, reference_uri=references) ``` -------------------------------- ### Customize KeyInfo and Signature Annotations Source: https://context7.com/xml-security/signxml/llms.txt Demonstrates how to inject custom KeyInfo elements into the signature block and use signature annotators to add custom metadata to the XML signature. ```python from signxml import XMLSigner def my_annotator(sig_root, signing_settings): custom_element = etree.SubElement(sig_root, "CustomData") custom_element.text = "Additional signature metadata" signer = XMLSigner() signer.signature_annotators.append(my_annotator) signed_doc = signer.sign(root, key=key, cert=cert) ``` -------------------------------- ### Sign and Verify XML Documents with SignXML Source: https://github.com/xml-security/signxml/blob/main/README.rst Demonstrates the basic workflow for signing an XML element using a private key and certificate, then verifying the resulting signature. It utilizes the lxml library for XML parsing and the SignXML library for cryptographic operations. ```python from lxml import etree from signxml import XMLSigner, XMLVerifier data_to_sign = "" cert = open("cert.pem").read() key = open("privkey.pem").read() root = etree.fromstring(data_to_sign) signed_root = XMLSigner().sign(root, key=key, cert=cert) verified_data = XMLVerifier().verify(signed_root).signed_xml ``` -------------------------------- ### Verify XML Signature with SignXML Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Demonstrates how to verify an XML signature using the XMLVerifier class from the SignXML library. It shows how to instantiate the verifier and call the verify method, returning a VerifyResult object. ```python from signxml import XMLVerifier verifier = XMLVerifier() verification_result = verifier.verify(input_data) ``` -------------------------------- ### POST /verify Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Verifies an XML signature against provided configuration settings and returns the verification result. ```APIDOC ## POST /verify ### Description Verifies an XML signature based on the provided input data and signature configuration. It ensures the signature meets specified security requirements and returns a structured result. ### Method POST ### Endpoint /verify ### Parameters #### Request Body - **id_attribute** (str) - Optional - Name of the attribute whose value URI refers to. Defaults to 'Id' then 'ID'. - **expect_config** (SignatureConfiguration) - Optional - Object defining expected properties of the verified signature. ### Response #### Success Response (200) - **signed_data** (bytes) - The binary data as it was signed. - **signed_xml** (_Element) - The signed data parsed as XML. - **signature_xml** (_Element) - The signature element parsed as XML. - **signature_key** (bytes) - The cryptographic key used for verification. #### Response Example { "signed_data": "b'...'", "signed_xml": "...", "signature_xml": "...", "signature_key": "PEM_ENCODED_KEY" } ``` -------------------------------- ### Configure Signature Algorithms and Verification Security Source: https://context7.com/xml-security/signxml/llms.txt Lists available cryptographic algorithms for signatures, digests, and canonicalization. Shows how to use SignatureConfiguration to enforce strict security policies during verification. ```python from signxml import ( SignatureMethod, DigestAlgorithm, CanonicalizationMethod, SignatureConfiguration ) strict_config = SignatureConfiguration( signature_methods=frozenset([SignatureMethod.RSA_SHA256]), digest_algorithms=frozenset([DigestAlgorithm.SHA256]), require_x509=True, expect_references=1 ) result = XMLVerifier().verify(signed_doc, expect_config=strict_config) ``` -------------------------------- ### Perform HMAC XML Signing and Verification Source: https://context7.com/xml-security/signxml/llms.txt Shows how to sign and verify XML documents using symmetric HMAC keys instead of asymmetric X.509 certificates. ```python from signxml import XMLSigner, XMLVerifier, SignatureMethod, SignatureConfiguration hmac_key = b"your-shared-secret-key-at-least-32-bytes-long" signer = XMLSigner(signature_algorithm=SignatureMethod.HMAC_SHA256) signed_doc = signer.sign(root, key=hmac_key) config = SignatureConfiguration(require_x509=False) result = XMLVerifier().verify( signed_doc, hmac_key=hmac_key, expect_config=config ) ``` -------------------------------- ### Configure Namespace Prefixes for XML Signatures Source: https://github.com/xml-security/signxml/blob/main/README.rst Explains how to customize the namespace prefix map in XMLSigner to meet specific application requirements for canonicalization. ```python signer = signxml.XMLSigner(...) signer.namespaces = {None: signxml.namespaces.ds} signed_root = signer.sign(...) ``` -------------------------------- ### Sign XML Documents with XMLSigner Source: https://context7.com/xml-security/signxml/llms.txt Demonstrates how to use the XMLSigner class to create digital signatures for XML data. It covers basic enveloped signatures, custom algorithms, detached and enveloping signatures, certificate chains, and namespace prefix configuration. The library uses lxml for XML parsing and supports various cryptographic algorithms. ```python from lxml import etree from signxml import XMLSigner, SignatureConstructionMethod, SignatureMethod, DigestAlgorithm # Generate test certificate and key for examples # openssl req -x509 -nodes -subj "/CN=test" -days 365 -newkey rsa:2048 -keyout privkey.pem -out cert.pem # Basic enveloped signature (default) data_to_sign = "Widget5" cert = open("cert.pem").read() key = open("privkey.pem").read() root = etree.fromstring(data_to_sign) signer = XMLSigner() signed_root = signer.sign(root, key=key, cert=cert) # Output: signed XML with embedded signature print(etree.tostring(signed_root, pretty_print=True).decode()) # Sign with custom algorithms signer = XMLSigner( method=SignatureConstructionMethod.enveloped, signature_algorithm=SignatureMethod.RSA_SHA512, digest_algorithm=DigestAlgorithm.SHA384 ) signed_root = signer.sign(root, key=key, cert=cert) # Detached signature (signature separate from content) doc = etree.fromstring('Important Data') signer = XMLSigner(method=SignatureConstructionMethod.detached) signed_doc = signer.sign(doc, key=key, cert=cert, reference_uri="#doc1") # Enveloping signature (content wrapped inside signature) signer = XMLSigner(method=SignatureConstructionMethod.enveloping) signed_doc = signer.sign(doc, key=key, cert=cert) # Sign with certificate chain ca_cert = open("ca-cert.pem").read() cert_chain = [cert, ca_cert] signed_root = XMLSigner().sign(root, key=key, cert=cert_chain) # Custom namespace prefix (for SAML compatibility) signer = XMLSigner() signer.namespaces = {None: "http://www.w3.org/2000/09/xmldsig#"} signed_root = signer.sign(root, key=key, cert=cert) ``` -------------------------------- ### Verify SAML Assertions using SignXML Source: https://github.com/xml-security/signxml/blob/main/README.rst Shows how to extract an X.509 certificate from SAML metadata and verify a base64-encoded SAML assertion. This is a common pattern for securing SAML-based authentication flows. ```python from lxml import etree from base64 import b64decode from signxml import XMLVerifier with open("metadata.xml", "rb") as fh: cert = etree.parse(fh).find("//ds:X509Certificate").text assertion_data = XMLVerifier().verify(b64decode(assertion_body), x509_cert=cert).signed_xml ``` -------------------------------- ### Configure XML Namespace Declaration Handling Source: https://github.com/xml-security/signxml/blob/main/docs/changelog.md Demonstrates how to enable or disable the excision of empty xmlns declarations during the XML signing and verification processes. This configuration allows users to control whether empty namespace attributes are stripped from the output. ```python signer = XMLSigner() signer.excise_empty_xmlns_declarations = True signer.sign(...) verifier = XMLVerifier() verifier.excise_empty_xmlns_declarations = True verifier.verify(...) ``` -------------------------------- ### XML Signing Configuration Options Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Configuration options for signing XML documents. ```APIDOC ## XML Signing Configuration This section details the configuration options available for signing XML documents using the signxml library. ### Parameters #### expect_references - **Type**: int or bool - **Default**: 1 - **Description**: Number of references to expect in the signature. If not 1, an array of VerifyResults is returned. If set to a non-integer, any number of references is accepted; otherwise, a mismatch raises an error. #### signature_methods - **Type**: FrozenSet[SignatureMethod] - **Default**: A predefined set of common signature methods including DSA, ECDSA, HMAC, and RSA variants. - **Description**: Set of acceptable signature methods (signature algorithms). Signatures generated using algorithms not in this set will fail verification. It is recommended to restrict this set to only methods expected by your application. #### digest_algorithms - **Type**: FrozenSet[DigestAlgorithm] - **Default**: A predefined set of common digest algorithms including SHA224, SHA256, SHA384, SHA512, and their SHA3 variants. - **Description**: Set of acceptable digest algorithms. Signatures or reference transforms generated using algorithms not in this set will cause verification to fail. It is recommended to restrict this set to only methods expected by your application. #### ignore_ambiguous_key_info - **Type**: bool - **Default**: False - **Description**: Ignore the presence of a KeyValue element when X509Data is present. If `False`, SignXML compares KeyValue against the X.509 certificate and raises `InvalidInput` on mismatch. Set to `True` to bypass this check and validate using X509Data only. #### default_reference_c14n_method - **Type**: CanonicalizationMethod - **Default**: 'http://www.w3.org/2006/12/xml-c14n11' - **Description**: The default canonicalization method for referenced data structures if not specified in the Transforms element. Useful for validating signatures where the canonicalization method is fixed and not included in Transforms. ### Enumerations #### DigestAlgorithm An enumeration of digest algorithms supported by SignXML. - **SHA224**: 'http://www.w3.org/2001/04/xmldsig-more#sha224' - **SHA384**: 'http://www.w3.org/2001/04/xmldsig-more#sha384' - **SHA256**: 'http://www.w3.org/2001/04/xmlenc#sha256' - **SHA512**: 'http://www.w3.org/2001/04/xmlenc#sha512' - **SHA3_224**: 'http://www.w3.org/2007/05/xmldsig-more#sha3-224' - **SHA3_256**: 'http://www.w3.org/2007/05/xmldsig-more#sha3-256' - **SHA3_384**: 'http://www.w3.org/2007/05/xmldsig-more#sha3-384' - **SHA3_512**: 'http://www.w3.org/2007/05/xmldsig-more#sha3-512' - **SHA1**: 'http://www.w3.org/2000/09/xmldsig#sha1' (Deprecated) #### SignatureMethod An enumeration of signature methods (signature algorithms) supported by SignXML. (Specific methods are listed in the original text, including DSA, ECDSA, HMAC, and RSA variants with different hash functions.) ``` -------------------------------- ### Configure XML Signature Verification in SignXML Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Illustrates the use of SignatureConfiguration to define expected properties of an XML signature during verification. This includes settings for X.509 requirements, signature location, and allowed signature/digest methods. ```python from signxml import XMLVerifier, SignatureConfiguration, SignatureMethod, DigestAlgorithm, CanonicalizationMethod config = SignatureConfiguration( require_x509=True, location='.//ds:Signature', expect_references=1, signature_methods=frozenset({SignatureMethod.RSA_SHA256}), digest_algorithms=frozenset({DigestAlgorithm.SHA256}), ignore_ambiguous_key_info=False, default_reference_c14n_method=CanonicalizationMethod.CANONICAL_XML_1_1 ) verifier = XMLVerifier(expect_config=config) verification_result = verifier.verify(input_data) ``` -------------------------------- ### Signing XML Data with signxml Source: https://github.com/xml-security/signxml/blob/main/docs/index.md This snippet demonstrates how to invoke the sign function to generate a digital signature for an XML element. It requires the data to be signed and a private key, with optional parameters for certificates and custom key information. ```python from signxml import sign from lxml import etree data = etree.fromstring("data") key = open("private.pem", "rb").read() signed_xml = sign(data, key=key) ``` -------------------------------- ### XML Signature Verification with SHA1 Deprecation Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Demonstrates how to configure an XML verifier to handle deprecated SHA1-based signatures. SHA1 algorithms are not secure for digital signatures and are included for legacy compatibility, often disabled by default. ```python XMLVerifier().verify( expect_config=SignatureConfiguration( signature_methods=..., digest_algorithms=... ) ) ``` -------------------------------- ### XML Verification API Source: https://context7.com/xml-security/signxml/llms.txt Demonstrates various methods for verifying XML signatures using the XMLVerifier class. ```APIDOC ## Verify HMAC signatures ### Description Verifies an XML document signed with an HMAC signature. ### Method POST (implied by verification process) ### Endpoint /xml-security/verify ### Parameters #### Request Body - **signed_doc** (bytes) - The signed XML document. - **hmac_key** (bytes) - The HMAC shared secret key. - **expect_config** (SignatureConfiguration) - Configuration for expected signature properties. ### Request Example ```python hmac_key = b"shared-secret-key-for-hmac" config = SignatureConfiguration(require_x509=False) result = XMLVerifier().verify(signed_doc, hmac_key=hmac_key, expect_config=config) ``` ## Verify detached signature with URI resolver ### Description Verifies a detached XML signature using a custom URI resolver to fetch external resources. ### Method POST (implied by verification process) ### Endpoint /xml-security/verify-detached ### Parameters #### Request Body - **detached_signature** (bytes) - The detached signature to verify. - **uri_resolver** (function) - A function to resolve URIs. ### Request Example ```python def uri_resolver(uri): if uri == "http://example.com/document.xml": return etree.parse("document.xml").getroot() raise ValueError(f"Unknown URI: {uri}") result = XMLVerifier().verify(detached_signature, uri_resolver=uri_resolver) ``` ## Multiple references verification ### Description Verifies an XML document with multiple signed references, checking against an expected number of references. ### Method POST (implied by verification process) ### Endpoint /xml-security/verify-multiple ### Parameters #### Request Body - **signed_doc** (bytes) - The signed XML document. - **expect_config** (SignatureConfiguration) - Configuration specifying the expected number of references. ### Request Example ```python config = SignatureConfiguration(expect_references=3) results = XMLVerifier().verify(signed_doc, expect_config=config) for result in results: print(f"Reference verified: {result.signed_xml.tag}") ``` ``` -------------------------------- ### Create Basic XAdES Signature Source: https://context7.com/xml-security/signxml/llms.txt Creates a basic XAdES (XML Advanced Electronic Signatures) compliant signature for an XML document. This involves initializing the XAdESSigner and calling its sign method with the document, private key, and certificate. The output is a signed XML document adhering to XAdES standards. ```python from signxml.xades import XAdESSigner from lxml import etree doc = etree.fromstring("1000.00") signer = XAdESSigner() signed_doc = signer.sign(doc, key=key, cert=cert) ``` -------------------------------- ### Create XAdES Signature with Claimed Roles Source: https://context7.com/xml-security/signxml/llms.txt Creates an XAdES signature where the signer claims specific roles, such as 'signer' or 'approver'. This is configured during the XAdESSigner initialization by providing a list of role strings. This metadata can be used to indicate the authority or capacity in which the signature was applied. ```python from signxml.xades import XAdESSigner from lxml import etree signer = XAdESSigner( claimed_roles=["signer", "approver", "legal-representative"] ) doc = etree.fromstring("1000.00") signed_doc = signer.sign(doc, key=key, cert=cert) ``` -------------------------------- ### Generate and Verify Detached XML Signatures Source: https://github.com/xml-security/signxml/blob/main/README.rst Shows how to specify the signature method as detached when signing XML and how to verify the resulting structure. ```python signed_root = XMLSigner(method=signxml.methods.detached).sign(root, key=key, cert=cert) verified_data = XMLVerifier().verify(signed_root).signed_xml ``` -------------------------------- ### XML Signature Construction Methods in SignXML Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Lists the supported signature construction methods in SignXML, defining how the digital signature is applied to the XML content. This includes enveloped and enveloping signature types. ```python class SignatureConstructionMethod(value): enveloped = 'http://www.w3.org/2000/09/xmldsig#enveloped-signature' enveloping = 'enveloping-signature' ``` -------------------------------- ### Verify XML Signature with Multiple References Source: https://context7.com/xml-security/signxml/llms.txt Verifies an XML document expected to contain multiple signed references. The SignatureConfiguration can specify the exact number of references that must be present. The verification process iterates through each verified reference, providing details about the signed XML element. ```python from signxml import XMLVerifier, SignatureConfiguration config = SignatureConfiguration(expect_references=3) results = XMLVerifier().verify(signed_doc, expect_config=config) for result in results: print(f"Reference verified: {result.signed_xml.tag}") ``` -------------------------------- ### Verify XAdES Signature with Custom Configuration Source: https://context7.com/xml-security/signxml/llms.txt Verifies an XAdES signature using a custom configuration, allowing for specific validation rules. For instance, the number of expected references can be adjusted. This provides flexibility in tailoring the verification process to different security contexts or requirements. ```python from signxml.xades import XAdESVerifier, XAdESSignatureConfiguration config = XAdESSignatureConfiguration( expect_references=4 # Custom number of references ) verify_results = XAdESVerifier().verify( signed_doc, x509_cert=cert, expect_config=config ) ``` -------------------------------- ### Initialize XML Signature Verifier Source: https://github.com/xml-security/signxml/blob/main/docs/index.md The XMLVerifier class provides methods to verify XML signatures. It supports configuring expected digest and signature algorithms, as well as setting up certificate chain verification. ```python from signxml import XMLVerifier verifier = XMLVerifier() verifier.check_digest_alg_expected("sha256") verifier.check_signature_alg_expected("rsa-sha256") verifier.get_cert_chain_verifier(ca_pem_file="ca.pem") ``` -------------------------------- ### Signature Methods Reference Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Lists the supported RSA, ECDSA, DSA, HMAC, and MGF1-based signature algorithms used for XML digital signatures. ```APIDOC ## Signature Methods ### Description Supported signature algorithms for XML digital signatures. Includes RSA, ECDSA, DSA, and HMAC variants. Note that SHA1-based algorithms are deprecated and disabled by default. ### Supported Identifiers - **RSA_SHA256**: http://www.w3.org/2001/04/xmldsig-more#rsa-sha256 - **ECDSA_SHA256**: http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256 - **HMAC_SHA256**: http://www.w3.org/2001/04/xmldsig-more#hmac-sha256 - **SHA256_RSA_MGF1**: http://www.w3.org/2007/05/xmldsig-more#sha256-rsa-MGF1 ### Legacy Support SHA1-based algorithms are included for legacy compatibility only. To enable them, configure the `XMLVerifier` with `SignatureConfiguration`. ``` -------------------------------- ### Registering a Custom Signature Annotator Source: https://github.com/xml-security/signxml/blob/main/docs/index.md This snippet demonstrates how to define a custom annotator function and append it to the XMLSigner instance. The annotator receives the signature root and signing settings, allowing for dynamic injection of custom nodes into the XML signature. ```python def my_annotator(sig_root, signing_settings): # Custom logic to modify sig_root sig_root.append(my_custom_node) signer = XMLSigner() signer.signature_annotators.append(my_annotator) signed = signer.sign(data, ...) ``` -------------------------------- ### Verify XML Signatures with XMLVerifier Source: https://context7.com/xml-security/signxml/llms.txt Illustrates how to use the XMLVerifier class to validate XML signatures. It covers basic verification, using pre-shared certificates, custom CA verification, subject name validation, and applying custom signature configurations. The verifier checks cryptographic integrity and can validate X.509 certificate chains. ```python from signxml import XMLVerifier, SignatureConfiguration, VerifyResult from signxml.exceptions import InvalidSignature, InvalidCertificate, InvalidDigest # Basic verification with embedded certificate try: result = XMLVerifier().verify(signed_root) verified_data = result.signed_xml # The XML that was actually signed print(f"Signature valid. Signed content: {etree.tostring(verified_data).decode()}") except InvalidSignature as e: print(f"Signature verification failed: {e}") # Verify with pre-shared certificate (recommended for production) trusted_cert = open("trusted-cert.pem").read() result = XMLVerifier().verify(signed_root, x509_cert=trusted_cert) # Verify with custom CA result = XMLVerifier().verify(signed_root, ca_pem_file="ca-bundle.pem") # Verify with subject name validation result = XMLVerifier().verify( signed_root, cert_subject_name="example.com" ) # Custom signature configuration config = SignatureConfiguration( require_x509=True, location="./", # Signature is the root element expect_references=1, signature_methods=frozenset([SignatureMethod.RSA_SHA256, SignatureMethod.RSA_SHA512]), digest_algorithms=frozenset([DigestAlgorithm.SHA256, DigestAlgorithm.SHA512]) ) result = XMLVerifier().verify(signed_root, expect_config=config) # Access verification result details verify_result: VerifyResult = XMLVerifier().verify(signed_root, x509_cert=trusted_cert) print(f"Signed data (bytes): {verify_result.signed_data}") print(f"Signed XML: {verify_result.signed_xml}") print(f"Signature XML: {verify_result.signature_xml}") print(f"Signature key (PEM): {verify_result.signature_key}") ``` -------------------------------- ### Handling Inclusive Namespace Prefixes for Canonicalization Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Specifies a list of XML namespace prefixes to be preserved during the canonicalization process for XML signatures. This is crucial for ensuring consistent signature generation across different environments. It can be applied globally or per reference. ```python signxml.sign(..., inclusive_ns_prefixes=['ns1', 'ns2']) # For specific references: reference = signxml.SignatureReference(uri='some_uri', inclusive_ns_prefixes=['ref_ns1']) signxml.sign(..., reference_uri=[reference]) ``` -------------------------------- ### SAML Assertion Verification API Source: https://context7.com/xml-security/signxml/llms.txt Provides methods for verifying SAML assertions using certificates, with options for secure verification and signature placement. ```APIDOC ## SAML Assertion Verification ### Description Verifies SAML assertions using certificates extracted from SAML metadata. Supports secure verification with location assertions and schema-compliant signature placement. ### Method POST (implied by verification process) ### Endpoint /saml/verify ### Parameters #### Request Body - **assertion_body** (bytes) - The base64-encoded SAML assertion. - **x509_cert** (string) - The X.509 certificate used for verification. - **expect_config** (SignatureConfiguration) - Optional configuration for expected signature properties, such as location. ### Request Example ```python from lxml import etree from base64 import b64decode from signxml import XMLVerifier, SignatureConfiguration # Extract certificate from SAML metadata with open("metadata.xml", "rb") as fh: metadata = etree.parse(fh) ns = {"ds": "http://www.w3.org/2000/09/xmldsig#"} cert = metadata.find("//ds:X509Certificate", namespaces=ns).text # Verify SAML assertion (typically base64-encoded) assertion_body = "..." # Base64-encoded SAML assertion assertion_data = XMLVerifier().verify( b64decode(assertion_body), x509_cert=cert ).signed_xml # Secure SAML verification with location assertion config = SignatureConfiguration(location="."). XMLVerifier().verify( b64decode(assertion_body), x509_cert=cert, expect_config=config ) # Sign SAML assertion with schema-compliant signature placement saml_assertion = """ https://idp.example.com user@example.com """ root = etree.fromstring(saml_assertion) signed_assertion = XMLSigner().sign(root, key=key, cert=cert) ``` ``` -------------------------------- ### Handle SignXML Exceptions Source: https://context7.com/xml-security/signxml/llms.txt Provides a pattern for catching specific SignXML exceptions to handle different failure modes like digest mismatches, certificate errors, or invalid signatures. ```python from signxml.exceptions import ( InvalidSignature, InvalidDigest, InvalidCertificate, InvalidInput, SignXMLException ) try: result = XMLVerifier().verify(signed_data, x509_cert=trusted_cert) except InvalidDigest as e: print(f"Digest mismatch - data may have been tampered: {e}") except InvalidCertificate as e: print(f"Certificate validation failed: {e}") except InvalidSignature as e: print(f"Signature verification failed: {e}") except InvalidInput as e: print(f"Invalid input data: {e}") except SignXMLException as e: print(f"SignXML error: {e}") ``` -------------------------------- ### Canonicalization Methods Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Enumeration of XML canonicalization algorithms (c14n) supported by SignXML for ensuring consistent XML representation. ```APIDOC ## Canonicalization Methods ### Description Methods used to canonicalize XML documents to ensure consistent hashing during signature verification. ### Supported Methods - **CANONICAL_XML_1_0**: http://www.w3.org/TR/2001/REC-xml-c14n-20010315 - **CANONICAL_XML_1_1**: http://www.w3.org/2006/12/xml-c14n11 - **EXCLUSIVE_XML_CANONICALIZATION_1_0**: http://www.w3.org/2001/10/xml-exc-c14n# ``` -------------------------------- ### Secure SAML Assertion Verification with Location Source: https://context7.com/xml-security/signxml/llms.txt Enhances SAML assertion verification by enforcing a specific location for the signature within the document. The SignatureConfiguration's 'location' parameter ensures the signature is found at the expected path, adding an extra layer of security against signature wrapping attacks. ```python from lxml import etree from base64 import b64decode from signxml import XMLVerifier, SignatureConfiguration assertion_body = "..." # Base64-encoded SAML assertion config = SignatureConfiguration(location="./") # Expect signature at specific location XMLVerifier().verify( b64decode(assertion_body), x509_cert=cert, expect_config=config ) ``` -------------------------------- ### Create XAdES Signature with Signature Policy Source: https://context7.com/xml-security/signxml/llms.txt Generates an XAdES signature that includes a specific signature policy. This involves defining the policy's identifier, description, digest method, and digest value. The XAdESSigner is initialized with this policy object, ensuring the signature meets defined policy requirements. ```python from signxml import DigestAlgorithm from signxml.xades import XAdESSigner, XAdESSignaturePolicy from lxml import etree signature_policy = XAdESSignaturePolicy( Identifier="urn:oid:2.16.724.1.3.1.1.2.1.9", Description="Electronic invoice signature policy", DigestMethod=DigestAlgorithm.SHA256, DigestValue="Ohixl6upD6av8N7pEvDABhEL6hM=" # Base64-encoded policy digest ) signer = XAdESSigner(signature_policy=signature_policy) doc = etree.fromstring("1000.00") signed_doc = signer.sign(doc, key=key, cert=cert) ``` -------------------------------- ### Enveloped Signature Placeholder Replacement Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Demonstrates how to prepare an XML document for an enveloped signature by inserting a placeholder element. This placeholder will be replaced by the generated signature during the signing process. ```xml Some content ``` -------------------------------- ### XAdES Verifier Class Initialization Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Initializes an XAdES Signature Verifier object. This object is designed to handle the verification of multiple XML signatures according to XAdES standards. ```python from signxml.xades import XAdESVerifier verifier = XAdESVerifier() ``` -------------------------------- ### Signature Construction Methods Source: https://github.com/xml-security/signxml/blob/main/docs/index.md Defines how the signature is constructed relative to the XML document (enveloped vs enveloping). ```APIDOC ## Signature Construction Methods ### Description Specifies the relationship between the signature element and the content being signed. ### Types - **enveloped**: The signature is contained within the XML document being signed. - **enveloping**: The signature contains the content being signed within an Object element. ``` -------------------------------- ### Verify HMAC Signatures with XMLVerifier Source: https://context7.com/xml-security/signxml/llms.txt Verifies XML documents signed using HMAC. It requires the signed document, the HMAC key, and optionally a SignatureConfiguration for specific requirements. The result indicates whether the signature is valid. ```python from signxml import XMLVerifier, SignatureConfiguration hmac_key = b"shared-secret-key-for-hmac" config = SignatureConfiguration(require_x509=False) result = XMLVerifier().verify(signed_doc, hmac_key=hmac_key, expect_config=config) ```