Bläddra i källkod

Convert Crypto to python3 - using 2to3

Oz N Tiram 8 år sedan
förälder
incheckning
36c36b5277
4 ändrade filer med 83 tillägg och 82 borttagningar
  1. 2 2
      pwman/util/crypto/AES.py
  2. 27 26
      pwman/util/crypto/blockcipher.py
  3. 12 12
      pwman/util/crypto/padding.py
  4. 42 42
      pwman/util/crypto/rijndael.py

+ 2 - 2
pwman/util/crypto/AES.py

@@ -24,8 +24,8 @@ IN THE SOFTWARE.
 This code is taken from https://github.com/doegox/python-cryptoplus/
 
 """
-from blockcipher import *
-from rijndael import rijndael
+from .blockcipher import *
+from .rijndael import rijndael
 
 def new(key,mode=MODE_ECB,IV=None,counter=None,segment_size=None):
     """Create a new cipher object

+ 27 - 26
pwman/util/crypto/blockcipher.py

@@ -20,8 +20,9 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 # THE SOFTWARE.
 # =============================================================================
-import util
-import padding
+from . import util
+from . import padding
+import collections
 
 MODE_ECB = 1
 MODE_CBC = 2
@@ -55,36 +56,36 @@ class BlockCipher():
         else:
             self.IV = IV
 
-        if mode <> MODE_XTS:
+        if mode != MODE_XTS:
             self.cipher = cipher_module(self.key,**args)
         if mode == MODE_ECB:
             self.chain = ECB(self.cipher, self.blocksize)
         elif mode == MODE_CBC:
-            if len(self.IV) <> self.blocksize:
-                raise Exception,"the IV length should be %i bytes"%self.blocksize
+            if len(self.IV) != self.blocksize:
+                raise Exception("the IV length should be %i bytes"%self.blocksize)
             self.chain = CBC(self.cipher, self.blocksize,self.IV)
         elif mode == MODE_CFB:
-            if len(self.IV) <> self.blocksize:
-                raise Exception,"the IV length should be %i bytes"%self.blocksize
+            if len(self.IV) != self.blocksize:
+                raise Exception("the IV length should be %i bytes"%self.blocksize)
             if segment_size == None:
-                raise ValueError,"segment size must be defined explicitely for CFB mode"
-            if segment_size > self.blocksize*8 or segment_size%8 <> 0:
+                raise ValueError("segment size must be defined explicitely for CFB mode")
+            if segment_size > self.blocksize*8 or segment_size%8 != 0:
                 # current CFB implementation doesn't support bit level acces => segment_size should be multiple of bytes
-                raise ValueError,"segment size should be a multiple of 8 bits between 8 and %i"%(self.blocksize*8)
+                raise ValueError("segment size should be a multiple of 8 bits between 8 and %i"%(self.blocksize*8))
             self.chain = CFB(self.cipher, self.blocksize,self.IV,segment_size)
         elif mode == MODE_OFB:
-            if len(self.IV) <> self.blocksize:
+            if len(self.IV) != self.blocksize:
                 raise ValueError("the IV length should be %i bytes"%self.blocksize)
             self.chain = OFB(self.cipher, self.blocksize,self.IV)
         elif mode == MODE_CTR:
-            if (counter == None) or  not callable(counter):
-                raise Exception,"Supply a valid counter object for the CTR mode"
+            if (counter == None) or  not isinstance(counter, collections.Callable):
+                raise Exception("Supply a valid counter object for the CTR mode")
             self.chain = CTR(self.cipher,self.blocksize,counter)
         elif mode == MODE_XTS:
-            if self.blocksize <> 16:
-                raise Exception,'XTS only works with blockcipher that have a 128-bit blocksize'
+            if self.blocksize != 16:
+                raise Exception('XTS only works with blockcipher that have a 128-bit blocksize')
             if not(type(key) == tuple and len(key) == 2):
-                raise Exception,'Supply two keys as a tuple when using XTS'
+                raise Exception('Supply two keys as a tuple when using XTS')
             if 'keylen_valid' in dir(self): #wrappers for pycrypto functions don't have this function
              if not self.keylen_valid(key[0]) or  not self.keylen_valid(key[1]):
                 raise ValueError(self.key_error_message)
