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   
11  if sys.version_info >= (3,0): 
12   
13 - def compat26Str(x): return x
14 15 # Python 3 requires bytes instead of bytearrays for HMAC 16 17 # So, python 2.6 requires strings, python 3 requires 'bytes', 18 # and python 2.7 can handle bytearrays...
19 - def compatHMAC(x): return bytes(x)
20
21 - def raw_input(s):
22 return input(s)
23 24 # So, the python3 binascii module deals with bytearrays, and python2 25 # deals with strings... I would rather deal with the "a" part as 26 # strings, and the "b" part as bytearrays, regardless of python version, 27 # so...
28 - def a2b_hex(s):
29 try: 30 b = bytearray(binascii.a2b_hex(bytearray(s, "ascii"))) 31 except Exception as e: 32 raise SyntaxError("base16 error: %s" % e) 33 return b
34
35 - def a2b_base64(s):
36 try: 37 b = bytearray(binascii.a2b_base64(bytearray(s, "ascii"))) 38 except Exception as e: 39 raise SyntaxError("base64 error: %s" % e) 40 return b
41
42 - def b2a_hex(b):
43 return binascii.b2a_hex(b).decode("ascii")
44
45 - def b2a_base64(b):
46 return binascii.b2a_base64(b).decode("ascii")
47
48 - def b2a_base32(b):
49 return base64.b32encode(b).decode("ascii")
50 51 # Decodes all 256 byte values, use "ascii" for first 128
52 - def bytesToStr(b, encoding="latin-1"):
53 return b.decode(encoding)
54
55 - def readStdinBinary():
56 return sys.stdin.buffer.read()
57 58 else: 59 # Python 2.6 requires strings instead of bytearrays in a couple places, 60 # so we define this function so it does the conversion if needed. 61 if sys.version_info < (2,7):
62 - def compat26Str(x): return str(x)
63 else:
64 - def compat26Str(x): return x
65 66 # So, python 2.6 requires strings, python 3 requires 'bytes', 67 # and python 2.7 can handle bytearrays...
68 - def compatHMAC(x): return compat26Str(x)
69
70 - def a2b_hex(s):
71 try: 72 b = bytearray(binascii.a2b_hex(s)) 73 except Exception as e: 74 raise SyntaxError("base16 error: %s" % e) 75 return b
76
77 - def a2b_base64(s):
78 try: 79 b = bytearray(binascii.a2b_base64(s)) 80 except Exception as e: 81 raise SyntaxError("base64 error: %s" % e) 82 return b
83
84 - def b2a_hex(b):
85 return binascii.b2a_hex(compat26Str(b))
86
87 - def b2a_base64(b):
88 return binascii.b2a_base64(compat26Str(b))
89
90 - def b2a_base32(b):
91 return base64.b32encode(str(b))
92 93 import traceback
94 -def formatExceptionTrace(e):
95 newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) 96 return newStr
97