def ensureKeyInfo(self, id=None): """creates a `KeyInfo` element, if not already present.""" ki = self.find(dsig("KeyInfo")) if ki is None: ki = mke(dsig("KeyInfo"), **(id and dict(Id=id) or {})) self[2:2] = [ki] return ki
def ensureKeyInfo(self, id=None): ki = self.find(dsig("KeyInfo")) if ki is None: ki = mke(dsig("KeyInfo"), attrib=id and dict(Id=id) or None) kii = self.find(enc("EncryptionMethod")) is not None and 1 or 0 self.insert(kii, ki) return ki
def ensureSignProperties(self, id=None): sp = self.find(dsig("SignProperties")) if sp is None: sp = mkse(self, dsig("SignProperties"), attrib = id and dict(Id=id) or None, ) return sp
def Signature(c14nMethod, signMethod, id=None, nsPrefix=None): """`Signature` factory.""" info = mke(dsig("SignedInfo")) mkse(info, dsig("CanonicalizationMethod"), Algorithm=c14nMethod.href) mkse(info, dsig("SignatureMethod"), Algorithm=signMethod.href) attrib = id and dict(Id=id) or None nsmap = nsPrefix and dict(nsPrefix=DSignNs) or DSigNsMap return _Signature(info, mke(dsig("SignatureValue")), attrib=attrib, nsmap=nsmap)
def ensureSignProperties(self, id=None): sp = self.find(dsig("SignProperties")) if sp is None: sp = mkse( self, dsig("SignProperties"), attrib=id and dict(Id=id) or None, ) return sp
def ensureKeyInfo(self, id=None): ki = self.find(dsig("KeyInfo")) if ki is None: ki = mke( dsig("KeyInfo"), attrib=id and dict(Id=id) or None, ) kii = self.find(enc("EncryptionMethod")) is not None and 1 or 0 self.insert(kii, ki) return ki
def Reference(digestMethod, id=None, uri=None, type=None): attrib = {} if id: attrib["Id"] = id if uri: attrib["URI"] = uri if type: attrib["Type"] = type return mke( dsig("Reference"), mke(dsig("DigestMethod"), Algorithm=digestMethod.href), mke(dsig("DigestValue")), attrib=attrib, )
def Signature(c14nMethod, signMethod, id=None, nsPrefix=None): """`Signature` factory.""" info = mke(dsig("SignedInfo")) mkse(info, dsig("CanonicalizationMethod"), Algorithm=c14nMethod.href) mkse(info, dsig("SignatureMethod"), Algorithm=signMethod.href) attrib = id and dict(Id=id) or None nsmap = nsPrefix and {nsPrefix: DSigNs} or DSigNsMap return _Signature(info, mke(dsig("SignatureValue")), attrib=attrib, nsmap=nsmap)
def addObject(self, id=None, mimeType=None, encoding=None): attrib = {} if id: attrib["Id"] = id if mimeType: attrib["MimeType"] = mimeType if encoding: attrib["Encoding"] = encoding o = mkse(self, dsig("Object"), attrib=attrib) return o
def addSignProperty(self, id=None, target=None): attrib = {} if id: attrib["Id"] = id if target: attrib["Target"] = target return mkse(self.ensureSignProperties(), dsig("SignProperties"), attrib=attrib)
def addManifest(self, id=None): attrib = {} if id: attrib["Id"] = id m = mke(dsig("Manifest"), attrib=attrib) self.insert(0, m) return m
def sign(self,doc, key): node = xmlsec.findNode(doc, xmlsec.dsig("Signature")) if node == None: print "Node was None" dsigCtx = xmlsec.DSigCtx() signKey = xmlsec.Key.load(key, xmlsec.KeyDataFormatPem, None) signKey.name = basename(key) dsigCtx.signKey = signKey dsigCtx.sign(node) return tostring(doc)
def sign(self, doc, id, keyname): """sign element identified by *id* in *doc* (`lxml` etree) with the (first) key with *keyname*.""" from dm.xmlsec.binding import dsig, DSigCtx, findNode, Error # will fail with ``IndexError`` when the id does not exist node = doc.xpath('//*[@ID="%s"]' % id)[0] node = findNode(node, dsig("Signature")) assert node is not None, "Missing signature element" sign_ctx = DSigCtx(None) sign_ctx.signKey = self.__keys_manager[keyname][0] try: sign_ctx.sign(node) except Error, e: raise SignError('signing failed', id, keyname, e)
def sign(self,doc, key): #print ("doc: ",tostring(doc)) #print ("key: ",key) node = xmlsec.findNode(doc, xmlsec.dsig("Signature")) dsigCtx = xmlsec.DSigCtx() signKey = xmlsec.Key.load(key, xmlsec.KeyDataFormatPem, None) signKey.name = basename(key) dsigCtx.signKey = signKey dsigCtx.sign(node) #print ("node: ",tostring(node)) #print ("doc : ",tostring(doc)) return tostring(doc)
def verify(self, doc, id, keyname): """verify the node identified by *id* in *doc* using a key associated with *keyname*. Raise ``VerifyError``, when the verification fails. We only allow a single reference. Its uri must either be empty or refer to the element we are verifying. In addition, we only allow the standard transforms. """ from dm.xmlsec.binding import findNode, dsig, DSigCtx, \ TransformExclC14N, TransformExclC14NWithComments, \ TransformEnveloped, \ VerificationError node = doc.xpath('//*[@ID="%s"]' % id) if len(node) != 1: raise VerifyError('id not unique or not found: %s %d' % (id, len(nodes))) node = node[0] sig = findNode(node, dsig("Signature")) # verify the reference. refs = sig.xpath('ds:SignedInfo/ds:Reference', namespaces=dsigns) if len(refs) != 1: raise VerifyError('only a single reference is allowed: %d' % len(refs)) ref = refs[0] uris = ref.xpath('@URI') if not uris or uris[0] != '#' + id: raise VerifyError( 'reference uri does not refer to signature parent', id) # now verify the signature: try each key in turn for key in self.__keys_manager.get(keyname, ()): verify_ctx = DSigCtx(None) for t in chain((TransformExclC14N, TransformExclC14NWithComments), config.signature_transforms): verify_ctx.enableSignatureTransform(t) for t in chain((TransformExclC14N, TransformExclC14NWithComments, TransformEnveloped), config.reference_transforms): verify_ctx.enableReferenceTransform(t) verify_ctx.signKey = key try: verify_ctx.verify(sig) except VerificationError: pass else: return raise VerifyError('signature verification failed: %s %s' % (id, keyname))
def firmar_digitalmente_semilla(tmpl_file, key_file, cert_file): from lxml.etree import parse, tostring doc = parse(tmpl_file) # find signature node node = xmlsec.findNode(doc, xmlsec.dsig("Signature")) dsigCtx = xmlsec.DSigCtx() # Note: we do not provide read access to `dsigCtx.signKey`. # Therefore, unlike the `xmlsec` example, we must set the key name # before we assign it to `dsigCtx` # load tiene el paramtro password vacio, porque el pem que yo genero no esta protegido signKey = xmlsec.Key.load(key_file, xmlsec.KeyDataFormatPem, "") signKey.loadCert(cert_file, xmlsec.KeyDataFormatPem) # Note: the assignment below effectively copies the key dsigCtx.signKey = signKey dsigCtx.sign(node) outFile = open('archivo_semilla_firmada.xml', 'w') doc.write(outFile, xml_declaration=True, encoding='iso-8859-1') return tostring(doc)
def verify(self, doc, id, keyname): """verify the node identified by *id* in *doc* using a key associated with *keyname*. Raise ``VerifyError``, when the verification fails. We only allow a single reference. Its uri must either be empty or refer to the element we are verifying. In addition, we only allow the standard transforms. """ from dm.xmlsec.binding import findNode, dsig, DSigCtx, \ TransformExclC14N, TransformExclC14NWithComments, \ TransformEnveloped, \ VerificationError node = doc.xpath('//*[@ID="%s"]' % id) if len(node) != 1: raise VerifyError('id not unique or not found: %s %d' % (id, len(nodes))) node = node[0] sig = findNode(node, dsig("Signature")) # verify the reference. refs = sig.xpath('ds:SignedInfo/ds:Reference', namespaces=dsigns) if len(refs) != 1: raise VerifyError('only a single reference is allowed: %d' % len(refs)) ref = refs[0] uris = ref.xpath('@URI') if not uris or uris[0] != '#' + id: raise VerifyError('reference uri does not refer to signature parent', id) # now verify the signature: try each key in turn for key in self.__keys_manager.get(keyname, ()): verify_ctx = DSigCtx(None) for t in chain((TransformExclC14N, TransformExclC14NWithComments), config.signature_transforms): verify_ctx.enableSignatureTransform(t) for t in chain((TransformExclC14N, TransformExclC14NWithComments, TransformEnveloped), config.reference_transforms): verify_ctx.enableReferenceTransform(t) verify_ctx.signKey = key try: verify_ctx.verify(sig) except VerificationError: pass else: return raise VerifyError('signature verification failed: %s %s' % (id, keyname))
def addKeyValue(self): return mkse(self, dsig("KeyValue"))
def addKeyName(self, name=None): kn = mkse(self, dsig("KeyName")) if name is not None: kn.text = name return kn
def addCertificate(self): return mkse(self, dsig("X509Certificate"))
def addIssuerName(self, name=None): return mkse(self, dsig("X509IssuerName"), *(name and (name, ) or ()))
def addHmacOutoutLength(self, bitsLen): return mkse(self, dsig("HMACOutputLenght"), str(bitsLen))
def addSubjectName(self): return mkse(self, dsig("X509SubjectName"))
def addIssuerSerial(self): return mkse(self, dsig("X509IssuerSerial"))
def addSKI(self): return mkse(self, dsig("X509SKI"))
def addTransform(self, transform): ts = self.find(enc("Transforms")) if ts is None: ts = mkse(self, enc("Transforms")) t = mkse(ts, dsig("Transform"), Algorithm=transform.href) return t
def addCRL(self): return mkse(self, dsig("X509CRL"))
def addSerial(self, serial=None): return mkse(self, dsig("X509SerialNumber"), *(serial and (serial,) or ()))
def addXPath(self, expression, nsmap=None): return mkse(self, dsig("XPath"), expression, nsmap=nsmap)
def addRetrievalMethod(self, uri, type=None): attrib = dict(URI=uri) if type: attrib["Type"] = type return mkse(self, dsig("RetrievalMethod"), attrib=attrib)
def addX509Data(self): return mkse(self, dsig("X509Data"))
def addSerial(self, serial=None): return mkse(self, dsig("X509SerialNumber"), *(serial and (serial, ) or ()))
def addTransform(self, transform): ts = self.find(dsig("Transforms")) if ts is None: ts = mke(dsig("Transforms")) self.insert(0, ts) return mkse(ts, dsig("Transform"), Algorithm=transform.href)
def addIssuerName(self, name=None): return mkse(self, dsig("X509IssuerName"), *(name and (name,) or ()))