@@ -93,10 +94,10 @@ class BlockCipher():
             self.chain = XTS(self.cipher, self.cipher2)
         elif mode == MODE_CMAC:
             if self.blocksize not in (8,16):
-                raise Exception,'CMAC only works with blockcipher that have a 64 or 128-bit blocksize'
+                raise Exception('CMAC only works with blockcipher that have a 64 or 128-bit blocksize')
             self.chain = CMAC(self.cipher,self.blocksize,self.IV)
         else:
-                raise Exception,"Unknown chaining mode!"
+                raise Exception("Unknown chaining mode!")
 
     def encrypt(self,plaintext,n=''):
         """Encrypt some plaintext
@@ -249,7 +250,7 @@ class ECB:
         self.cache += data
         if len(self.cache) < self.blocksize:
             return ''
-        for i in xrange(0, len(self.cache)-self.blocksize+1, self.blocksize):
+        for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
             #the only difference between encryption/decryption in the chain is the cipher block
             if ed == 'e':
                 output_blocks.append(self.codebook.encrypt( self.cache[i:i + self.blocksize] ))
@@ -287,7 +288,7 @@ class CBC:
             self.cache += data
             if len(self.cache) < self.blocksize:
                 return ''
-            for i in xrange(0, len(self.cache)-self.blocksize+1, self.blocksize):
+            for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
                 self.IV = self.codebook.encrypt(util.xorstring(self.cache[i:i+self.blocksize],self.IV))
                 encrypted_blocks += self.IV
             self.cache = self.cache[i+self.blocksize:]
@@ -297,7 +298,7 @@ class CBC:
             self.cache += data
             if len(self.cache) < self.blocksize:
                 return ''
-            for i in xrange(0, len(self.cache)-self.blocksize+1, self.blocksize):
+            for i in range(0, len(self.cache)-self.blocksize+1, self.blocksize):
                 plaintext = util.xorstring(self.IV,self.codebook.decrypt(self.cache[i:i + self.blocksize]))
                 self.IV = self.cache[i:i + self.blocksize]
                 decrypted_blocks+=plaintext
@@ -333,7 +334,7 @@ class CFB:
         """
         output = list(data)
 
-        for i in xrange(len(data)):
+        for i in range(len(data)):
             if ed =='e':
                 if len(self.keystream) == 0:
                     block = self.codebook.encrypt(self.IV)
@@ -380,7 +381,7 @@ class OFB:
         blocksize = self.blocksize
         output = list(data)
 
-        for i in xrange(n):
+        for i in range(n):
             if len(self.keystream) == 0: #encrypt a new counter block when the current keystream is fully used
                 self.IV = self.codebook.encrypt(self.IV)
                 self.keystream = list(self.IV)
@@ -420,7 +421,7 @@ class CTR:
         blocksize = self.blocksize
 
         output = list(data)
-        for i in xrange(n):
+        for i in range(n):
             if len(self.keystream) == 0: #encrypt a new counter block when the current keystream is fully used
                 block = self.codebook.encrypt(self.counter())
                 self.keystream = list(block)
@@ -504,7 +505,7 @@ class XTS:
         # if (Cout)
         if self.T >> (8*16):
             #T[0] ^= GF_128_FDBK;
-            self.T = self.T ^ 0x100000000000000000000000000000087L
+            self.T = self.T ^ 0x100000000000000000000000000000087
 
 
 class CMAC:
@@ -520,7 +521,7 @@ class CMAC:
     # TODO: change update behaviour to .update() and .digest() as for all hash modules?
     #       -> other hash functions in pycrypto: calling update, concatenates current input with previous input and hashes everything
     __Rb_dictionary = {64:0x000000000000001b,128:0x00000000000000000000000000000087}
-    supported_blocksizes = __Rb_dictionary.keys()
+    supported_blocksizes = list(__Rb_dictionary.keys())
     def __init__(self,codebook,blocksize,IV):
         # Purpose of init: calculate Lu & Lu2
         #blocksize (in bytes): to select the Rb constant in the dictionary

+ 12 - 12
pwman/util/crypto/padding.py

