--- lib/Crypto/Protocol/AllOrNothing.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/Protocol/AllOrNothing.py @@ -48,6 +48,7 @@ import operator import sys from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.Util.py3compat import * +from functools import reduce def isInt(x): test = 0 @@ -186,11 +187,11 @@ class AllOrNothing: # better have at least 2 blocks, for the padbytes package and the hash # block accumulator if len(blocks) < 2: - raise ValueError, "List must be at least length 2." + raise ValueError("List must be at least length 2.") # blocks is a list of strings. We need to deal with them as long # integers - blocks = map(bytes_to_long, blocks) + blocks = list(map(bytes_to_long, blocks)) # Calculate the well-known key, to which the hash blocks are # encrypted, and create the hash cipher. @@ -271,15 +272,15 @@ Where: def usage(code, msg=None): if msg: - print msg - print usagemsg % {'program': sys.argv[0], - 'ciphermodule': ciphermodule} + print(msg) + print(usagemsg % {'program': sys.argv[0], + 'ciphermodule': ciphermodule}) sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 'c:l', ['cipher=', 'aslong']) - except getopt.error, msg: + except getopt.error as msg: usage(1, msg) if args: @@ -297,23 +298,23 @@ Where: module = __import__('Crypto.Cipher.'+ciphermodule, None, None, ['new']) x = AllOrNothing(module) - print 'Original text:\n==========' - print __doc__ - print '==========' + print('Original text:\n==========') + print(__doc__) + print('==========') msgblocks = x.digest(b(__doc__)) - print 'message blocks:' - for i, blk in zip(range(len(msgblocks)), msgblocks): + print('message blocks:') + for i, blk in zip(list(range(len(msgblocks))), msgblocks): # base64 adds a trailing newline - print ' %3d' % i, + print(' %3d' % i, end=' ') if aslong: - print bytes_to_long(blk) + print(bytes_to_long(blk)) else: - print base64.encodestring(blk)[:-1] + print(base64.encodestring(blk)[:-1]) # # get a new undigest-only object so there's no leakage y = AllOrNothing(module) text = y.undigest(msgblocks) if text == b(__doc__): - print 'They match!' + print('They match!') else: - print 'They differ!' + print('They differ!') --- lib/Crypto/Protocol/Chaffing.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/Protocol/Chaffing.py @@ -106,9 +106,9 @@ class Chaff: """ if not (0.0<=factor<=1.0): - raise ValueError, "'factor' must be between 0.0 and 1.0" + raise ValueError("'factor' must be between 0.0 and 1.0") if blocksper < 0: - raise ValueError, "'blocksper' must be zero or more" + raise ValueError("'blocksper' must be zero or more") self.__factor = factor self.__blocksper = blocksper @@ -139,8 +139,8 @@ class Chaff: # number of chaff blocks to add per message block that is being # chaffed. count = len(blocks) * self.__factor - blocksper = range(self.__blocksper) - for i, wheat in zip(range(len(blocks)), blocks): + blocksper = list(range(self.__blocksper)) + for i, wheat in zip(list(range(len(blocks))), blocks): # it shouldn't matter which of the n blocks we add chaff to, so for # ease of implementation, we'll just add them to the first count # blocks @@ -185,9 +185,9 @@ abolish it, and to institute new Government, laying it principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. """ - print 'Original text:\n==========' - print text - print '==========' + print('Original text:\n==========') + print(text) + print('==========') # first transform the text into packets blocks = [] ; size = 40 @@ -195,7 +195,7 @@ likely to effect their Safety and Happiness. blocks.append( text[i:i+size] ) # now get MACs for all the text blocks. The key is obvious... - print 'Calculating MACs...' + print('Calculating MACs...') from Crypto.Hash import HMAC, SHA key = 'Jefferson' macs = [HMAC.new(key, block, digestmod=SHA).digest() @@ -205,13 +205,13 @@ likely to effect their Safety and Happiness. # put these into a form acceptable as input to the chaffing procedure source = [] - m = zip(range(len(blocks)), blocks, macs) - print m + m = list(zip(list(range(len(blocks))), blocks, macs)) + print(m) for i, data, mac in m: source.append((i, data, mac)) # now chaff these - print 'Adding chaff...' + print('Adding chaff...') c = Chaff(factor=0.5, blocksper=2) chaffed = c.chaff(source) @@ -221,7 +221,7 @@ likely to effect their Safety and Happiness. # the chaff wheat = [] - print 'chaffed message blocks:' + print('chaffed message blocks:') for i, data, mac in chaffed: # do the authentication h = HMAC.new(key, data, digestmod=SHA) @@ -232,14 +232,14 @@ likely to effect their Safety and Happiness. else: tag = ' ' # base64 adds a trailing newline - print tag, '%3d' % i, \ - repr(data), encodestring(mac)[:-1] + print(tag, '%3d' % i, \ + repr(data), encodestring(mac)[:-1]) # now decode the message packets and check it against the original text - print 'Undigesting wheat...' + print('Undigesting wheat...') # PY3K: This is meant to be text, do not change to bytes (data) newtext = "".join(wheat) if newtext == text: - print 'They match!' + print('They match!') else: - print 'They differ!' + print('They differ!') --- lib/Crypto/PublicKey/_DSA.py.orig 2013-10-14 21:38:10 UTC +++ lib/Crypto/PublicKey/_DSA.py @@ -50,7 +50,7 @@ def generateQ(randfunc): q=q*256+c while (not isPrime(q)): q=q+2 - if pow(2,159L) < q < pow(2,160L): + if pow(2,159) < q < pow(2,160): return S, q raise RuntimeError('Bad q value generated') @@ -80,7 +80,7 @@ def generate_py(bits, randfunc, progress_func=None): V[k]=bytes_to_long(SHA.new(S+bstr(N)+bstr(k)).digest()) W=V[n] % powb for k in range(n-1, -1, -1): - W=(W<<160L)+V[k] + W=(W<<160)+V[k] X=W+powL1 p=X-(X%(2*obj.q)-1) if powL1<=p and isPrime(p): --- lib/Crypto/PublicKey/_RSA.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/PublicKey/_RSA.py @@ -37,12 +37,12 @@ def generate_py(bits, randfunc, progress_func=None, e= if present, to display the progress of the key generation. """ obj=RSAobj() - obj.e = long(e) + obj.e = int(e) # Generate the prime factors of n if progress_func: progress_func('p,q\n') - p = q = 1L + p = q = 1 while number.size(p*q) < bits: # Note that q might be one bit longer than p if somebody specifies an odd # number of bits for the key. (Why would anyone do that? You don't get --- lib/Crypto/PublicKey/_slowmath.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/PublicKey/_slowmath.py @@ -81,12 +81,12 @@ class _RSAKey(object): def rsa_construct(n, e, d=None, p=None, q=None, u=None): """Construct an RSAKey object""" - assert isinstance(n, long) - assert isinstance(e, long) - assert isinstance(d, (long, type(None))) - assert isinstance(p, (long, type(None))) - assert isinstance(q, (long, type(None))) - assert isinstance(u, (long, type(None))) + assert isinstance(n, int) + assert isinstance(e, int) + assert isinstance(d, (int, type(None))) + assert isinstance(p, (int, type(None))) + assert isinstance(q, (int, type(None))) + assert isinstance(u, (int, type(None))) obj = _RSAKey() obj.n = n obj.e = e @@ -151,7 +151,7 @@ class _DSAKey(object): # SECURITY TODO - We _should_ be computing SHA1(m), but we don't because that's the API. if not self.has_private(): raise TypeError("No private key") - if not (1L < k < self.q): + if not (1 < k < self.q): raise ValueError("k is not between 2 and q-1") inv_k = inverse(k, self.q) # Compute k**-1 mod q r = pow(self.g, k, self.p) % self.q # r = (g**k mod p) mod q @@ -169,11 +169,11 @@ class _DSAKey(object): return v == r def dsa_construct(y, g, p, q, x=None): - assert isinstance(y, long) - assert isinstance(g, long) - assert isinstance(p, long) - assert isinstance(q, long) - assert isinstance(x, (long, type(None))) + assert isinstance(y, int) + assert isinstance(g, int) + assert isinstance(p, int) + assert isinstance(q, int) + assert isinstance(x, (int, type(None))) obj = _DSAKey() obj.y = y obj.g = g --- lib/Crypto/PublicKey/RSA.py.orig 2013-10-14 21:38:10 UTC +++ lib/Crypto/PublicKey/RSA.py @@ -288,7 +288,7 @@ class _RSAobj(pubkey.pubkey): self.implementation = RSAImplementation() t = [] for k in self.keydata: - if not d.has_key(k): + if k not in d: break t.append(d[k]) self.key = self.implementation._math.rsa_construct(*tuple(t)) @@ -582,7 +582,7 @@ class RSAImplementation(object): if privateKey.isType('OCTET STRING'): return self._importKeyDER(privateKey.payload) - except ValueError, IndexError: + except ValueError as IndexError: pass raise ValueError("RSA key format is not supported") --- lib/Crypto/Random/Fortuna/FortunaAccumulator.py.orig 2013-10-14 21:38:10 UTC +++ lib/Crypto/Random/Fortuna/FortunaAccumulator.py @@ -34,9 +34,9 @@ import time import warnings from Crypto.pct_warnings import ClockRewindWarning -import SHAd256 +from . import SHAd256 -import FortunaGenerator +from . import FortunaGenerator class FortunaPool(object): """Fortuna pool type @@ -89,7 +89,7 @@ def which_pools(r): retval.append(i) else: break # optimization. once this fails, it always fails - mask = (mask << 1) | 1L + mask = (mask << 1) | 1 return retval class FortunaAccumulator(object): --- lib/Crypto/Random/OSRNG/posix.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/Random/OSRNG/posix.py @@ -29,7 +29,7 @@ import errno import os import stat -from rng_base import BaseRNG +from .rng_base import BaseRNG from Crypto.Util.py3compat import b class DevURandomRNG(BaseRNG): @@ -63,7 +63,7 @@ class DevURandomRNG(BaseRNG): while len(data) < N: try: d = self.__file.read(N - len(data)) - except IOError, e: + except IOError as e: # read(2) has been interrupted by a signal; redo the read if e.errno == errno.EINTR: continue --- lib/Crypto/Random/random.py.orig 2013-10-14 21:38:10 UTC +++ lib/Crypto/Random/random.py @@ -47,7 +47,7 @@ class StrongRandom(object): """Return a python long integer with k random bits.""" if self._randfunc is None: self._randfunc = Random.new().read - mask = (1L << k) - 1 + mask = (1 << k) - 1 return mask & bytes_to_long(self._randfunc(ceil_div(k, 8))) def randrange(self, *args): @@ -64,9 +64,9 @@ class StrongRandom(object): step = 1 else: raise TypeError("randrange expected at most 3 arguments, got %d" % (len(args),)) - if (not isinstance(start, (int, long)) - or not isinstance(stop, (int, long)) - or not isinstance(step, (int, long))): + if (not isinstance(start, int) + or not isinstance(stop, int) + or not isinstance(step, int)): raise TypeError("randrange requires integer arguments") if step == 0: raise ValueError("randrange step argument must not be zero") @@ -86,7 +86,7 @@ class StrongRandom(object): def randint(self, a, b): """Return a random integer N such that a <= N <= b.""" - if not isinstance(a, (int, long)) or not isinstance(b, (int, long)): + if not isinstance(a, int) or not isinstance(b, int): raise TypeError("randint requires integer arguments") N = self.randrange(a, b+1) assert a <= N <= b @@ -108,7 +108,7 @@ class StrongRandom(object): # Choose a random item (without replacement) until all the items have been # chosen. - for i in xrange(len(x)): + for i in range(len(x)): x[i] = items.pop(self.randrange(len(items))) def sample(self, population, k): @@ -120,9 +120,9 @@ class StrongRandom(object): retval = [] selected = {} # we emulate a set using a dict here - for i in xrange(k): + for i in range(k): r = None - while r is None or selected.has_key(r): + while r is None or r in selected: r = self.randrange(num_choices) retval.append(population[r]) selected[r] = 1 --- lib/Crypto/SelfTest/Cipher/common.py.orig 2013-10-14 21:38:10 UTC +++ lib/Crypto/SelfTest/Cipher/common.py @@ -97,9 +97,9 @@ class CipherSelfTest(unittest.TestCase): from Crypto.Util import Counter ctr_class = _extract(params, 'ctr_class', Counter.new) ctr_params = _extract(params, 'ctr_params', {}).copy() - if ctr_params.has_key('prefix'): ctr_params['prefix'] = a2b_hex(b(ctr_params['prefix'])) - if ctr_params.has_key('suffix'): ctr_params['suffix'] = a2b_hex(b(ctr_params['suffix'])) - if not ctr_params.has_key('nbits'): + if 'prefix' in ctr_params: ctr_params['prefix'] = a2b_hex(b(ctr_params['prefix'])) + if 'suffix' in ctr_params: ctr_params['suffix'] = a2b_hex(b(ctr_params['suffix'])) + if 'nbits' not in ctr_params: ctr_params['nbits'] = 8*(self.module.block_size - len(ctr_params.get('prefix', '')) - len(ctr_params.get('suffix', ''))) params['counter'] = ctr_class(**ctr_params) @@ -202,7 +202,7 @@ class CTRWraparoundTest(unittest.TestCase): for disable_shortcut in (0, 1): # (False, True) Test CTR-mode shortcut and PyObject_CallObject code paths for little_endian in (0, 1): # (False, True) Test both endiannesses - ctr = Counter.new(8*self.module.block_size, initial_value=2L**(8*self.module.block_size)-1, little_endian=little_endian, disable_shortcut=disable_shortcut) + ctr = Counter.new(8*self.module.block_size, initial_value=2**(8*self.module.block_size)-1, little_endian=little_endian, disable_shortcut=disable_shortcut) cipher = self.module.new(a2b_hex(self.key), self.module.MODE_CTR, counter=ctr) block = b("\x00") * self.module.block_size cipher.encrypt(block) @@ -347,12 +347,12 @@ def make_block_tests(module, module_name, test_data): tests.append(CipherStreamingSelfTest(module, params)) # When using CTR mode, test the non-shortcut code path. - if p_mode == 'CTR' and not params.has_key('ctr_class'): + if p_mode == 'CTR' and 'ctr_class' not in params: params2 = params.copy() params2['description'] += " (shortcut disabled)" ctr_params2 = params.get('ctr_params', {}).copy() params2['ctr_params'] = ctr_params2 - if not params2['ctr_params'].has_key('disable_shortcut'): + if 'disable_shortcut' not in params2['ctr_params']: params2['ctr_params']['disable_shortcut'] = 1 tests.append(CipherSelfTest(module, params2)) return tests --- lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py @@ -41,7 +41,7 @@ def t2b(t): """Convert a text string with bytes in hex form to a byte string""" clean = b(rws(t)) if len(clean)%2 == 1: - print clean + print(clean) raise ValueError("Even number of characters expected") return a2b_hex(clean) @@ -154,7 +154,7 @@ HKukWBcq9f/UOmS0oEhai/6g+Uf7VHJdWaeO5LzuvwU= def testEncryptVerify1(self): # Encrypt/Verify messages of length [0..RSAlen-11] # and therefore padding [8..117] - for pt_len in xrange(0,128-11+1): + for pt_len in range(0,128-11+1): pt = self.rng(pt_len) cipher = PKCS.new(self.key1024) ct = cipher.encrypt(pt) --- lib/Crypto/SelfTest/PublicKey/test_ElGamal.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/SelfTest/PublicKey/test_ElGamal.py @@ -105,8 +105,8 @@ class ElGamalTest(unittest.TestCase): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) ct = key.encrypt(d['pt'], d['k']) - self.assertEquals(ct[0], d['ct1']) - self.assertEquals(ct[1], d['ct2']) + self.assertEqual(ct[0], d['ct1']) + self.assertEqual(ct[1], d['ct2']) def test_decryption(self): for tv in self.tve: @@ -114,7 +114,7 @@ class ElGamalTest(unittest.TestCase): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) pt = key.decrypt((d['ct1'], d['ct2'])) - self.assertEquals(pt, d['pt']) + self.assertEqual(pt, d['pt']) def test_signing(self): for tv in self.tvs: @@ -122,8 +122,8 @@ class ElGamalTest(unittest.TestCase): d = self.convert_tv(tv, as_longs) key = ElGamal.construct(d['key']) sig1, sig2 = key.sign(d['h'], d['k']) - self.assertEquals(sig1, d['sig1']) - self.assertEquals(sig2, d['sig2']) + self.assertEqual(sig1, d['sig1']) + self.assertEqual(sig2, d['sig2']) def test_verification(self): for tv in self.tvs: @@ -132,17 +132,17 @@ class ElGamalTest(unittest.TestCase): key = ElGamal.construct(d['key']) # Positive test res = key.verify( d['h'], (d['sig1'],d['sig2']) ) - self.failUnless(res) + self.assertTrue(res) # Negative test res = key.verify( d['h'], (d['sig1']+1,d['sig2']) ) - self.failIf(res) + self.assertFalse(res) def convert_tv(self, tv, as_longs=0): """Convert a test vector from textual form (hexadecimal ascii to either integers or byte strings.""" key_comps = 'p','g','y','x' tv2 = {} - for c in tv.keys(): + for c in list(tv.keys()): tv2[c] = a2b_hex(tv[c]) if as_longs or c in key_comps or c in ('sig1','sig2'): tv2[c] = bytes_to_long(tv2[c]) @@ -163,41 +163,41 @@ class ElGamalTest(unittest.TestCase): def _check_private_key(self, elgObj): # Check capabilities - self.failUnless(elgObj.has_private()) - self.failUnless(elgObj.can_sign()) - self.failUnless(elgObj.can_encrypt()) + self.assertTrue(elgObj.has_private()) + self.assertTrue(elgObj.can_sign()) + self.assertTrue(elgObj.can_encrypt()) # Sanity check key data - self.failUnless(1 (1L << bits-1)-1, 1) - self.assertEqual(x < (1L << bits), 1) + self.assertEqual(x > (1 << bits-1)-1, 1) + self.assertEqual(x < (1 << bits), 1) e = 2**16+1 x = number.getStrongPrime(bits, e) self.assertEqual(number.GCD(x-1, e), 1) self.assertNotEqual(x % 2, 0) - self.assertEqual(x > (1L << bits-1)-1, 1) - self.assertEqual(x < (1L << bits), 1) + self.assertEqual(x > (1 << bits-1)-1, 1) + self.assertEqual(x < (1 << bits), 1) e = 2**16+2 x = number.getStrongPrime(bits, e) self.assertEqual(number.GCD((x-1)>>1, e), 1) self.assertNotEqual(x % 2, 0) - self.assertEqual(x > (1L << bits-1)-1, 1) - self.assertEqual(x < (1L << bits), 1) + self.assertEqual(x > (1 << bits-1)-1, 1) + self.assertEqual(x < (1 << bits), 1) def test_isPrime(self): """Util.number.isPrime""" @@ -258,28 +258,28 @@ class MiscTests(unittest.TestCase): self.assertEqual(number.isPrime(2), True) self.assertEqual(number.isPrime(3), True) self.assertEqual(number.isPrime(4), False) - self.assertEqual(number.isPrime(2L**1279-1), True) - self.assertEqual(number.isPrime(-(2L**1279-1)), False) # Regression test: negative numbers should not be prime + self.assertEqual(number.isPrime(2**1279-1), True) + self.assertEqual(number.isPrime(-(2**1279-1)), False) # Regression test: negative numbers should not be prime # test some known gmp pseudo-primes taken from # http://www.trnicely.net/misc/mpzspsp.html for composite in (43 * 127 * 211, 61 * 151 * 211, 15259 * 30517, - 346141L * 692281L, 1007119L * 2014237L, 3589477L * 7178953L, - 4859419L * 9718837L, 2730439L * 5460877L, - 245127919L * 490255837L, 963939391L * 1927878781L, - 4186358431L * 8372716861L, 1576820467L * 3153640933L): - self.assertEqual(number.isPrime(long(composite)), False) + 346141 * 692281, 1007119 * 2014237, 3589477 * 7178953, + 4859419 * 9718837, 2730439 * 5460877, + 245127919 * 490255837, 963939391 * 1927878781, + 4186358431 * 8372716861, 1576820467 * 3153640933): + self.assertEqual(number.isPrime(int(composite)), False) def test_size(self): self.assertEqual(number.size(2),2) self.assertEqual(number.size(3),2) self.assertEqual(number.size(0xa2),8) self.assertEqual(number.size(0xa2ba40),8*3) - self.assertEqual(number.size(0xa2ba40ee07e3b2bd2f02ce227f36a195024486e49c19cb41bbbdfbba98b22b0e577c2eeaffa20d883a76e65e394c69d4b3c05a1e8fadda27edb2a42bc000fe888b9b32c22d15add0cd76b3e7936e19955b220dd17d4ea904b1ec102b2e4de7751222aa99151024c7cb41cc5ea21d00eeb41f7c800834d2c6e06bce3bce7ea9a5L), 1024) + self.assertEqual(number.size(0xa2ba40ee07e3b2bd2f02ce227f36a195024486e49c19cb41bbbdfbba98b22b0e577c2eeaffa20d883a76e65e394c69d4b3c05a1e8fadda27edb2a42bc000fe888b9b32c22d15add0cd76b3e7936e19955b220dd17d4ea904b1ec102b2e4de7751222aa99151024c7cb41cc5ea21d00eeb41f7c800834d2c6e06bce3bce7ea9a5), 1024) def test_negative_number_roundtrip_mpzToLongObj_longObjToMPZ(self): """Test that mpzToLongObj and longObjToMPZ (internal functions) roundtrip negative numbers correctly.""" - n = -100000000000000000000000000000000000L - e = 2L + n = -100000000000000000000000000000000000 + e = 2 k = number._fastmath.rsa_construct(n, e) self.assertEqual(n, k.n) self.assertEqual(e, k.e) --- lib/Crypto/Util/_number_new.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/Util/_number_new.py @@ -37,11 +37,11 @@ def ceil_shift(n, b): This is done by right-shifting n by b bits and incrementing the result by 1 if any '1' bits were shifted out. """ - if not isinstance(n, (int, long)) or not isinstance(b, (int, long)): + if not isinstance(n, int) or not isinstance(b, int): raise TypeError("unsupported operand type(s): %r and %r" % (type(n).__name__, type(b).__name__)) assert n >= 0 and b >= 0 # I haven't tested or even thought about negative values - mask = (1L << b) - 1 + mask = (1 << b) - 1 if n & mask: return (n >> b) + 1 else: @@ -50,7 +50,7 @@ def ceil_shift(n, b): def ceil_div(a, b): """Return ceil(a / b) without performing any floating-point operations.""" - if not isinstance(a, (int, long)) or not isinstance(b, (int, long)): + if not isinstance(a, int) or not isinstance(b, int): raise TypeError("unsupported operand type(s): %r and %r" % (type(a).__name__, type(b).__name__)) (q, r) = divmod(a, b) @@ -60,7 +60,7 @@ def ceil_div(a, b): return q def floor_div(a, b): - if not isinstance(a, (int, long)) or not isinstance(b, (int, long)): + if not isinstance(a, int) or not isinstance(b, int): raise TypeError("unsupported operand type(s): %r and %r" % (type(a).__name__, type(b).__name__)) (q, r) = divmod(a, b) @@ -72,10 +72,10 @@ def exact_log2(num): If no such integer exists, this function raises ValueError. """ - if not isinstance(num, (int, long)): + if not isinstance(num, int): raise TypeError("unsupported operand type: %r" % (type(num).__name__,)) - n = long(num) + n = int(num) if n <= 0: raise ValueError("cannot compute logarithm of non-positive number") @@ -87,7 +87,7 @@ def exact_log2(num): n >>= 1 i -= 1 - assert num == (1L << i) + assert num == (1 << i) return i def exact_div(p, d, allow_divzero=False): @@ -101,7 +101,7 @@ def exact_div(p, d, allow_divzero=False): unless allow_divzero is true (default: False). """ - if not isinstance(p, (int, long)) or not isinstance(d, (int, long)): + if not isinstance(p, int) or not isinstance(d, int): raise TypeError("unsupported operand type(s): %r and %r" % (type(p).__name__, type(d).__name__)) if d == 0 and allow_divzero: --- lib/Crypto/Util/number.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/Util/number.py @@ -32,7 +32,7 @@ import math import sys from Crypto.Util.py3compat import * -bignum = long +bignum = int try: from Crypto.PublicKey import _fastmath except ImportError: @@ -57,7 +57,7 @@ if _fastmath is not None and not _fastmath.HAVE_DECL_M _warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning) # New functions -from _number_new import * +from ._number_new import * # Commented out and replaced with faster versions below ## def long2str(n): @@ -136,7 +136,7 @@ def getRandomNBitInteger(N, randfunc=None): the future. """ value = getRandomInteger (N-1, randfunc) - value |= 2L ** (N-1) # Ensure high bit is set + value |= 2 ** (N-1) # Ensure high bit is set assert size(value) >= N return value @@ -153,8 +153,8 @@ def inverse(u, v): """inverse(u:long, v:long):long Return the inverse of u mod v. """ - u3, v3 = long(u), long(v) - u1, v1 = 1L, 0L + u3, v3 = int(u), int(v) + u1, v1 = 1, 0 while v3 > 0: q=divmod(u3, v3)[0] u1, v1 = v1, u1 - v1*q @@ -208,7 +208,7 @@ def _rabinMillerTest(n, rounds, randfunc=None): tested = [] # we need to do at most n-2 rounds. - for i in xrange (min (rounds, n-2)): + for i in range (min (rounds, n-2)): # randomly choose a < n and make sure it hasn't been tested yet a = getRandomRange (2, n, randfunc) while a in tested: @@ -219,7 +219,7 @@ def _rabinMillerTest(n, rounds, randfunc=None): if z == 1 or z == n_1: continue composite = 1 - for r in xrange (b): + for r in range (b): z = (z * z) % n if z == 1: return 0 @@ -261,7 +261,7 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, r # Use the accelerator if available if _fastmath is not None: - return _fastmath.getStrongPrime(long(N), long(e), false_positive_prob, + return _fastmath.getStrongPrime(int(N), int(e), false_positive_prob, randfunc) if (N < 512) or ((N % 128) != 0): @@ -275,9 +275,9 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, r x = (N - 512) >> 7; # We need to approximate the sqrt(2) in the lower_bound by an integer # expression because floating point math overflows with these numbers - lower_bound = divmod(14142135623730950489L * (2L ** (511 + 128*x)), - 10000000000000000000L)[0] - upper_bound = (1L << (512 + 128*x)) - 1 + lower_bound = divmod(14142135623730950489 * (2 ** (511 + 128*x)), + 10000000000000000000)[0] + upper_bound = (1 << (512 + 128*x)) - 1 # Randomly choose X in calculated range X = getRandomRange (lower_bound, upper_bound, randfunc) @@ -291,7 +291,7 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, r # sieve the field for prime in sieve_base: offset = y % prime - for j in xrange ((prime - offset) % prime, len (field), prime): + for j in range ((prime - offset) % prime, len (field), prime): field[j] = 1 # look for suitable p[i] starting at y @@ -347,7 +347,7 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, r X += increment # abort when X has more bits than requested # TODO: maybe we shouldn't abort but rather start over. - if X >= 1L << N: + if X >= 1 << N: raise RuntimeError ("Couln't find prime in field. " "Developer: Increase field_size") return X @@ -365,7 +365,7 @@ def isPrime(N, false_positive_prob=1e-6, randfunc=None If randfunc is omitted, then Random.new().read is used. """ if _fastmath is not None: - return _fastmath.isPrime(long(N), false_positive_prob, randfunc) + return _fastmath.isPrime(int(N), false_positive_prob, randfunc) if N < 3 or N & 1 == 0: return N == 2 @@ -394,10 +394,10 @@ def long_to_bytes(n, blocksize=0): """ # after much testing, this algorithm was deemed to be the fastest s = b('') - n = long(n) + n = int(n) pack = struct.pack while n > 0: - s = pack('>I', n & 0xffffffffL) + s + s = pack('>I', n & 0xffffffff) + s n = n >> 32 # strip off leading zeros for i in range(len(s)): @@ -420,7 +420,7 @@ def bytes_to_long(s): This is (essentially) the inverse of long_to_bytes(). """ - acc = 0L + acc = 0 unpack = struct.unpack length = len(s) if length % 4: --- lib/Crypto/Util/RFC1751.py.orig 2012-05-24 12:55:30 UTC +++ lib/Crypto/Util/RFC1751.py @@ -29,6 +29,7 @@ __revision__ = "$Id$" import binascii from Crypto.Util.py3compat import * +from functools import reduce binary={0:'0000', 1:'0001', 2:'0010', 3:'0011', 4:'0100', 5:'0101', 6:'0110', 7:'0111', 8:'1000', 9:'1001', 10:'1010', 11:'1011', @@ -36,8 +37,8 @@ binary={0:'0000', 1:'0001', 2:'0010', 3:'0011', 4:'010 def _key2bin(s): "Convert a key into a string of binary digits" - kl=map(lambda x: bord(x), s) - kl=map(lambda x: binary[x>>4]+binary[x&15], kl) + kl=[bord(x) for x in s] + kl=[binary[x>>4]+binary[x&15] for x in kl] return ''.join(kl) def _extract(key, start, length): @@ -95,7 +96,7 @@ def english_to_key (s): p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) if (p&3) != _extract(skbin, 64, 2): - raise ValueError, "Parity error in resulting key" + raise ValueError("Parity error in resulting key") key=key+subkey[0:8] return key @@ -352,13 +353,13 @@ if __name__=='__main__': ] for key, words in data: - print 'Trying key', key + print('Trying key', key) key=binascii.a2b_hex(key) w2=key_to_english(key) if w2!=words: - print 'key_to_english fails on key', repr(key), ', producing', str(w2) + print('key_to_english fails on key', repr(key), ', producing', str(w2)) k2=english_to_key(words) if k2!=key: - print 'english_to_key fails on key', repr(key), ', producing', repr(k2) + print('english_to_key fails on key', repr(key), ', producing', repr(k2))