Skip to content

Commit 4055a6c

Browse files
authored
Merge pull request #64 from IdentityPython/more-py3-compat
More py3 compat
2 parents d724f8d + c2cb3f6 commit 4055a6c

5 files changed

Lines changed: 37 additions & 36 deletions

File tree

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
six
12
defusedxml
23
lxml
34
pyconfig

setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,6 @@
4242
},
4343
zip_safe=False,
4444
install_requires=install_requires,
45-
requires=install_requires,
4645
extras_require=extras_require,
4746
entry_points={
4847
'console_scripts': ['xmlsign=xmlsec.tools:sign_cmd','xmlverify=xmlsec.tools:verify_cmd']

src/xmlsec/__init__.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@
2222
DS = ElementMaker(namespace=NS['ds'], nsmap=NSDefault)
2323

2424

25+
log = logging.getLogger('xmlsec')
26+
2527
class Config(object):
2628
"""
2729
This class holds a set of configuration parameters (using pyconfig) for pyXMLSecurity:
@@ -92,7 +94,7 @@ def _signed_value(data, key_size, do_pad, hash_alg): # TODO Do proper asn1 CMS
9294

9395
def _get_by_id(t, id_v):
9496
for id_a in config.id_attributes:
95-
logging.debug("Looking for #%s using id attribute '%s'" % (id_v, id_a))
97+
log.debug("Looking for #%s using id attribute '%s'" % (id_v, id_a))
9698
elts = t.xpath("//*[@%s='%s']" % (id_a, id_v))
9799
if elts is not None and len(elts) > 0:
98100
return elts[0]
@@ -176,21 +178,21 @@ def _process_references(t, sig, verify_mode=True, sig_path=".//{%s}Signature" %
176178
fd.write(obj)
177179

178180
hash_alg = _ref_digest(ref)
179-
logging.debug("using hash algorithm %s" % hash_alg)
181+
log.debug("using hash algorithm %s" % hash_alg)
180182
digest = xmlsec.crypto._digest(obj, hash_alg)
181-
logging.debug("computed %s digest %s for ref %s" % (hash_alg, digest, uri))
183+
log.debug("computed %s digest %s for ref %s" % (hash_alg, digest, uri))
182184
dv = ref.find(".//{%s}DigestValue" % NS['ds'])
183185

184186
if verify_mode:
185-
logging.debug("found %s digest %s for ref %s" % (hash_alg, dv.text, uri))
187+
log.debug("found %s digest %s for ref %s" % (hash_alg, dv.text, uri))
186188
computed_digest_binary = b64d(digest)
187189
digest_binary = b64d(dv.text)
188190
if digest_binary == computed_digest_binary: # no point in verifying signature if the digest doesn't match
189191
verified_objects[ref] = obj_copy
190192
else:
191-
logging.error("not returning ref %s - digest mismatch" % uri)
193+
log.error("not returning ref %s - digest mismatch" % uri)
192194
else: # signing - lets store the digest
193-
logging.debug("replacing digest in %s" % etree.tostring(dv))
195+
log.debug("replacing digest in %s" % etree.tostring(dv))
194196
dv.text = digest
195197

196198

@@ -306,12 +308,12 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
306308
if not sv:
307309
raise XMLSigException("No SignatureValue")
308310

309-
logging.debug("SignatureValue: {!s}".format(sv))
311+
log.debug("SignatureValue: {!s}".format(sv))
310312
this_cert = xmlsec.crypto.from_keyspec(keyspec, signature_element=sig)
311-
logging.debug("key size: {!s} bits".format(this_cert.keysize))
313+
log.debug("key size: {!s} bits".format(this_cert.keysize))
312314

313315
si = sig.find(".//{%s}SignedInfo" % NS['ds'])
314-
logging.debug("Found signedinfo {!s}".format(etree.tostring(si)))
316+
log.debug("Found signedinfo {!s}".format(etree.tostring(si)))
315317
cm_alg = _cm_alg(si)
316318
try:
317319
sig_digest_alg = _sig_alg(si)
@@ -321,12 +323,12 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
321323
refmap = _process_references(t, sig, verify_mode=True, sig_path=sig_path, drop_signature=drop_signature)
322324
for ref,obj in refmap.items():
323325

324-
logging.debug("transform %s on %s" % (cm_alg, etree.tostring(si)))
326+
log.debug("transform %s on %s" % (cm_alg, etree.tostring(si)))
325327
sic = _transform(cm_alg, si)
326-
logging.debug("SignedInfo C14N: %s" % sic)
328+
log.debug("SignedInfo C14N: %s" % sic)
327329
if this_cert.do_digest:
328330
digest = xmlsec.crypto._digest(sic, sig_digest_alg)
329-
logging.debug("SignedInfo digest: %s" % digest)
331+
log.debug("SignedInfo digest: %s" % digest)
330332
b_digest = b64d(digest)
331333
actual = _signed_value(b_digest, this_cert.keysize, True, sig_digest_alg)
332334
else:
@@ -336,7 +338,7 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
336338
raise XMLSigException("Failed to validate {!s} using sig digest {!s} and cm {!s}".format(etree.tostring(sig), sig_digest_alg, cm_alg))
337339
validated.append(obj)
338340
except XMLSigException as ex:
339-
logging.error(ex)
341+
log.error(ex)
340342

341343
if not validated:
342344
raise XMLSigException("No valid ds:Signature elements found")
@@ -437,7 +439,7 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
437439
raise XMLSigException("Public and private key sizes do not match ({!s}, {!s})".format(
438440
public.keysize, private.keysize))
439441
# This might be incorrect for PKCS#11 tokens if we have no public key
440-
logging.debug("Using {!s} bit key".format(private.keysize))
442+
log.debug("Using {!s} bit key".format(private.keysize))
441443
sig_paths = t.findall(sig_path)
442444
templates = list(filter(_is_template, sig_paths))
443445
if not templates:
@@ -451,22 +453,22 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
451453
fd.write(etree_to_string(root_elt(t)))
452454

453455
for sig in templates:
454-
logging.debug("processing sig template: %s" % etree.tostring(sig))
456+
log.debug("processing sig template: %s" % etree.tostring(sig))
455457
si = sig.find(".//{%s}SignedInfo" % NS['ds'])
456458
assert si is not None
457459
cm_alg = _cm_alg(si)
458460
sig_alg = _sig_alg(si)
459461

460462
_process_references(t, sig, verify_mode=False, sig_path=sig_path)
461463
# XXX create signature reference duplicates/overlaps process references unless a c14 is part of transforms
462-
logging.debug("transform %s on %s" % (cm_alg, etree.tostring(si)))
464+
log.debug("transform %s on %s" % (cm_alg, etree.tostring(si)))
463465
sic = _transform(cm_alg, si)
464-
logging.debug("SignedInfo C14N: %s" % sic)
466+
log.debug("SignedInfo C14N: %s" % sic)
465467

466468
# sign hash digest and insert it into the XML
467469
if private.do_digest:
468470
digest = xmlsec.crypto._digest(sic, sig_alg)
469-
logging.debug("SignedInfo digest: %s" % digest)
471+
log.debug("SignedInfo digest: %s" % digest)
470472
b_digest = b64d(digest)
471473
tbs = _signed_value(b_digest, private.keysize, private.do_padding, sig_alg)
472474
else:
@@ -476,7 +478,7 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
476478
signature = b64e(signed)
477479
if isinstance(signature, six.binary_type):
478480
signature = six.text_type(signature, 'utf-8')
479-
logging.debug("SignatureValue: %s" % signature)
481+
log.debug("SignatureValue: %s" % signature)
480482
sv = sig.find(".//{%s}SignatureValue" % NS['ds'])
481483
if sv is None:
482484
si.addnext(DS.SignatureValue(signature))

src/xmlsec/crypto.py

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44
import logging
55
import threading
66
import six
7+
from six.moves import xrange
8+
from xmlsec import constants
79
from binascii import hexlify
810
from xmlsec.exceptions import XMLSigException
911
from xmlsec.utils import unicode_to_bytes
@@ -12,6 +14,7 @@
1214
from cryptography.hazmat.primitives import serialization, hashes
1315
from cryptography.hazmat.primitives.asymmetric import rsa, padding, utils
1416
from cryptography.x509 import load_pem_x509_certificate, load_der_x509_certificate, Certificate
17+
import base64
1518

1619
if six.PY2:
1720
from UserDict import DictMixin
@@ -223,16 +226,22 @@ def sign(self, data, hash_alg=None):
223226
import requests
224227
import json
225228
url = '{!s}/rawsign'.format(self._keyspec)
226-
r = requests.post(url, json=dict(mech='RSAPKCS1', data=data.encode("base64")))
229+
if not isinstance(data, six.binary_type):
230+
data = data.encode("utf-8")
231+
data = base64.b64encode(data)
232+
r = requests.post(url, json=dict(mech='RSAPKCS1', data=data))
227233
if r.status_code != requests.codes.ok:
228234
r.raise_for_status()
229235
msg = r.json()
230-
if not 'signed' in msg:
236+
if 'signed' not in msg:
231237
raise ValueError("Missing signed data in response message")
232-
return msg['signed'].decode('base64')
238+
signed_msg = msg['signed']
239+
if not isinstance(signed_msg, six.binary_type):
240+
signed_msg = signed_msg.encode("utf-8")
241+
return base64.b64decode(signed_msg)
233242
except Exception as ex:
234-
from traceback import print_exc
235-
print_exc(ex)
243+
from traceback import format_exc
244+
log.debug(format_exc())
236245
raise XMLSigException(ex)
237246

238247

@@ -311,7 +320,7 @@ def _cert_fingerprint(cert_pem):
311320
else:
312321
cert = load_der_x509_certificate(base64.standard_b64decode(cert_pem), backend=default_backend())
313322

314-
fingerprint = hexlify(cert.fingerprint(hashes.SHA1())).lower()
323+
fingerprint = hexlify(cert.fingerprint(hashes.SHA1())).lower().decode('ascii')
315324
fingerprint = ":".join([fingerprint[x:x + 2] for x in xrange(0, len(fingerprint), 2)])
316325

317326
return fingerprint, cert

src/xmlsec/test/p11_test.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -238,16 +238,6 @@ def teardown(self):
238238
self.p11_test_files = []
239239

240240

241-
def _get_all_signatures(t):
242-
res = []
243-
for sig in t.findall(".//{%s}Signature" % xmlsec.NS['ds']):
244-
sv = sig.findtext(".//{%s}SignatureValue" % xmlsec.NS['ds'])
245-
assert sv is not None
246-
# base64-dance to normalize newlines
247-
res.append(sv.decode('base64').encode('base64'))
248-
return res
249-
250-
251241
class TestPKCS11(unittest.TestCase):
252242
def setUp(self):
253243
datadir = pkg_resources.resource_filename(__name__, 'data')

0 commit comments

Comments
 (0)