@@ -54,12 +54,12 @@ def bitPadding (padData, direction, length=None):
             'test'"""
         if direction == PAD:
             if length == None:
-                raise ValueError,"Supply a valid length"
+                raise ValueError("Supply a valid length")
             return __bitPadding(padData, length)
         elif direction == UNPAD:
             return __bitPadding_unpad(padData)
         else:
-            raise ValueError,"Supply a valid direction"
+            raise ValueError("Supply a valid direction")
 
 def __bitPadding (toPad,length):
     padded = toPad + '\x80' + '\x00'*(length - len(toPad)%length -1)
@@ -96,12 +96,12 @@ def zerosPadding (padData, direction, length=None):
             '12345678'"""
         if direction == PAD:
             if length == None:
-                raise ValueError,"Supply a valid length"
+                raise ValueError("Supply a valid length")
             return __zerosPadding(padData, length)
         elif direction == UNPAD:
             return __zerosPadding_unpad(padData)
         else:
-            raise ValueError,"Supply a valid direction"
+            raise ValueError("Supply a valid direction")
 
 def __zerosPadding (toPad, length):
     padLength = (length - len(toPad))%length
@@ -133,12 +133,12 @@ def PKCS7(padData, direction, length=None):
             '12345678'"""
         if direction == PAD:
             if length == None:
-                raise ValueError,"Supply a valid length"
+                raise ValueError("Supply a valid length")
             return __PKCS7(padData, length)
         elif direction == UNPAD:
             return __PKCS7_unpad(padData)
         else:
-            raise ValueError,"Supply a valid direction"
+            raise ValueError("Supply a valid direction")
 
 
 def __PKCS7 (toPad, length):
@@ -155,7 +155,7 @@ def __PKCS7_unpad (padded):
         return padded[:-length]
     else:
         return padded
-        print 'error: padding pattern not recognized'
+        print('error: padding pattern not recognized')
 
 def ANSI_X923 (padData, direction, length=None):
         """Pad a string using ANSI_X923
@@ -180,12 +180,12 @@ def ANSI_X923 (padData, direction, length=None):
             '12345678'"""
         if direction == PAD:
             if length == None:
-                raise ValueError,"Supply a valid length"
+                raise ValueError("Supply a valid length")
             return __ANSI_X923(padData, length)
         elif direction == UNPAD:
             return __ANSI_X923_unpad(padData)
         else:
-            raise ValueError,"Supply a valid direction"
+            raise ValueError("Supply a valid direction")
 
 def __ANSI_X923 (toPad, length):
     bytesToPad = length - len(toPad)%length
@@ -199,7 +199,7 @@ def __ANSI_X923_unpad (padded):
     if padded.count('\x00',-length,-1) == length - 1:
         return padded[:-length]
     else:
-        print 'error: padding pattern not recognized %s' % padded.count('\x00',-length,-1)
+        print('error: padding pattern not recognized %s' % padded.count('\x00',-length,-1))
         return padded
 
 def ISO_10126 (padData, direction, length=None):
@@ -224,12 +224,12 @@ def ISO_10126 (padData, direction, length=None):
             '12345678'"""
         if direction == PAD:
             if length == None:
-                raise ValueError,"Supply a valid length"
+                raise ValueError("Supply a valid length")
             return __ISO_10126(padData, length)
         elif direction == UNPAD:
             return __ISO_10126_unpad(padData)
         else:
-            raise ValueError,"Supply a valid direction"
+            raise ValueError("Supply a valid direction")
 
 def __ISO_10126 (toPad, length):
     bytesToPad = length - len(toPad)%length

+ 42 - 42
pwman/util/crypto/rijndael.py

@@ -89,14 +89,14 @@ A = [[1, 1, 1, 1, 1, 0, 0, 0],
 # produce log and alog tables, needed for multiplying in the
 # field GF(2^m) (generator = 3)
 alog = [1]
-for i in xrange(255):
+for i in range(255):
     j = (alog[-1] << 1) ^ alog[-1]
     if j & 0x100 != 0:
         j ^= 0x11B
     alog.append(j)
 
 log = [0] * 256
-for i in xrange(1, 255):
+for i in range(1, 255):
     log[alog[i]] = i
 
 # multiply two elements of GF(2^m)
@@ -106,29 +106,29 @@ def mul(a, b):
     return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255]
 
 # substitution box based on F^{-1}(x)
-box = [[0] * 8 for i in xrange(256)]
+box = [[0] * 8 for i in range(256)]
 box[1][7] = 1
