OLD | NEW |
| 1 # Author: Trevor Perrin |
| 2 # See the LICENSE file for legal information regarding use of this file. |
| 3 |
1 """Miscellaneous functions to mask Python version differences.""" | 4 """Miscellaneous functions to mask Python version differences.""" |
2 | 5 |
3 import sys | 6 import sys |
4 import os | 7 import os |
| 8 import math |
| 9 import binascii |
5 | 10 |
6 if sys.version_info < (2,2): | 11 if sys.version_info >= (3,0): |
7 raise AssertionError("Python 2.2 or later required") | |
8 | 12 |
9 if sys.version_info < (2,3): | 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 |
10 | 34 |
11 def enumerate(collection): | 35 def a2b_base64(s): |
12 return zip(range(len(collection)), collection) | 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 |
13 | 41 |
14 class Set: | 42 def b2a_hex(b): |
15 def __init__(self, seq=None): | 43 return binascii.b2a_hex(b).decode("ascii") |
16 self.values = {} | 44 |
17 if seq: | 45 def b2a_base64(b): |
18 for e in seq: | 46 return binascii.b2a_base64(b).decode("ascii") |
19 self.values[e] = None | |
20 | 47 |
21 def add(self, e): | 48 def b2a_base32(b): |
22 self.values[e] = None | 49 return base64.b32encode(b).decode("ascii") |
| 50 |
| 51 def readStdinBinary(): |
| 52 return sys.stdin.buffer.read() |
23 | 53 |
24 def discard(self, e): | 54 def long(n): |
25 if e in self.values.keys(): | 55 return n |
26 del(self.values[e]) | |
27 | |
28 def union(self, s): | |
29 ret = Set() | |
30 for e in self.values.keys(): | |
31 ret.values[e] = None | |
32 for e in s.values.keys(): | |
33 ret.values[e] = None | |
34 return ret | |
35 | |
36 def issubset(self, other): | |
37 for e in self.values.keys(): | |
38 if e not in other.values.keys(): | |
39 return False | |
40 return True | |
41 | |
42 def __nonzero__( self): | |
43 return len(self.values.keys()) | |
44 | |
45 def __contains__(self, e): | |
46 return e in self.values.keys() | |
47 | |
48 def __iter__(self): | |
49 return iter(set.values.keys()) | |
50 | |
51 | |
52 if os.name != "java": | |
53 | |
54 import array | |
55 def createByteArraySequence(seq): | |
56 return array.array('B', seq) | |
57 def createByteArrayZeros(howMany): | |
58 return array.array('B', [0] * howMany) | |
59 def concatArrays(a1, a2): | |
60 return a1+a2 | |
61 | |
62 def bytesToString(bytes): | |
63 return bytes.tostring() | |
64 def stringToBytes(s): | |
65 bytes = createByteArrayZeros(0) | |
66 bytes.fromstring(s) | |
67 return bytes | |
68 | |
69 import math | |
70 def numBits(n): | |
71 if n==0: | |
72 return 0 | |
73 s = "%x" % n | |
74 return ((len(s)-1)*4) + \ | |
75 {'0':0, '1':1, '2':2, '3':2, | |
76 '4':3, '5':3, '6':3, '7':3, | |
77 '8':4, '9':4, 'a':4, 'b':4, | |
78 'c':4, 'd':4, 'e':4, 'f':4, | |
79 }[s[0]] | |
80 return int(math.floor(math.log(n, 2))+1) | |
81 | |
82 BaseException = Exception | |
83 import sys | |
84 import traceback | |
85 def formatExceptionTrace(e): | |
86 newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value,
sys.exc_traceback)) | |
87 return newStr | |
88 | 56 |
89 else: | 57 else: |
90 #Jython 2.1 is missing lots of python 2.3 stuff, | 58 # Python 2.6 requires strings instead of bytearrays in a couple places, |
91 #which we have to emulate here: | 59 # so we define this function so it does the conversion if needed. |
92 #NOTE: JYTHON SUPPORT NO LONGER WORKS, DUE TO USE OF GENERATORS. | 60 if sys.version_info < (2,7): |
93 #THIS CODE IS LEFT IN SO THAT ONE JYTHON UPDATES TO 2.2, IT HAS A | 61 def compat26Str(x): return str(x) |
94 #CHANCE OF WORKING AGAIN. | 62 else: |
| 63 def compat26Str(x): return x |
95 | 64 |
96 import java | 65 # So, python 2.6 requires strings, python 3 requires 'bytes', |
97 import jarray | 66 # and python 2.7 can handle bytearrays... |
| 67 def compatHMAC(x): return compat26Str(x) |
98 | 68 |
99 def createByteArraySequence(seq): | 69 def a2b_hex(s): |
100 if isinstance(seq, type("")): #If it's a string, convert | 70 try: |
101 seq = [ord(c) for c in seq] | 71 b = bytearray(binascii.a2b_hex(s)) |
102 return jarray.array(seq, 'h') #use short instead of bytes, cause bytes a
re signed | 72 except Exception as e: |
103 def createByteArrayZeros(howMany): | 73 raise SyntaxError("base16 error: %s" % e) |
104 return jarray.zeros(howMany, 'h') #use short instead of bytes, cause byt
es are signed | 74 return b |
105 def concatArrays(a1, a2): | |
106 l = list(a1)+list(a2) | |
107 return createByteArraySequence(l) | |
108 | 75 |
109 #WAY TOO SLOW - MUST BE REPLACED------------ | 76 def a2b_base64(s): |
110 def bytesToString(bytes): | 77 try: |
111 return "".join([chr(b) for b in bytes]) | 78 b = bytearray(binascii.a2b_base64(s)) |
| 79 except Exception as e: |
| 80 raise SyntaxError("base64 error: %s" % e) |
| 81 return b |
| 82 |
| 83 def b2a_hex(b): |
| 84 return binascii.b2a_hex(compat26Str(b)) |
| 85 |
| 86 def b2a_base64(b): |
| 87 return binascii.b2a_base64(compat26Str(b)) |
| 88 |
| 89 def b2a_base32(b): |
| 90 return base64.b32encode(str(b)) |
112 | 91 |
113 def stringToBytes(s): | 92 import traceback |
114 bytes = createByteArrayZeros(len(s)) | 93 def formatExceptionTrace(e): |
115 for count, c in enumerate(s): | 94 newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys
.exc_traceback)) |
116 bytes[count] = ord(c) | 95 return newStr |
117 return bytes | |
118 #WAY TOO SLOW - MUST BE REPLACED------------ | |
119 | 96 |
120 def numBits(n): | |
121 if n==0: | |
122 return 0 | |
123 n= 1L * n; #convert to long, if it isn't already | |
124 return n.__tojava__(java.math.BigInteger).bitLength() | |
125 | |
126 #Adjust the string to an array of bytes | |
127 def stringToJavaByteArray(s): | |
128 bytes = jarray.zeros(len(s), 'b') | |
129 for count, c in enumerate(s): | |
130 x = ord(c) | |
131 if x >= 128: x -= 256 | |
132 bytes[count] = x | |
133 return bytes | |
134 | |
135 BaseException = java.lang.Exception | |
136 import sys | |
137 import traceback | |
138 def formatExceptionTrace(e): | |
139 newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value,
sys.exc_traceback)) | |
140 return newStr | |
OLD | NEW |