예제 #1
0
 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):
     """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
예제 #4
0
 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)
예제 #6
0
 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
예제 #7
0
 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
예제 #8
0
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,
    )
예제 #9
0
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)
예제 #10
0
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,
      )
예제 #11
0
 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
예제 #12
0
 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 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)
예제 #15
0
 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
예제 #16
0
 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)
예제 #18
0
    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)
예제 #19
0
 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)
예제 #20
0
    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))
예제 #21
0
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
예제 #25
0
 def addCertificate(self):
     return mkse(self, dsig("X509Certificate"))
예제 #26
0
 def addIssuerName(self, name=None):
     return mkse(self, dsig("X509IssuerName"), *(name and (name, ) or ()))
예제 #27
0
 def addHmacOutoutLength(self, bitsLen):
     return mkse(self, dsig("HMACOutputLenght"), str(bitsLen))
예제 #28
0
 def addSubjectName(self):
     return mkse(self, dsig("X509SubjectName"))
 def addIssuerSerial(self):
     return mkse(self, dsig("X509IssuerSerial"))
 def addHmacOutoutLength(self, bitsLen):
     return mkse(self, dsig("HMACOutputLenght"), str(bitsLen))
 def addSKI(self):
     return mkse(self, dsig("X509SKI"))
 def addSubjectName(self):
     return mkse(self, dsig("X509SubjectName"))
 def addCertificate(self):
     return mkse(self, dsig("X509Certificate"))
 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)
예제 #38
0
 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)
예제 #40
0
 def addIssuerSerial(self):
     return mkse(self, dsig("X509IssuerSerial"))
 def addX509Data(self):
     return mkse(self, dsig("X509Data"))
예제 #42
0
 def addSKI(self):
     return mkse(self, dsig("X509SKI"))
예제 #43
0
 def addManifest(self, id=None):
     attrib = {}
     if id: attrib["Id"] = id
     m = mke(dsig("Manifest"), attrib=attrib)
     self.insert(0, m)
     return m
예제 #44
0
 def addCRL(self):
     return mkse(self, dsig("X509CRL"))
예제 #45
0
 def addKeyName(self, name=None):
     kn = mkse(self, dsig("KeyName"))
     if name is not None: kn.text = name
     return kn
예제 #46
0
 def addSerial(self, serial=None):
     return mkse(self, dsig("X509SerialNumber"),
                 *(serial and (serial, ) or ()))
예제 #47
0
 def addKeyValue(self):
     return mkse(self, dsig("KeyValue"))
예제 #48
0
 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
예제 #49
0
 def addX509Data(self):
     return mkse(self, dsig("X509Data"))
 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)
예제 #51
0
 def addRetrievalMethod(self, uri, type=None):
     attrib = dict(URI=uri)
     if type: attrib["Type"] = type
     return mkse(self, dsig("RetrievalMethod"), attrib=attrib)
예제 #52
0
 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 ()))