-for i in xrange(2, 256):
+for i in range(2, 256):
     j = alog[255 - log[i]]
-    for t in xrange(8):
+    for t in range(8):
         box[i][t] = (j >> (7 - t)) & 0x01
 
 B = [0, 1, 1, 0, 0, 0, 1, 1]
 
 # affine transform:  box[i] <- B + A*box[i]
-cox = [[0] * 8 for i in xrange(256)]
-for i in xrange(256):
-    for t in xrange(8):
+cox = [[0] * 8 for i in range(256)]
+for i in range(256):
+    for t in range(8):
         cox[i][t] = B[t]
-        for j in xrange(8):
+        for j in range(8):
             cox[i][t] ^= A[t][j] * box[i][j]
 
 # S-boxes and inverse S-boxes
 S =  [0] * 256
 Si = [0] * 256
-for i in xrange(256):
+for i in range(256):
     S[i] = cox[i][0] << 7
-    for t in xrange(1, 8):
+    for t in range(1, 8):
         S[i] ^= cox[i][t] << (7-t)
     Si[S[i] & 0xFF] = i
 
@@ -138,36 +138,36 @@ G = [[2, 1, 1, 3],
     [1, 3, 2, 1],
     [1, 1, 3, 2]]
 
-AA = [[0] * 8 for i in xrange(4)]
+AA = [[0] * 8 for i in range(4)]
 
-for i in xrange(4):
-    for j in xrange(4):
+for i in range(4):
+    for j in range(4):
         AA[i][j] = G[i][j]
         AA[i][i+4] = 1
 
-for i in xrange(4):
+for i in range(4):
     pivot = AA[i][i]
     if pivot == 0:
         t = i + 1
         while AA[t][i] == 0 and t < 4:
             t += 1
             assert t != 4, 'G matrix must be invertible'
-            for j in xrange(8):
+            for j in range(8):
                 AA[i][j], AA[t][j] = AA[t][j], AA[i][j]
             pivot = AA[i][i]
-    for j in xrange(8):
+    for j in range(8):
         if AA[i][j] != 0:
             AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255]
-    for t in xrange(4):
+    for t in range(4):
         if i != t:
-            for j in xrange(i+1, 8):
+            for j in range(i+1, 8):
                 AA[t][j] ^= mul(AA[i][j], AA[t][i])
             AA[t][i] = 0
 
-iG = [[0] * 4 for i in xrange(4)]
+iG = [[0] * 4 for i in range(4)]
 
-for i in xrange(4):
-    for j in xrange(4):
+for i in range(4):
+    for j in range(4):
         iG[i][j] = AA[i][j + 4]
 
 def mul4(a, bs):
@@ -193,7 +193,7 @@ U2 = []
 U3 = []
 U4 = []
 
-for t in xrange(256):
+for t in range(256):
     s = S[t]
     T1.append(mul4(s, G[0]))
     T2.append(mul4(s, G[1]))
@@ -214,7 +214,7 @@ for t in xrange(256):
 # round constants
 rcon = [1]
 r = 1
-for t in xrange(1, 30):
+for t in range(1, 30):
     r = mul(2, r)
     rcon.append(r)
 
@@ -247,15 +247,15 @@ class rijndael:
         ROUNDS = num_rounds[len(key)][block_size]
         BC = block_size / 4
         # encryption round keys
-        Ke = [[0] * BC for i in xrange(ROUNDS + 1)]
+        Ke = [[0] * BC for i in range(ROUNDS + 1)]
         # decryption round keys
-        Kd = [[0] * BC for i in xrange(ROUNDS + 1)]
+        Kd = [[0] * BC for i in range(ROUNDS + 1)]
         ROUND_KEY_COUNT = (ROUNDS + 1) * BC
         KC = len(key) / 4
 
         # copy user material bytes into temporary ints
         tk = []
-        for i in xrange(0, KC):
+        for i in range(0, KC):
             tk.append((ord(key[i * 4]) << 24) | (ord(key[i * 4 + 1]) << 16) |
                 (ord(key[i * 4 + 2]) << 8) | ord(key[i * 4 + 3]))
 
@@ -279,17 +279,17 @@ class rijndael:
                      (rcon[rconpointer]    & 0xFF) << 24
             rconpointer += 1
             if KC != 8:
