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
@@ -83,9 +84,9 @@ def _signed_value(data, key_size, do_pad, hash_alg): # TODO Do proper asn1 CMS
8384 if do_pad :
8485 # Pad to "one octet shorter than the RSA modulus" [RSA-SHA1]
8586 # WARNING: key size is in bits, not bytes!
86- padded_size = key_size / 8 - 1
87+ padded_size = key_size // 8 - 1
8788 pad_size = padded_size - len (asn_digest ) - 2
88- pad = '\x01 ' + '\xFF ' * pad_size + '\x00 '
89+ pad = b '\x01 ' + b '\xFF ' * pad_size + b '\x00 '
8990 return pad + asn_digest
9091 else :
9192 return asn_digest
@@ -153,7 +154,7 @@ def _process_references(t, sig, verify_mode=True, sig_path=".//{%s}Signature" %
153154
154155 if config .debug_write_to_files :
155156 with open ("/tmp/foo-pre-transform.xml" , "w" ) as fd :
156- fd .write (etree . tostring (obj ))
157+ fd .write (etree_to_string (obj ))
157158
158159 for tr in ref .findall (".//{%s}Transform" % NS ['ds' ]):
159160 obj = _transform (_alg (tr ), obj , tr = tr , sig_path = sig_path )
@@ -164,14 +165,16 @@ def _process_references(t, sig, verify_mode=True, sig_path=".//{%s}Signature" %
164165 if nsprefix in r .nsmap :
165166 obj_copy .nsmap [nsprefix ] = r .nsmap [nsprefix ]
166167
167- if not isinstance (obj , basestring ):
168+ if not isinstance (obj , six . string_types ):
168169 if config .debug_write_to_files :
169170 with open ("/tmp/foo-pre-serialize.xml" , "w" ) as fd :
170- fd .write (etree . tostring (obj ))
171+ fd .write (etree_to_string (obj ))
171172 obj = _transform (constants .TRANSFORM_C14N_INCLUSIVE , obj )
172173
173174 if config .debug_write_to_files :
174175 with open ("/tmp/foo-obj.xml" , "w" ) as fd :
176+ if six .PY2 :
177+ obj = obj .encode ('utf-8' )
175178 fd .write (obj )
176179
177180 hash_alg = _ref_digest (ref )
@@ -217,7 +220,7 @@ def _enveloped_signature(t, sig_path=".//{%s}Signature" % NS['ds']):
217220 delete_elt (sig )
218221 if config .debug_write_to_files :
219222 with open ("/tmp/foo-env.xml" , "w" ) as fd :
220- fd .write (etree . tostring (t ))
223+ fd .write (etree_to_string (t ))
221224 return t
222225
223226
@@ -233,15 +236,17 @@ def _c14n(t, exclusive, with_comments, inclusive_prefix_list=None, schema=None):
233236 """
234237 doc = t
235238 if root_elt (doc ).getparent () is not None :
236- xml_str = etree . tostring (doc , encoding = unicode )
239+ xml_str = etree_to_string (doc )
237240 doc = parse_xml (xml_str , remove_whitespace = config .c14n_strip_ws , remove_comments = not with_comments , schema = schema )
238241 del xml_str
239242
240- buf = etree .tostring (doc ,
241- method = 'c14n' ,
242- exclusive = exclusive ,
243- with_comments = with_comments ,
244- inclusive_ns_prefixes = inclusive_prefix_list )
243+ buf = six .text_type (
244+ etree .tostring (doc ,
245+ method = 'c14n' ,
246+ exclusive = exclusive ,
247+ with_comments = with_comments ,
248+ inclusive_ns_prefixes = inclusive_prefix_list ),
249+ 'utf-8' )
245250 #u = unescape_xml_entities(buf.decode("utf8", 'strict')).encode("utf8").strip()
246251 assert buf [0 ] == '<'
247252 assert buf [- 1 ] == '>'
@@ -294,7 +299,7 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
294299 """
295300 if config .debug_write_to_files :
296301 with open ("/tmp/foo-sig.xml" , "w" ) as fd :
297- fd .write (etree . tostring ( root_elt ( t ) ))
302+ fd .write (etree_to_string ( t ))
298303
299304 validated = []
300305 for sig in t .findall (sig_path ):
@@ -332,7 +337,7 @@ def _verify(t, keyspec, sig_path=".//{%s}Signature" % NS['ds'], drop_signature=F
332337 if not this_cert .verify (b64d (sv ), actual , sig_digest_alg ):
333338 raise XMLSigException ("Failed to validate {!s} using sig digest {!s} and cm {!s}" .format (etree .tostring (sig ), sig_digest_alg , cm_alg ))
334339 validated .append (obj )
335- except XMLSigException , ex :
340+ except XMLSigException as ex :
336341 log .error (ex )
337342
338343 if not validated :
@@ -435,8 +440,8 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
435440 public .keysize , private .keysize ))
436441 # This might be incorrect for PKCS#11 tokens if we have no public key
437442 log .debug ("Using {!s} bit key" .format (private .keysize ))
438-
439- templates = filter (_is_template , t . findall ( sig_path ))
443+ sig_paths = t . findall ( sig_path )
444+ templates = list ( filter (_is_template , sig_paths ))
440445 if not templates :
441446 tmpl = add_enveloped_signature (t , reference_uri = reference_uri , pos = insert_index )
442447 templates = [tmpl ]
@@ -445,7 +450,7 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
445450
446451 if config .debug_write_to_files :
447452 with open ("/tmp/sig-ref.xml" , "w" ) as fd :
448- fd .write (etree . tostring (root_elt (t )))
453+ fd .write (etree_to_string (root_elt (t )))
449454
450455 for sig in templates :
451456 log .debug ("processing sig template: %s" % etree .tostring (sig ))
@@ -471,6 +476,8 @@ def sign(t, key_spec, cert_spec=None, reference_uri='', insert_index=0, sig_path
471476
472477 signed = private .sign (tbs , sig_alg )
473478 signature = b64e (signed )
479+ if isinstance (signature , six .binary_type ):
480+ signature = six .text_type (signature , 'utf-8' )
474481 log .debug ("SignatureValue: %s" % signature )
475482 sv = sig .find (".//{%s}SignatureValue" % NS ['ds' ])
476483 if sv is None :
0 commit comments