Signing Documents¶
Sign and verify signatures using the python-xmlsec library.
-
saml.signature.
sign
(xml, stream, password=None)[source]¶ Sign an XML document with the given private key file. This will add a <Signature> element to the document.
Parameters: - xml (lxml.etree._Element) – The document to sign
- stream (file) – The private key to sign the document with
- password (str) – The password used to access the private key
Return type: None
Example usage:
from saml import schema from lxml import etree document = schema.AuthenticationRequest() xml_document = document.serialize() with open('my_key_file.pem', 'r+') as stream: sign(xml_document, stream) print etree.tostring(xml_document)
Produces the following XML document:
<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" ID="_6087de0b111b44349a70ff40191a4c0c" IssueInstant="2015-03-16T21:06:39Z"> <Signature xmlns="http://www.w3.org/2000/09/xmldsig#"> <SignedInfo> <CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/> <SignatureMethod Algorithm="http://www.w3.org/2000/ 09/xmldsig#rsa-sha1"/> <Reference> <Transforms> <Transform Algorithm="http://www.w3.org/2000/ 09/xmldsig#enveloped-signature"/> </Transforms> <DigestMethod Algorithm="http://www.w3.org/2000/ 09/xmldsig#sha1"/> <DigestValue> 94O1FOjRE4JQYVDqStkYzne9StQ= </DigestValue> </Reference> </SignedInfo> <SignatureValue> aFYRRjtB3bDyLLJzLZmsn0K4SXmOpFYJ+8R8D31VojgiF37FOElbE56UFbm8BAjn l2AixrUGXP4djxoxxnfBD/reYw5yVuIVXlMxKec784nF2V4GyrfwJOKaNmlVPkq5 c8SI+EkKJ02mwiail0Zvjb9FzwvlYD+osMSXvJXVqnGHQDVFlhwbBRRVB6t44/M3 TzC4mLSVhuvcpsm4GTQSpGkHP7HvweKN/OTc0aTy8Kh/YUrImwnUCii+J0EW4nGg 71eZyq/IiSPnTD09WDHsWe3g29kpicZXqrQCWeLE2zfVKtyxxs7PyEmodH19jXyz wh9hQ8t6PFO47Ros5aV0bw== </SignatureValue> </Signature> </samlp:AuthnRequest>
-
saml.signature.
verify
(xml, stream)[source]¶ Verify the signaure of an XML document with the given certificate. Returns True if the document is signed with a valid signature. Returns False if the document is not signed or if the signature is invalid.
Parameters: - xml (lxml.etree._Element) – The document to sign
- stream (file) – The private key to sign the document with
Return type: Boolean