-                for i in xrange(1, KC):
+                for i in range(1, KC):
                     tk[i] ^= tk[i-1]
             else:
-                for i in xrange(1, KC / 2):
+                for i in range(1, KC / 2):
                     tk[i] ^= tk[i-1]
                 tt = tk[KC / 2 - 1]
                 tk[KC / 2] ^= (S[ tt        & 0xFF] & 0xFF)       ^ \
                               (S[(tt >>  8) & 0xFF] & 0xFF) <<  8 ^ \
                               (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \
                               (S[(tt >> 24) & 0xFF] & 0xFF) << 24
-                for i in xrange(KC / 2 + 1, KC):
+                for i in range(KC / 2 + 1, KC):
                     tk[i] ^= tk[i-1]
             # copy values into round key arrays
             j = 0
@@ -299,8 +299,8 @@ class rijndael:
                 j += 1
                 t += 1
         # inverse MixColumn where needed
-        for r in xrange(1, ROUNDS):
-            for j in xrange(BC):
+        for r in range(1, ROUNDS):
+            for j in range(BC):
                 tt = Kd[r][j]
                 Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \
                            U2[(tt >> 16) & 0xFF] ^ \
@@ -329,14 +329,14 @@ class rijndael:
         # temporary work array
         t = []
         # plaintext to ints + key
-        for i in xrange(BC):
+        for i in range(BC):
             t.append((ord(plaintext[i * 4    ]) << 24 |
                       ord(plaintext[i * 4 + 1]) << 16 |
                       ord(plaintext[i * 4 + 2]) <<  8 |
                       ord(plaintext[i * 4 + 3])        ) ^ Ke[0][i])
         # apply round transforms
-        for r in xrange(1, ROUNDS):
-            for i in xrange(BC):
+        for r in range(1, ROUNDS):
+            for i in range(BC):
                 a[i] = (T1[(t[ i           ] >> 24) & 0xFF] ^
                         T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^
                         T3[(t[(i + s2) % BC] >>  8) & 0xFF] ^
@@ -344,13 +344,13 @@ class rijndael:
             t = copy.copy(a)
         # last round is special
         result = []
-        for i in xrange(BC):
+        for i in range(BC):
             tt = Ke[ROUNDS][i]
             result.append((S[(t[ i           ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)
             result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)
             result.append((S[(t[(i + s2) % BC] >>  8) & 0xFF] ^ (tt >>  8)) & 0xFF)
             result.append((S[ t[(i + s3) % BC]        & 0xFF] ^  tt       ) & 0xFF)
-        return string.join(map(chr, result), '')
+        return string.join(list(map(chr, result)), '')
 
     def decrypt(self, ciphertext):
         if len(ciphertext) != self.block_size:
@@ -372,14 +372,14 @@ class rijndael:
         # temporary work array
         t = [0] * BC
         # ciphertext to ints + key
-        for i in xrange(BC):
+        for i in range(BC):
             t[i] = (ord(ciphertext[i * 4    ]) << 24 |
                     ord(ciphertext[i * 4 + 1]) << 16 |
                     ord(ciphertext[i * 4 + 2]) <<  8 |
                     ord(ciphertext[i * 4 + 3])        ) ^ Kd[0][i]
         # apply round transforms
-        for r in xrange(1, ROUNDS):
-            for i in xrange(BC):
+        for r in range(1, ROUNDS):
+            for i in range(BC):
                 a[i] = (T5[(t[ i           ] >> 24) & 0xFF] ^
                         T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^
                         T7[(t[(i + s2) % BC] >>  8) & 0xFF] ^
@@ -387,13 +387,13 @@ class rijndael:
             t = copy.copy(a)
         # last round is special
         result = []
-        for i in xrange(BC):
+        for i in range(BC):
             tt = Kd[ROUNDS][i]
             result.append((Si[(t[ i           ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF)
             result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF)
             result.append((Si[(t[(i + s2) % BC] >>  8) & 0xFF] ^ (tt >>  8)) & 0xFF)
             result.append((Si[ t[(i + s3) % BC]        & 0xFF] ^  tt       ) & 0xFF)
-        return string.join(map(chr, result), '')
+        return string.join(list(map(chr, result)), '')
 
 def encrypt(key, block):
     return rijndael(key, len(block)).encrypt(block)