55
66__author__ = 'leifj'
77
8+ import six
89from defusedxml import lxml
910from lxml import etree as etree
1011import logging
1112import copy
1213from lxml .builder import ElementMaker
1314from xmlsec .exceptions import XMLSigException
1415from xmlsec import constants
15- from xmlsec .utils import parse_xml , pem2b64 , unescape_xml_entities , delete_elt , root_elt , b64d , b64e
16+ from xmlsec .utils import parse_xml , pem2b64 , unescape_xml_entities , delete_elt , root_elt , b64d , b64e , etree_to_string
1617import xmlsec .crypto
1718import pyconfig
1819
@@ -81,9 +82,9 @@ def _signed_value(data, key_size, do_pad, hash_alg): # TODO Do proper asn1 CMS
8182 if do_pad :
8283 # Pad to "one octet shorter than the RSA modulus" [RSA-SHA1]
8384 # WARNING: key size is in bits, not bytes!
84- padded_size = key_size / 8 - 1
85+ padded_size = key_size // 8 - 1
8586 pad_size = padded_size - len (asn_digest ) - 2
86- pad = '\x01 ' + '\xFF ' * pad_size + '\x00 '
87+ pad = b '\x01 ' + b '\xFF ' * pad_size + b '\x00 '
8788 return pad + asn_digest
8889 else :
8990 return asn_digest
@@ -151,7 +152,7 @@ def _process_references(t, sig, verify_mode=True, sig_path=".//{%s}Signature" %
151152
152153 if config .debug_write_to_files :
153154 with open ("/tmp/foo-pre-transform.xml" , "w" ) as fd :
154- fd .write (etree . tostring (obj ))
155+ fd .write (etree_to_string (obj ))
155156
156157 for tr in ref .findall (".//{%s}Transform" % NS ['ds' ]):
157158 obj = _transform (_alg (tr ), obj , tr = tr , sig_path = sig_path )
@@ -162,14 +163,16 @@ def _process_references(t, sig, verify_mode=True, sig_path=".//{%s}Signature" %
162163 if nsprefix in r .nsmap :
163164 obj_copy .nsmap [nsprefix ] = r .nsmap [nsprefix ]
164165
165- if not isinstance (obj , basestring ):
166+ if not isinstance (obj , six . string_types ):
166167 if config .debug_write_to_files :
167168 with open ("/tmp/foo-pre-serialize.xml" , "w" ) as fd :
168- fd .write (etree . tostring (obj ))
169+ fd .write (etree_to_string (obj ))
169170 obj = _transform (constants .TRANSFORM_C14N_INCLUSIVE , obj )
170171
171172 if config .debug_write_to_files :
172173 with open ("/tmp/foo-obj.xml" , "w" ) as fd :
174+ if six .PY2 :
175+ obj = obj .encode ('utf-8' )
173176 fd .write (obj )
174177
175178 hash_alg = _ref_digest (ref )
@@ -215,7 +218,7 @@ def _enveloped_signature(t, sig_path=".//{%s}Signature" % NS['ds']):
215218 delete_elt (sig )
216219 if config .debug_write_to_files :
217220 with open ("/tmp/foo-env.xml" , "w" ) as fd :
218- fd .write (etree . tostring (t ))
221+ fd .write (etree_to_string (t ))
219222 return t
220223
221224
@@ -231,15 +234,17 @@ def _c14n(t, exclusive, with_comments, inclusive_prefix_list=None, schema=None):
231234 """
232235 doc = t
233236 if root_elt (doc ).getparent () is not None :
234- xml_str = etree . tostring (doc , encoding = unicode )
237+ xml_str = etree_to_string (doc )
235238 doc = parse_xml (xml_str , remove_whitespace = config .c14n_strip_ws , remove_comments = not with_comments , schema = schema )
236239 del xml_str
237240
238- buf = etree .tostring (doc ,
239- method = 'c14n' ,
240- exclusive = exclusive ,
241- with_comments = with_comments ,
242- inclusive_ns_prefixes = inclusive_prefix_list )
241+ buf = six .text_type (
242+ etree .tostring (doc ,
243+ method = 'c14n' ,
244+ exclusive = exclusive ,
245+ with_comments = with_comments ,
246+ inclusive_ns_prefixes = inclusive_prefix_list ),
247+ 'utf-8' )
243248 #u = unescape_xml_entities(buf.decode("utf8", 'strict')).encode("utf8").strip()
244249 assert buf [0 ] == '<'
245250 assert buf [- 1 ] == '>'
@@ -292,7 +297,7 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
292297 """
293298 if config .debug_write_to_files :
294299 with open ("/tmp/foo-sig.xml" , "w" ) as fd :
295- fd .write (etree . tostring ( root_elt ( t ) ))
300+ fd .write (etree_to_string ( t ))
296301
297302 validated = []
298303 for sig in t .findall (sig_path ):
@@ -330,7 +335,7 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
330335 if not this_cert .verify (b64d (sv ), actual , sig_digest_alg ):
331336 raise XMLSigException ("Failed to validate {!s} using sig digest {!s} and cm {!s}" .format (etree .tostring (sig ), sig_digest_alg , cm_alg ))
332337 validated .append (obj )
333- except XMLSigException , ex :
338+ except XMLSigException as ex :
334339 logging .error (ex )
335340
336341 if not validated :
@@ -433,8 +438,8 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
433438 public .keysize , private .keysize ))
434439 # This might be incorrect for PKCS#11 tokens if we have no public key
435440 logging .debug ("Using {!s} bit key" .format (private .keysize ))
436-
437- templates = filter (_is_template , t . findall ( sig_path ))
441+ sig_paths = t . findall ( sig_path )
442+ templates = list ( filter (_is_template , sig_paths ))
438443 if not templates :
439444 tmpl = add_enveloped_signature (t , reference_uri = reference_uri , pos = insert_index )
440445 templates = [tmpl ]
@@ -443,7 +448,7 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
443448
444449 if config .debug_write_to_files :
445450 with open ("/tmp/sig-ref.xml" , "w" ) as fd :
446- fd .write (etree . tostring (root_elt (t )))
451+ fd .write (etree_to_string (root_elt (t )))
447452
448453 for sig in templates :
449454 logging .debug ("processing sig template: %s" % etree .tostring (sig ))
@@ -469,6 +474,8 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
469474
470475 signed = private .sign (tbs , sig_alg )
471476 signature = b64e (signed )
477+ if isinstance (signature , six .binary_type ):
478+ signature = six .text_type (signature , 'utf-8' )
472479 logging .debug ("SignatureValue: %s" % signature )
473480 sv = sig .find (".//{%s}SignatureValue" % NS ['ds' ])
474481 if sv is None :
0 commit comments