Package tlslite :: Package utils :: Module compat
[hide private]
[frames] | no frames]

Source Code for Module tlslite.utils.compat

  1  # Author: Trevor Perrin 
  2  # See the LICENSE file for legal information regarding use of this file. 
  3   
  4  """Miscellaneous functions to mask Python version differences.""" 
  5   
  6  import sys 
  7  import os 
  8  import math 
  9  import binascii 
 10  import ecdsa 
 11   
 12  if sys.version_info >= (3,0): 
 13   
14 - def compat26Str(x): return x
15 16 # Python 3 requires bytes instead of bytearrays for HMAC 17 18 # So, python 2.6 requires strings, python 3 requires 'bytes', 19 # and python 2.7 can handle bytearrays...
20 - def compatHMAC(x): return bytes(x)
21
22 - def raw_input(s):
23 return input(s)
24 25 # So, the python3 binascii module deals with bytearrays, and python2 26 # deals with strings... I would rather deal with the "a" part as 27 # strings, and the "b" part as bytearrays, regardless of python version, 28 # so...
29 - def a2b_hex(s):
30 try: 31 b = bytearray(binascii.a2b_hex(bytearray(s, "ascii"))) 32 except Exception as e: 33 raise SyntaxError("base16 error: %s" % e) 34 return b
35
36 - def a2b_base64(s):
37 try: 38 b = bytearray(binascii.a2b_base64(bytearray(s, "ascii"))) 39 except Exception as e: 40 raise SyntaxError("base64 error: %s" % e) 41 return b
42
43 - def b2a_hex(b):
44 return binascii.b2a_hex(b).decode("ascii")
45
46 - def b2a_base64(b):
47 return binascii.b2a_base64(b).decode("ascii")
48
49 - def readStdinBinary():
50 return sys.stdin.buffer.read()
51
52 - def compatLong(num):
53 return int(num)
54 55 else: 56 # Python 2.6 requires strings instead of bytearrays in a couple places, 57 # so we define this function so it does the conversion if needed. 58 if sys.version_info < (2,7):
59 - def compat26Str(x): return str(x)
60 else:
61 - def compat26Str(x): return x
62 63 # So, python 2.6 requires strings, python 3 requires 'bytes', 64 # and python 2.7 can handle bytearrays...
65 - def compatHMAC(x): return compat26Str(x)
66
67 - def a2b_hex(s):
68 try: 69 b = bytearray(binascii.a2b_hex(s)) 70 except Exception as e: 71 raise SyntaxError("base16 error: %s" % e) 72 return b
73
74 - def a2b_base64(s):
75 try: 76 b = bytearray(binascii.a2b_base64(s)) 77 except Exception as e: 78 raise SyntaxError("base64 error: %s" % e) 79 return b
80
81 - def b2a_hex(b):
82 return binascii.b2a_hex(compat26Str(b))
83
84 - def b2a_base64(b):
85 return binascii.b2a_base64(compat26Str(b))
86
87 - def compatLong(num):
88 return long(num)
89 90 import traceback
91 -def formatExceptionTrace(e):
92 newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) 93 return newStr
94 95 try: 96 # Fedora and Red Hat Enterprise Linux versions have small curves removed 97 getattr(ecdsa, 'NIST192p') 98 except AttributeError: 99 ecdsaAllCurves = False 100 else: 101 ecdsaAllCurves = True 102