You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2280 lines
90 KiB
2280 lines
90 KiB
--- lib/Crypto/Cipher/ARC2.py
|
|
+++ lib/Crypto/Cipher/ARC2.py
|
|
@@ -126,5 +126,5 @@ MODE_OPENPGP = 7
|
|
#: Size of a data block (in bytes)
|
|
block_size = 8
|
|
#: Size of a key (in bytes)
|
|
-key_size = xrange(1,16+1)
|
|
+key_size = range(1,16+1)
|
|
|
|
--- lib/Crypto/Cipher/ARC4.py
|
|
+++ lib/Crypto/Cipher/ARC4.py
|
|
@@ -116,5 +116,5 @@ def new(key, *args, **kwargs):
|
|
#: Size of a data block (in bytes)
|
|
block_size = 1
|
|
#: Size of a key (in bytes)
|
|
-key_size = xrange(1,256+1)
|
|
+key_size = range(1,256+1)
|
|
|
|
--- lib/Crypto/Cipher/Blowfish.py
|
|
+++ lib/Crypto/Cipher/Blowfish.py
|
|
@@ -117,5 +117,5 @@ MODE_OPENPGP = 7
|
|
#: Size of a data block (in bytes)
|
|
block_size = 8
|
|
#: Size of a key (in bytes)
|
|
-key_size = xrange(4,56+1)
|
|
+key_size = range(4,56+1)
|
|
|
|
--- lib/Crypto/Cipher/CAST.py
|
|
+++ lib/Crypto/Cipher/CAST.py
|
|
@@ -120,4 +120,4 @@ MODE_OPENPGP = 7
|
|
#: Size of a data block (in bytes)
|
|
block_size = 8
|
|
#: Size of a key (in bytes)
|
|
-key_size = xrange(5,16+1)
|
|
+key_size = range(5,16+1)
|
|
--- lib/Crypto/Cipher/PKCS1_OAEP.py
|
|
+++ lib/Crypto/Cipher/PKCS1_OAEP.py
|
|
@@ -49,7 +49,7 @@ the RSA key:
|
|
.. __: http://www.rsa.com/rsalabs/node.asp?id=2125.
|
|
"""
|
|
|
|
-from __future__ import nested_scopes
|
|
+
|
|
|
|
__revision__ = "$Id$"
|
|
__all__ = [ 'new', 'PKCS1OAEP_Cipher' ]
|
|
--- lib/Crypto/Cipher/PKCS1_v1_5.py
|
|
+++ lib/Crypto/Cipher/PKCS1_v1_5.py
|
|
@@ -132,7 +132,7 @@ class PKCS115_Cipher:
|
|
def __call__(self, c):
|
|
while bord(c)==0x00: c=self.rf(1)[0]
|
|
return c
|
|
- ps = tobytes(map(nonZeroRandByte(randFunc), randFunc(k-mLen-3)))
|
|
+ ps = tobytes(list(map(nonZeroRandByte(randFunc), randFunc(k-mLen-3))))
|
|
# Step 2b
|
|
em = b('\x00\x02') + ps + bchr(0x00) + message
|
|
# Step 3a (OS2IP), step 3b (RSAEP), part of step 3c (I2OSP)
|
|
--- lib/Crypto/Cipher/XOR.py
|
|
+++ lib/Crypto/Cipher/XOR.py
|
|
@@ -82,5 +82,5 @@ def new(key, *args, **kwargs):
|
|
#: Size of a data block (in bytes)
|
|
block_size = 1
|
|
#: Size of a key (in bytes)
|
|
-key_size = xrange(1,32+1)
|
|
+key_size = range(1,32+1)
|
|
|
|
--- lib/Crypto/Hash/HMAC.py
|
|
+++ lib/Crypto/Hash/HMAC.py
|
|
@@ -98,7 +98,7 @@ class HMAC:
|
|
A hash module or object instantiated from `Crypto.Hash`
|
|
"""
|
|
if digestmod is None:
|
|
- import MD5
|
|
+ from . import MD5
|
|
digestmod = MD5
|
|
|
|
self.digestmod = digestmod
|
|
--- lib/Crypto/Protocol/AllOrNothing.py
|
|
+++ 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
|
|
+++ 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 Governm
|
|
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 Happin
|
|
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 Happin
|
|
|
|
# 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 Happin
|
|
# 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 Happin
|
|
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/Protocol/KDF.py
|
|
+++ lib/Crypto/Protocol/KDF.py
|
|
@@ -79,7 +79,7 @@ def PBKDF1(password, salt, dkLen, count=
|
|
raise ValueError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
|
|
if len(salt)!=8:
|
|
raise ValueError("Salt is not 8 bytes long.")
|
|
- for i in xrange(count-1):
|
|
+ for i in range(count-1):
|
|
pHash = pHash.new(pHash.digest())
|
|
return pHash.digest()[:dkLen]
|
|
|
|
@@ -114,7 +114,7 @@ def PBKDF2(password, salt, dkLen=16, cou
|
|
i = 1
|
|
while len(key)<dkLen:
|
|
U = previousU = prf(password,salt+struct.pack(">I", i))
|
|
- for j in xrange(count-1):
|
|
+ for j in range(count-1):
|
|
previousU = t = prf(password,previousU)
|
|
U = strxor(U,t)
|
|
key += U
|
|
--- lib/Crypto/PublicKey/_DSA.py
|
|
+++ 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
|
|
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/DSA.py
|
|
+++ lib/Crypto/PublicKey/DSA.py
|
|
@@ -217,7 +217,7 @@ class _DSAobj(pubkey.pubkey):
|
|
self.implementation = DSAImplementation()
|
|
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.dsa_construct(*tuple(t))
|
|
--- lib/Crypto/PublicKey/pubkey.py
|
|
+++ lib/Crypto/PublicKey/pubkey.py
|
|
@@ -45,7 +45,7 @@ class pubkey:
|
|
restoration."""
|
|
d=self.__dict__
|
|
for key in self.keydata:
|
|
- if d.has_key(key): d[key]=long(d[key])
|
|
+ if key in d: d[key]=int(d[key])
|
|
return d
|
|
|
|
def __setstate__(self, d):
|
|
@@ -53,7 +53,7 @@ class pubkey:
|
|
number representation being used, whether that is Python long
|
|
integers, MPZ objects, or whatever."""
|
|
for key in self.keydata:
|
|
- if d.has_key(key): self.__dict__[key]=bignum(d[key])
|
|
+ if key in d: self.__dict__[key]=bignum(d[key])
|
|
|
|
def encrypt(self, plaintext, K):
|
|
"""Encrypt a piece of data.
|
|
@@ -68,9 +68,9 @@ integers, MPZ objects, or whatever."""
|
|
plaintext (string or long).
|
|
"""
|
|
wasString=0
|
|
- if isinstance(plaintext, types.StringType):
|
|
+ if isinstance(plaintext, bytes):
|
|
plaintext=bytes_to_long(plaintext) ; wasString=1
|
|
- if isinstance(K, types.StringType):
|
|
+ if isinstance(K, bytes):
|
|
K=bytes_to_long(K)
|
|
ciphertext=self._encrypt(plaintext, K)
|
|
if wasString: return tuple(map(long_to_bytes, ciphertext))
|
|
@@ -86,9 +86,9 @@ integers, MPZ objects, or whatever."""
|
|
of byte strings. A long otherwise.
|
|
"""
|
|
wasString=0
|
|
- if not isinstance(ciphertext, types.TupleType):
|
|
+ if not isinstance(ciphertext, tuple):
|
|
ciphertext=(ciphertext,)
|
|
- if isinstance(ciphertext[0], types.StringType):
|
|
+ if isinstance(ciphertext[0], bytes):
|
|
ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1
|
|
plaintext=self._decrypt(ciphertext)
|
|
if wasString: return long_to_bytes(plaintext)
|
|
@@ -107,8 +107,8 @@ integers, MPZ objects, or whatever."""
|
|
"""
|
|
if (not self.has_private()):
|
|
raise TypeError('Private key not available in this object')
|
|
- if isinstance(M, types.StringType): M=bytes_to_long(M)
|
|
- if isinstance(K, types.StringType): K=bytes_to_long(K)
|
|
+ if isinstance(M, bytes): M=bytes_to_long(M)
|
|
+ if isinstance(K, bytes): K=bytes_to_long(K)
|
|
return self._sign(M, K)
|
|
|
|
def verify (self, M, signature):
|
|
@@ -122,7 +122,7 @@ integers, MPZ objects, or whatever."""
|
|
|
|
:Return: True if the signature is correct, False otherwise.
|
|
"""
|
|
- if isinstance(M, types.StringType): M=bytes_to_long(M)
|
|
+ if isinstance(M, bytes): M=bytes_to_long(M)
|
|
return self._verify(M, signature)
|
|
|
|
# alias to compensate for the old validate() name
|
|
@@ -142,9 +142,9 @@ integers, MPZ objects, or whatever."""
|
|
:Return: A byte string if M was so. A long otherwise.
|
|
"""
|
|
wasString=0
|
|
- if isinstance(M, types.StringType):
|
|
+ if isinstance(M, bytes):
|
|
M=bytes_to_long(M) ; wasString=1
|
|
- if isinstance(B, types.StringType): B=bytes_to_long(B)
|
|
+ if isinstance(B, bytes): B=bytes_to_long(B)
|
|
blindedmessage=self._blind(M, B)
|
|
if wasString: return long_to_bytes(blindedmessage)
|
|
else: return blindedmessage
|
|
@@ -159,9 +159,9 @@ integers, MPZ objects, or whatever."""
|
|
:Type B: byte string or long
|
|
"""
|
|
wasString=0
|
|
- if isinstance(M, types.StringType):
|
|
+ if isinstance(M, bytes):
|
|
M=bytes_to_long(M) ; wasString=1
|
|
- if isinstance(B, types.StringType): B=bytes_to_long(B)
|
|
+ if isinstance(B, bytes): B=bytes_to_long(B)
|
|
unblindedmessage=self._unblind(M, B)
|
|
if wasString: return long_to_bytes(unblindedmessage)
|
|
else: return unblindedmessage
|
|
--- lib/Crypto/PublicKey/_RSA.py
|
|
+++ lib/Crypto/PublicKey/_RSA.py
|
|
@@ -37,12 +37,12 @@ def generate_py(bits, randfunc, progress
|
|
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/RSA.py
|
|
+++ lib/Crypto/PublicKey/RSA.py
|
|
@@ -286,7 +286,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))
|
|
@@ -580,7 +580,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/PublicKey/_slowmath.py
|
|
+++ lib/Crypto/PublicKey/_slowmath.py
|
|
@@ -79,12 +79,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
|
|
@@ -149,7 +149,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
|
|
@@ -167,11 +167,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/Random/Fortuna/FortunaAccumulator.py
|
|
+++ lib/Crypto/Random/Fortuna/FortunaAccumulator.py
|
|
@@ -32,9 +32,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
|
|
@@ -87,7 +87,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/Fortuna/FortunaGenerator.py
|
|
+++ lib/Crypto/Random/Fortuna/FortunaGenerator.py
|
|
@@ -33,7 +33,7 @@ from Crypto.Util.number import ceil_shif
|
|
from Crypto.Util import Counter
|
|
from Crypto.Cipher import AES
|
|
|
|
-import SHAd256
|
|
+from . import SHAd256
|
|
|
|
class AESGenerator(object):
|
|
"""The Fortuna "generator"
|
|
@@ -88,7 +88,7 @@ class AESGenerator(object):
|
|
remainder = bytes & ((1<<20)-1)
|
|
|
|
retval = []
|
|
- for i in xrange(num_full_blocks):
|
|
+ for i in range(num_full_blocks):
|
|
retval.append(self._pseudo_random_data(1<<20))
|
|
retval.append(self._pseudo_random_data(remainder))
|
|
|
|
@@ -121,7 +121,7 @@ class AESGenerator(object):
|
|
raise AssertionError("generator must be seeded before use")
|
|
assert 0 <= num_blocks <= self.max_blocks_per_request
|
|
retval = []
|
|
- for i in xrange(num_blocks >> 12): # xrange(num_blocks / 4096)
|
|
+ for i in range(num_blocks >> 12): # xrange(num_blocks / 4096)
|
|
retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros))
|
|
remaining_bytes = (num_blocks & 4095) << self.block_size_shift # (num_blocks % 4095) * self.block_size
|
|
retval.append(self._cipher.encrypt(self._four_kiblocks_of_zeros[:remaining_bytes]))
|
|
--- lib/Crypto/Random/random.py
|
|
+++ lib/Crypto/Random/random.py
|
|
@@ -45,7 +45,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):
|
|
@@ -62,9 +62,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")
|
|
@@ -84,7 +84,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
|
|
@@ -106,7 +106,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):
|
|
@@ -118,9 +118,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
|
|
+++ 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.TestCas
|
|
|
|
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)
|
|
@@ -361,12 +361,12 @@ def make_block_tests(module, module_name
|
|
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_AES.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_AES.py
|
|
@@ -26,7 +26,7 @@
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
-from common import dict # For compatibility with Python 2.1 and 2.2
|
|
+from .common import dict # For compatibility with Python 2.1 and 2.2
|
|
from Crypto.Util.py3compat import *
|
|
from binascii import hexlify
|
|
|
|
@@ -1422,7 +1422,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import AES
|
|
- from common import make_block_tests
|
|
+ from .common import make_block_tests
|
|
return make_block_tests(AES, "AES", test_data)
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Cipher/test_ARC2.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_ARC2.py
|
|
@@ -26,7 +26,7 @@
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
-from common import dict # For compatibility with Python 2.1 and 2.2
|
|
+from .common import dict # For compatibility with Python 2.1 and 2.2
|
|
|
|
import unittest
|
|
from Crypto.Util.py3compat import *
|
|
@@ -109,7 +109,7 @@ class BufferOverflowTest(unittest.TestCa
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import ARC2
|
|
- from common import make_block_tests
|
|
+ from .common import make_block_tests
|
|
|
|
tests = make_block_tests(ARC2, "ARC2", test_data)
|
|
tests.append(BufferOverflowTest())
|
|
--- lib/Crypto/SelfTest/Cipher/test_ARC4.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_ARC4.py
|
|
@@ -70,7 +70,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import ARC4
|
|
- from common import make_stream_tests
|
|
+ from .common import make_stream_tests
|
|
return make_stream_tests(ARC4, "ARC4", test_data)
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Cipher/test_Blowfish.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_Blowfish.py
|
|
@@ -102,7 +102,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import Blowfish
|
|
- from common import make_block_tests
|
|
+ from .common import make_block_tests
|
|
return make_block_tests(Blowfish, "Blowfish", test_data)
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Cipher/test_CAST.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_CAST.py
|
|
@@ -46,7 +46,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import CAST
|
|
- from common import make_block_tests
|
|
+ from .common import make_block_tests
|
|
return make_block_tests(CAST, "CAST", test_data)
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Cipher/test_DES3.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_DES3.py
|
|
@@ -26,7 +26,7 @@
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
-from common import dict # For compatibility with Python 2.1 and 2.2
|
|
+from .common import dict # For compatibility with Python 2.1 and 2.2
|
|
from Crypto.Util.py3compat import *
|
|
from binascii import hexlify
|
|
|
|
@@ -322,7 +322,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import DES3
|
|
- from common import make_block_tests
|
|
+ from .common import make_block_tests
|
|
return make_block_tests(DES3, "DES3", test_data)
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Cipher/test_DES.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_DES.py
|
|
@@ -26,7 +26,7 @@
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
-from common import dict # For compatibility with Python 2.1 and 2.2
|
|
+from .common import dict # For compatibility with Python 2.1 and 2.2
|
|
from Crypto.Util.py3compat import *
|
|
import unittest
|
|
|
|
@@ -328,7 +328,7 @@ class RonRivestTest(unittest.TestCase):
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Cipher import DES
|
|
- from common import make_block_tests
|
|
+ from .common import make_block_tests
|
|
return make_block_tests(DES, "DES", test_data) + [RonRivestTest()]
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py
|
|
+++ 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+Uf7VHJdWaeO5Lzu
|
|
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/Cipher/test_pkcs1_oaep.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py
|
|
@@ -20,7 +20,7 @@
|
|
# SOFTWARE.
|
|
# ===================================================================
|
|
|
|
-from __future__ import nested_scopes
|
|
+
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
@@ -269,7 +269,7 @@ class PKCS1_OAEP_Tests(unittest.TestCase
|
|
# Verify encryption using all test vectors
|
|
for test in self._testData:
|
|
# Build the key
|
|
- comps = [ long(rws(test[0][x]),16) for x in ('n','e') ]
|
|
+ comps = [ int(rws(test[0][x]),16) for x in ('n','e') ]
|
|
key = RSA.construct(comps)
|
|
# RNG that takes its random numbers from a pool given
|
|
# at initialization
|
|
@@ -297,7 +297,7 @@ class PKCS1_OAEP_Tests(unittest.TestCase
|
|
# Verify decryption using all test vectors
|
|
for test in self._testData:
|
|
# Build the key
|
|
- comps = [ long(rws(test[0][x]),16) for x in ('n','e','d') ]
|
|
+ comps = [ int(rws(test[0][x]),16) for x in ('n','e','d') ]
|
|
key = RSA.construct(comps)
|
|
# The real test
|
|
cipher = PKCS.new(key, test[4])
|
|
@@ -312,7 +312,7 @@ class PKCS1_OAEP_Tests(unittest.TestCase
|
|
|
|
def testEncryptDecrypt1(self):
|
|
# Encrypt/Decrypt messages of length [0..128-2*20-2]
|
|
- for pt_len in xrange(0,128-2*20-2):
|
|
+ for pt_len in range(0,128-2*20-2):
|
|
pt = self.rng(pt_len)
|
|
ct = PKCS.encrypt(pt, self.key1024)
|
|
pt2 = PKCS.decrypt(ct, self.key1024)
|
|
@@ -335,7 +335,7 @@ class PKCS1_OAEP_Tests(unittest.TestCase
|
|
cipher = PKCS.new(self.key1024, hashmod)
|
|
ct = cipher.encrypt(pt)
|
|
self.assertEqual(cipher.decrypt(ct), pt)
|
|
- self.failUnless(asked > hashmod.digest_size)
|
|
+ self.assertTrue(asked > hashmod.digest_size)
|
|
|
|
def testEncryptDecrypt2(self):
|
|
# Verify that OAEP supports labels
|
|
--- lib/Crypto/SelfTest/Cipher/test_XOR.py
|
|
+++ lib/Crypto/SelfTest/Cipher/test_XOR.py
|
|
@@ -61,7 +61,7 @@ class TruncationSelfTest(unittest.TestCa
|
|
def get_tests(config={}):
|
|
global XOR
|
|
from Crypto.Cipher import XOR
|
|
- from common import make_stream_tests
|
|
+ from .common import make_stream_tests
|
|
return make_stream_tests(XOR, "XOR", test_data) + [TruncationSelfTest()]
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Hash/common.py
|
|
+++ lib/Crypto/SelfTest/Hash/common.py
|
|
@@ -53,11 +53,11 @@ class HashDigestSizeSelfTest(unittest.Te
|
|
return self.description
|
|
|
|
def runTest(self):
|
|
- self.failUnless(hasattr(self.hashmod, "digest_size"))
|
|
- self.assertEquals(self.hashmod.digest_size, self.expected)
|
|
+ self.assertTrue(hasattr(self.hashmod, "digest_size"))
|
|
+ self.assertEqual(self.hashmod.digest_size, self.expected)
|
|
h = self.hashmod.new()
|
|
- self.failUnless(hasattr(h, "digest_size"))
|
|
- self.assertEquals(h.digest_size, self.expected)
|
|
+ self.assertTrue(hasattr(h, "digest_size"))
|
|
+ self.assertEqual(h.digest_size, self.expected)
|
|
|
|
|
|
class HashSelfTest(unittest.TestCase):
|
|
@@ -133,7 +133,7 @@ class MACSelfTest(unittest.TestCase):
|
|
return self.description
|
|
|
|
def runTest(self):
|
|
- for hashname in self.expected_dict.keys():
|
|
+ for hashname in list(self.expected_dict.keys()):
|
|
hashmod = self.hashmods[hashname]
|
|
key = binascii.a2b_hex(b(self.key))
|
|
data = binascii.a2b_hex(b(self.input))
|
|
@@ -171,7 +171,7 @@ def make_hash_tests(module, module_name,
|
|
tests = []
|
|
for i in range(len(test_data)):
|
|
row = test_data[i]
|
|
- (expected, input) = map(b,row[0:2])
|
|
+ (expected, input) = list(map(b,row[0:2]))
|
|
if len(row) < 3:
|
|
description = repr(input)
|
|
else:
|
|
--- lib/Crypto/SelfTest/Hash/test_HMAC.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_HMAC.py
|
|
@@ -26,7 +26,7 @@
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
-from common import dict # For compatibility with Python 2.1 and 2.2
|
|
+from .common import dict # For compatibility with Python 2.1 and 2.2
|
|
from Crypto.Util.py3compat import *
|
|
|
|
# This is a list of (key, data, results, description) tuples.
|
|
@@ -204,7 +204,7 @@ hashlib_test_data = [
|
|
def get_tests(config={}):
|
|
global test_data
|
|
from Crypto.Hash import HMAC, MD5, SHA as SHA1, SHA256
|
|
- from common import make_mac_tests
|
|
+ from .common import make_mac_tests
|
|
hashmods = dict(MD5=MD5, SHA1=SHA1, SHA256=SHA256, default=None)
|
|
try:
|
|
from Crypto.Hash import SHA224, SHA384, SHA512
|
|
--- lib/Crypto/SelfTest/Hash/test_MD2.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_MD2.py
|
|
@@ -51,7 +51,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import MD2
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(MD2, "MD2", test_data,
|
|
digest_size=16,
|
|
oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02")
|
|
--- lib/Crypto/SelfTest/Hash/test_MD4.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_MD4.py
|
|
@@ -51,7 +51,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import MD4
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(MD4, "MD4", test_data,
|
|
digest_size=16,
|
|
oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04")
|
|
--- lib/Crypto/SelfTest/Hash/test_MD5.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_MD5.py
|
|
@@ -51,7 +51,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import MD5
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(MD5, "MD5", test_data,
|
|
digest_size=16,
|
|
oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05")
|
|
--- lib/Crypto/SelfTest/Hash/test_RIPEMD.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_RIPEMD.py
|
|
@@ -60,7 +60,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import RIPEMD
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(RIPEMD, "RIPEMD", test_data,
|
|
digest_size=20,
|
|
oid="\x06\x05\x2b\x24\x03\02\x01")
|
|
--- lib/Crypto/SelfTest/Hash/test_SHA224.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_SHA224.py
|
|
@@ -52,7 +52,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import SHA224
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(SHA224, "SHA224", test_data,
|
|
digest_size=28,
|
|
oid='\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04')
|
|
--- lib/Crypto/SelfTest/Hash/test_SHA256.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_SHA256.py
|
|
@@ -36,13 +36,13 @@ class LargeSHA256Test(unittest.TestCase)
|
|
zeros = bchr(0x00) * (1024*1024)
|
|
|
|
h = SHA256.new(zeros)
|
|
- for i in xrange(511):
|
|
+ for i in range(511):
|
|
h.update(zeros)
|
|
|
|
# This test vector is from PyCrypto's old testdata.py file.
|
|
self.assertEqual('9acca8e8c22201155389f65abbf6bc9723edc7384ead80503839f49dcc56d767', h.hexdigest()) # 512 MiB
|
|
|
|
- for i in xrange(8):
|
|
+ for i in range(8):
|
|
h.update(zeros)
|
|
|
|
# This test vector is from PyCrypto's old testdata.py file.
|
|
@@ -78,7 +78,7 @@ def get_tests(config={}):
|
|
]
|
|
|
|
from Crypto.Hash import SHA256
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
tests = make_hash_tests(SHA256, "SHA256", test_data,
|
|
digest_size=32,
|
|
oid="\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01")
|
|
--- lib/Crypto/SelfTest/Hash/test_SHA384.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_SHA384.py
|
|
@@ -50,7 +50,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import SHA384
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(SHA384, "SHA384", test_data,
|
|
digest_size=48,
|
|
oid='\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02')
|
|
--- lib/Crypto/SelfTest/Hash/test_SHA512.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_SHA512.py
|
|
@@ -47,7 +47,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import SHA512
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(SHA512, "SHA512", test_data,
|
|
digest_size=64,
|
|
oid="\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03")
|
|
--- lib/Crypto/SelfTest/Hash/test_SHA.py
|
|
+++ lib/Crypto/SelfTest/Hash/test_SHA.py
|
|
@@ -51,7 +51,7 @@ test_data = [
|
|
|
|
def get_tests(config={}):
|
|
from Crypto.Hash import SHA
|
|
- from common import make_hash_tests
|
|
+ from .common import make_hash_tests
|
|
return make_hash_tests(SHA, "SHA", test_data,
|
|
digest_size=20,
|
|
oid="\x06\x05\x2B\x0E\x03\x02\x1A")
|
|
--- lib/Crypto/SelfTest/__init__.py
|
|
+++ lib/Crypto/SelfTest/__init__.py
|
|
@@ -32,7 +32,7 @@ __revision__ = "$Id$"
|
|
|
|
import sys
|
|
import unittest
|
|
-from StringIO import StringIO
|
|
+from io import StringIO
|
|
|
|
class SelfTestError(Exception):
|
|
def __init__(self, message, result):
|
|
--- lib/Crypto/SelfTest/Protocol/test_KDF.py
|
|
+++ lib/Crypto/SelfTest/Protocol/test_KDF.py
|
|
@@ -78,7 +78,7 @@ class PBKDF2_Tests(unittest.TestCase):
|
|
def prf(p,s):
|
|
return HMAC.new(p,s,SHA1).digest()
|
|
|
|
- for i in xrange(len(self._testData)):
|
|
+ for i in range(len(self._testData)):
|
|
v = self._testData[i]
|
|
res = PBKDF2(v[0], t2b(v[1]), v[2], v[3])
|
|
res2 = PBKDF2(v[0], t2b(v[1]), v[2], v[3], prf)
|
|
--- lib/Crypto/SelfTest/PublicKey/test_ElGamal.py
|
|
+++ 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<elgObj.g<(elgObj.p-1))
|
|
- self.assertEquals(pow(elgObj.g, elgObj.p-1, elgObj.p), 1)
|
|
- self.failUnless(1<elgObj.x<(elgObj.p-1))
|
|
- self.assertEquals(pow(elgObj.g, elgObj.x, elgObj.p), elgObj.y)
|
|
+ self.assertTrue(1<elgObj.g<(elgObj.p-1))
|
|
+ self.assertEqual(pow(elgObj.g, elgObj.p-1, elgObj.p), 1)
|
|
+ self.assertTrue(1<elgObj.x<(elgObj.p-1))
|
|
+ self.assertEqual(pow(elgObj.g, elgObj.x, elgObj.p), elgObj.y)
|
|
|
|
def _check_public_key(self, elgObj):
|
|
|
|
# Check capabilities
|
|
- self.failIf(elgObj.has_private())
|
|
- self.failUnless(elgObj.can_sign())
|
|
- self.failUnless(elgObj.can_encrypt())
|
|
+ self.assertFalse(elgObj.has_private())
|
|
+ self.assertTrue(elgObj.can_sign())
|
|
+ self.assertTrue(elgObj.can_encrypt())
|
|
|
|
# Sanity check key data
|
|
- self.failUnless(1<elgObj.g<(elgObj.p-1))
|
|
- self.assertEquals(pow(elgObj.g, elgObj.p-1, elgObj.p), 1)
|
|
+ self.assertTrue(1<elgObj.g<(elgObj.p-1))
|
|
+ self.assertEqual(pow(elgObj.g, elgObj.p-1, elgObj.p), 1)
|
|
|
|
def _exercise_primitive(self, elgObj):
|
|
# Test encryption/decryption
|
|
plaintext = b("Test")
|
|
- ciphertext = elgObj.encrypt(plaintext, 123456789L)
|
|
+ ciphertext = elgObj.encrypt(plaintext, 123456789)
|
|
plaintextP = elgObj.decrypt(ciphertext)
|
|
- self.assertEquals(plaintext, plaintextP)
|
|
+ self.assertEqual(plaintext, plaintextP)
|
|
|
|
# Test signature/verification
|
|
- signature = elgObj.sign(plaintext, 987654321L)
|
|
+ signature = elgObj.sign(plaintext, 987654321)
|
|
elgObj.verify(plaintext, signature)
|
|
|
|
def _exercise_public_primitive(self, elgObj):
|
|
plaintext = b("Test")
|
|
- ciphertext = elgObj.encrypt(plaintext, 123456789L)
|
|
+ ciphertext = elgObj.encrypt(plaintext, 123456789)
|
|
|
|
def get_tests(config={}):
|
|
tests = []
|
|
--- lib/Crypto/SelfTest/PublicKey/test_importKey.py
|
|
+++ lib/Crypto/SelfTest/PublicKey/test_importKey.py
|
|
@@ -20,7 +20,7 @@
|
|
# SOFTWARE.
|
|
# ===================================================================
|
|
|
|
-from __future__ import nested_scopes
|
|
+
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
@@ -42,7 +42,7 @@ def der2pem(der, text='PUBLIC'):
|
|
|
|
class ImportKeyTests(unittest.TestCase):
|
|
# 512-bit RSA key generated with openssl
|
|
- rsaKeyPEM = u'''-----BEGIN RSA PRIVATE KEY-----
|
|
+ rsaKeyPEM = '''-----BEGIN RSA PRIVATE KEY-----
|
|
MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII
|
|
q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8
|
|
Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI
|
|
@@ -53,7 +53,7 @@ n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sB
|
|
-----END RSA PRIVATE KEY-----'''
|
|
|
|
# As above, but this is actually an unencrypted PKCS#8 key
|
|
- rsaKeyPEM8 = u'''-----BEGIN PRIVATE KEY-----
|
|
+ rsaKeyPEM8 = '''-----BEGIN PRIVATE KEY-----
|
|
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvx4nkAqgiyNRGlwS
|
|
ga5tkzEsPv6RP5MuvtSS8S0WtGEMMoy24girX0WsvilQgzKY8xIsGfeEkt7fQPDj
|
|
wZAzhQIDAQABAkAJRIMSnxFN7fZ+2rwjAbxaiOXmYB3XAWIg6tn9S/xv3rdYk4mK
|
|
@@ -68,7 +68,7 @@ BX85JB8zqwHB
|
|
rsaKeyEncryptedPEM=(
|
|
|
|
# With DES and passphrase 'test'
|
|
- ('test', u'''-----BEGIN RSA PRIVATE KEY-----
|
|
+ ('test', '''-----BEGIN RSA PRIVATE KEY-----
|
|
Proc-Type: 4,ENCRYPTED
|
|
DEK-Info: DES-CBC,AF8F9A40BD2FA2FC
|
|
|
|
@@ -83,7 +83,7 @@ dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rb
|
|
"\xAF\x8F\x9A\x40\xBD\x2F\xA2\xFC"),
|
|
|
|
# With Triple-DES and passphrase 'rocking'
|
|
- ('rocking', u'''-----BEGIN RSA PRIVATE KEY-----
|
|
+ ('rocking', '''-----BEGIN RSA PRIVATE KEY-----
|
|
Proc-Type: 4,ENCRYPTED
|
|
DEK-Info: DES-EDE3-CBC,C05D6C07F7FC02F6
|
|
|
|
@@ -98,7 +98,7 @@ YSxC7qDQIT/RECvV3+oQKEcmpEujn45wAnkTi12B
|
|
"\xC0\x5D\x6C\x07\xF7\xFC\x02\xF6"),
|
|
)
|
|
|
|
- rsaPublicKeyPEM = u'''-----BEGIN PUBLIC KEY-----
|
|
+ rsaPublicKeyPEM = '''-----BEGIN PUBLIC KEY-----
|
|
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T
|
|
Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ==
|
|
-----END PUBLIC KEY-----'''
|
|
@@ -144,21 +144,21 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3
|
|
03010001
|
|
'''.replace(" ",""))
|
|
|
|
- n = long('BF 1E 27 90 0A A0 8B 23 51 1A 5C 12 81 AE 6D 93 31 2C 3E FE 91 3F 93 2E BE D4 92 F1 2D 16 B4 61 0C 32 8C B6 E2 08 AB 5F 45 AC BE 29 50 83 32 98 F3 12 2C 19 F7 84 92 DE DF 40 F0 E3 C1 90 33 85'.replace(" ",""),16)
|
|
- e = 65537L
|
|
- d = long('09 44 83 12 9F 11 4D ED F6 7E DA BC 23 01 BC 5A 88 E5 E6 60 1D D7 01 62 20 EA D9 FD 4B FC 6F DE B7 58 93 89 8A E4 1C 54 DD BD BF 15 39 F8 CC BD 18 F6 7B 44 0D E1 AC 30 44 02 81 D4 0C FA C8 39'.replace(" ",""),16)
|
|
- p = long('00 F2 0F 2F 3E 1D A6 18 83 F6 29 80 92 2B D8 DF 54 5C E4 07 C7 26 24 11 03 B5 E2 C5 37 23 12 4A 23'.replace(" ",""),16)
|
|
- q = long('00 CA 1F E9 24 79 2C FC C9 6B FA B7 4F 34 4A 68 B4 18 DF 57 83 38 06 48 06 00 0F E2 A5 C9 9A 02 37'.replace(" ",""),16)
|
|
+ n = int('BF 1E 27 90 0A A0 8B 23 51 1A 5C 12 81 AE 6D 93 31 2C 3E FE 91 3F 93 2E BE D4 92 F1 2D 16 B4 61 0C 32 8C B6 E2 08 AB 5F 45 AC BE 29 50 83 32 98 F3 12 2C 19 F7 84 92 DE DF 40 F0 E3 C1 90 33 85'.replace(" ",""),16)
|
|
+ e = 65537
|
|
+ d = int('09 44 83 12 9F 11 4D ED F6 7E DA BC 23 01 BC 5A 88 E5 E6 60 1D D7 01 62 20 EA D9 FD 4B FC 6F DE B7 58 93 89 8A E4 1C 54 DD BD BF 15 39 F8 CC BD 18 F6 7B 44 0D E1 AC 30 44 02 81 D4 0C FA C8 39'.replace(" ",""),16)
|
|
+ p = int('00 F2 0F 2F 3E 1D A6 18 83 F6 29 80 92 2B D8 DF 54 5C E4 07 C7 26 24 11 03 B5 E2 C5 37 23 12 4A 23'.replace(" ",""),16)
|
|
+ q = int('00 CA 1F E9 24 79 2C FC C9 6B FA B7 4F 34 4A 68 B4 18 DF 57 83 38 06 48 06 00 0F E2 A5 C9 9A 02 37'.replace(" ",""),16)
|
|
|
|
# This is q^{-1} mod p). fastmath and slowmath use pInv (p^{-1}
|
|
# mod q) instead!
|
|
- qInv = long('00 BD 9F 40 A7 64 22 7A 21 96 2A 4A DD 07 E4 DE FE 43 ED 91 A3 AE 27 BB 05 7F 39 24 1F 33 AB 01 C1'.replace(" ",""),16)
|
|
+ qInv = int('00 BD 9F 40 A7 64 22 7A 21 96 2A 4A DD 07 E4 DE FE 43 ED 91 A3 AE 27 BB 05 7F 39 24 1F 33 AB 01 C1'.replace(" ",""),16)
|
|
pInv = inverse(p,q)
|
|
|
|
def testImportKey1(self):
|
|
"""Verify import of RSAPrivateKey DER SEQUENCE"""
|
|
key = self.rsa.importKey(self.rsaKeyDER)
|
|
- self.failUnless(key.has_private())
|
|
+ self.assertTrue(key.has_private())
|
|
self.assertEqual(key.n, self.n)
|
|
self.assertEqual(key.e, self.e)
|
|
self.assertEqual(key.d, self.d)
|
|
@@ -168,7 +168,7 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3
|
|
def testImportKey2(self):
|
|
"""Verify import of SubjectPublicKeyInfo DER SEQUENCE"""
|
|
key = self.rsa.importKey(self.rsaPublicKeyDER)
|
|
- self.failIf(key.has_private())
|
|
+ self.assertFalse(key.has_private())
|
|
self.assertEqual(key.n, self.n)
|
|
self.assertEqual(key.e, self.e)
|
|
|
|
@@ -228,7 +228,7 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3
|
|
"""Verify import of encrypted PrivateKeyInfo DER SEQUENCE"""
|
|
for t in self.rsaKeyEncryptedPEM:
|
|
key = self.rsa.importKey(t[1], t[0])
|
|
- self.failUnless(key.has_private())
|
|
+ self.assertTrue(key.has_private())
|
|
self.assertEqual(key.n, self.n)
|
|
self.assertEqual(key.e, self.e)
|
|
self.assertEqual(key.d, self.d)
|
|
@@ -238,7 +238,7 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3
|
|
def testImportKey9(self):
|
|
"""Verify import of unencrypted PrivateKeyInfo DER SEQUENCE"""
|
|
key = self.rsa.importKey(self.rsaKeyDER8)
|
|
- self.failUnless(key.has_private())
|
|
+ self.assertTrue(key.has_private())
|
|
self.assertEqual(key.n, self.n)
|
|
self.assertEqual(key.e, self.e)
|
|
self.assertEqual(key.d, self.d)
|
|
@@ -248,7 +248,7 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3
|
|
def testImportKey10(self):
|
|
"""Verify import of unencrypted PrivateKeyInfo DER SEQUENCE, encoded with PEM"""
|
|
key = self.rsa.importKey(self.rsaKeyPEM8)
|
|
- self.failUnless(key.has_private())
|
|
+ self.assertTrue(key.has_private())
|
|
self.assertEqual(key.n, self.n)
|
|
self.assertEqual(key.e, self.e)
|
|
self.assertEqual(key.d, self.d)
|
|
@@ -301,7 +301,7 @@ Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3
|
|
def testExportKey4(self):
|
|
key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv])
|
|
# Tuple with index #1 is encrypted with 3DES
|
|
- t = map(b,self.rsaKeyEncryptedPEM[1])
|
|
+ t = list(map(b,self.rsaKeyEncryptedPEM[1]))
|
|
# Force the salt being used when exporting
|
|
key._randfunc = lambda N: (t[2]*divmod(N+len(t[2]),len(t[2]))[0])[:N]
|
|
pemKey = key.exportKey("PEM", t[0])
|
|
--- lib/Crypto/SelfTest/PublicKey/test_RSA.py
|
|
+++ lib/Crypto/SelfTest/PublicKey/test_RSA.py
|
|
@@ -76,7 +76,7 @@ class RSATest(unittest.TestCase):
|
|
e2 53 72 98 ca 2a 8f 59 46 f8 e5 fd 09 1d bd cb
|
|
"""
|
|
|
|
- e = 0x11L # public exponent
|
|
+ e = 0x11 # public exponent
|
|
|
|
prime_factor = """
|
|
c9 7f b1 f0 27 f4 53 f6 34 12 33 ea aa d1 d9 35
|
|
@@ -170,9 +170,9 @@ class RSATest(unittest.TestCase):
|
|
|
|
def test_factoring(self):
|
|
rsaObj = self.rsa.construct([self.n, self.e, self.d])
|
|
- self.failUnless(rsaObj.p==self.p or rsaObj.p==self.q)
|
|
- self.failUnless(rsaObj.q==self.p or rsaObj.q==self.q)
|
|
- self.failUnless(rsaObj.q*rsaObj.p == self.n)
|
|
+ self.assertTrue(rsaObj.p==self.p or rsaObj.p==self.q)
|
|
+ self.assertTrue(rsaObj.q==self.p or rsaObj.q==self.q)
|
|
+ self.assertTrue(rsaObj.q*rsaObj.p == self.n)
|
|
|
|
self.assertRaises(ValueError, self.rsa.construct, [self.n, self.e, self.n-1])
|
|
|
|
--- lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py
|
|
+++ lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py
|
|
@@ -77,17 +77,17 @@ class FortunaAccumulatorTests(unittest.T
|
|
self.assertEqual(FortunaAccumulator.which_pools(7), [0])
|
|
self.assertEqual(FortunaAccumulator.which_pools(8), [0, 1, 2, 3])
|
|
for i in range(1, 32):
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**i-1), [0])
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**i), range(i+1))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**i+1), [0])
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**31), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**32), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**33), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**34), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**35), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**36), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**64), range(32))
|
|
- self.assertEqual(FortunaAccumulator.which_pools(2L**128), range(32))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**i-1), [0])
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**i), list(range(i+1)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**i+1), [0])
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**31), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**32), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**33), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**34), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**35), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**36), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**64), list(range(32)))
|
|
+ self.assertEqual(FortunaAccumulator.which_pools(2**128), list(range(32)))
|
|
|
|
def test_accumulator(self):
|
|
"""FortunaAccumulator.FortunaAccumulator"""
|
|
--- lib/Crypto/SelfTest/Random/test_random.py
|
|
+++ lib/Crypto/SelfTest/Random/test_random.py
|
|
@@ -93,7 +93,7 @@ class SimpleTest(unittest.TestCase):
|
|
self.assertRaises(TypeError, random.randint, "1", stop)
|
|
self.assertRaises(TypeError, random.randint, 1, "2")
|
|
# Test choice
|
|
- seq = range(10000)
|
|
+ seq = list(range(10000))
|
|
x = random.choice(seq)
|
|
y = random.choice(seq)
|
|
self.assertNotEqual(x, y)
|
|
@@ -109,7 +109,7 @@ class SimpleTest(unittest.TestCase):
|
|
self.assertRaises(TypeError, random.choice, 1)
|
|
# Test shuffle. Lacks random parameter to specify function.
|
|
# Make copies of seq
|
|
- seq = range(500)
|
|
+ seq = list(range(500))
|
|
x = list(seq)
|
|
y = list(seq)
|
|
random.shuffle(x)
|
|
@@ -150,7 +150,7 @@ class SimpleTest(unittest.TestCase):
|
|
self.assertEqual(z[0] in (1,2,3), True)
|
|
z = random.sample("123", 1)
|
|
self.assertEqual(z[0] in "123", True)
|
|
- z = random.sample(range(3), 1)
|
|
+ z = random.sample(list(range(3)), 1)
|
|
self.assertEqual(z[0] in range(3), True)
|
|
if sys.version_info[0] == 3:
|
|
z = random.sample(b("123"), 1)
|
|
--- lib/Crypto/SelfTest/Signature/__init__.py
|
|
+++ lib/Crypto/SelfTest/Signature/__init__.py
|
|
@@ -28,8 +28,8 @@ import os
|
|
|
|
def get_tests(config={}):
|
|
tests = []
|
|
- import test_pkcs1_15; tests += test_pkcs1_15.get_tests(config=config)
|
|
- import test_pkcs1_pss; tests += test_pkcs1_pss.get_tests(config=config)
|
|
+ from . import test_pkcs1_15; tests += test_pkcs1_15.get_tests(config=config)
|
|
+ from . import test_pkcs1_pss; tests += test_pkcs1_pss.get_tests(config=config)
|
|
return tests
|
|
|
|
if __name__ == '__main__':
|
|
--- lib/Crypto/SelfTest/Signature/test_pkcs1_15.py
|
|
+++ lib/Crypto/SelfTest/Signature/test_pkcs1_15.py
|
|
@@ -158,7 +158,7 @@ class PKCS1_15_Tests(unittest.TestCase):
|
|
if isStr(row[0]):
|
|
key = RSA.importKey(row[0])
|
|
else:
|
|
- comps = [ long(rws(row[0][x]),16) for x in ('n','e','d') ]
|
|
+ comps = [ int(rws(row[0][x]),16) for x in ('n','e','d') ]
|
|
key = RSA.construct(comps)
|
|
h = row[3].new()
|
|
# Data to sign can either be in hex form or not
|
|
@@ -168,7 +168,7 @@ class PKCS1_15_Tests(unittest.TestCase):
|
|
h.update(b(row[1]))
|
|
# The real test
|
|
signer = PKCS.new(key)
|
|
- self.failUnless(signer.can_sign())
|
|
+ self.assertTrue(signer.can_sign())
|
|
s = signer.sign(h)
|
|
self.assertEqual(s, t2b(row[2]))
|
|
|
|
@@ -179,7 +179,7 @@ class PKCS1_15_Tests(unittest.TestCase):
|
|
if isStr(row[0]):
|
|
key = RSA.importKey(row[0]).publickey()
|
|
else:
|
|
- comps = [ long(rws(row[0][x]),16) for x in ('n','e') ]
|
|
+ comps = [ int(rws(row[0][x]),16) for x in ('n','e') ]
|
|
key = RSA.construct(comps)
|
|
h = row[3].new()
|
|
# Data to sign can either be in hex form or not
|
|
@@ -189,9 +189,9 @@ class PKCS1_15_Tests(unittest.TestCase):
|
|
h.update(b(row[1]))
|
|
# The real test
|
|
verifier = PKCS.new(key)
|
|
- self.failIf(verifier.can_sign())
|
|
+ self.assertFalse(verifier.can_sign())
|
|
result = verifier.verify(h, t2b(row[2]))
|
|
- self.failUnless(result)
|
|
+ self.assertTrue(result)
|
|
|
|
def testSignVerify(self):
|
|
rng = Random.new().read
|
|
@@ -204,7 +204,7 @@ class PKCS1_15_Tests(unittest.TestCase):
|
|
signer = PKCS.new(key)
|
|
s = signer.sign(h)
|
|
result = signer.verify(h, s)
|
|
- self.failUnless(result)
|
|
+ self.assertTrue(result)
|
|
|
|
|
|
def get_tests(config={}):
|
|
--- lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py
|
|
+++ lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py
|
|
@@ -20,7 +20,7 @@
|
|
# SOFTWARE.
|
|
# ===================================================================
|
|
|
|
-from __future__ import nested_scopes
|
|
+
|
|
|
|
__revision__ = "$Id$"
|
|
|
|
@@ -346,7 +346,7 @@ class PKCS1_PSS_Tests(unittest.TestCase)
|
|
def testSign1(self):
|
|
for i in range(len(self._testData)):
|
|
# Build the key
|
|
- comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ]
|
|
+ comps = [ int(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ]
|
|
key = MyKey(RSA.construct(comps))
|
|
# Hash function
|
|
h = self._testData[i][4].new()
|
|
@@ -357,14 +357,14 @@ class PKCS1_PSS_Tests(unittest.TestCase)
|
|
key._randfunc = lambda N: test_salt
|
|
# The real test
|
|
signer = PKCS.new(key)
|
|
- self.failUnless(signer.can_sign())
|
|
+ self.assertTrue(signer.can_sign())
|
|
s = signer.sign(h)
|
|
self.assertEqual(s, t2b(self._testData[i][2]))
|
|
|
|
def testVerify1(self):
|
|
for i in range(len(self._testData)):
|
|
# Build the key
|
|
- comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e') ]
|
|
+ comps = [ int(rws(self._testData[i][0][x]),16) for x in ('n','e') ]
|
|
key = MyKey(RSA.construct(comps))
|
|
# Hash function
|
|
h = self._testData[i][4].new()
|
|
@@ -375,9 +375,9 @@ class PKCS1_PSS_Tests(unittest.TestCase)
|
|
# The real test
|
|
key._randfunc = lambda N: test_salt
|
|
verifier = PKCS.new(key)
|
|
- self.failIf(verifier.can_sign())
|
|
+ self.assertFalse(verifier.can_sign())
|
|
result = verifier.verify(h, t2b(self._testData[i][2]))
|
|
- self.failUnless(result)
|
|
+ self.assertTrue(result)
|
|
|
|
def testSignVerify(self):
|
|
h = SHA.new()
|
|
@@ -403,7 +403,7 @@ class PKCS1_PSS_Tests(unittest.TestCase)
|
|
key.asked = 0
|
|
signer = PKCS.new(key)
|
|
s = signer.sign(h)
|
|
- self.failUnless(signer.verify(h, s))
|
|
+ self.assertTrue(signer.verify(h, s))
|
|
self.assertEqual(key.asked, h.digest_size)
|
|
|
|
h = SHA.new()
|
|
@@ -415,14 +415,14 @@ class PKCS1_PSS_Tests(unittest.TestCase)
|
|
signer = PKCS.new(key, saltLen=sLen)
|
|
s = signer.sign(h)
|
|
self.assertEqual(key.asked, sLen)
|
|
- self.failUnless(signer.verify(h, s))
|
|
+ self.assertTrue(signer.verify(h, s))
|
|
|
|
# Verify that sign() uses the custom MGF
|
|
mgfcalls = 0
|
|
signer = PKCS.new(key, newMGF)
|
|
s = signer.sign(h)
|
|
self.assertEqual(mgfcalls, 1)
|
|
- self.failUnless(signer.verify(h, s))
|
|
+ self.assertTrue(signer.verify(h, s))
|
|
|
|
# Verify that sign() does not call the RNG
|
|
# when salt length is 0, even when a new MGF is provided
|
|
@@ -432,7 +432,7 @@ class PKCS1_PSS_Tests(unittest.TestCase)
|
|
s = signer.sign(h)
|
|
self.assertEqual(key.asked,0)
|
|
self.assertEqual(mgfcalls, 1)
|
|
- self.failUnless(signer.verify(h, s))
|
|
+ self.assertTrue(signer.verify(h, s))
|
|
|
|
def get_tests(config={}):
|
|
tests = []
|
|
--- lib/Crypto/SelfTest/Util/test_asn1.py
|
|
+++ lib/Crypto/SelfTest/Util/test_asn1.py
|
|
@@ -35,86 +35,86 @@ class DerObjectTests(unittest.TestCase):
|
|
def testObjEncode1(self):
|
|
# No payload
|
|
der = DerObject(b('\x33'))
|
|
- self.assertEquals(der.encode(), b('\x33\x00'))
|
|
+ self.assertEqual(der.encode(), b('\x33\x00'))
|
|
# Small payload
|
|
der.payload = b('\x45')
|
|
- self.assertEquals(der.encode(), b('\x33\x01\x45'))
|
|
+ self.assertEqual(der.encode(), b('\x33\x01\x45'))
|
|
# Invariant
|
|
- self.assertEquals(der.encode(), b('\x33\x01\x45'))
|
|
+ self.assertEqual(der.encode(), b('\x33\x01\x45'))
|
|
# Initialize with numerical tag
|
|
der = DerObject(b(0x33))
|
|
der.payload = b('\x45')
|
|
- self.assertEquals(der.encode(), b('\x33\x01\x45'))
|
|
+ self.assertEqual(der.encode(), b('\x33\x01\x45'))
|
|
|
|
def testObjEncode2(self):
|
|
# Known types
|
|
der = DerObject('SEQUENCE')
|
|
- self.assertEquals(der.encode(), b('\x30\x00'))
|
|
+ self.assertEqual(der.encode(), b('\x30\x00'))
|
|
der = DerObject('BIT STRING')
|
|
- self.assertEquals(der.encode(), b('\x03\x00'))
|
|
+ self.assertEqual(der.encode(), b('\x03\x00'))
|
|
|
|
def testObjEncode3(self):
|
|
# Long payload
|
|
der = DerObject(b('\x34'))
|
|
der.payload = b("0")*128
|
|
- self.assertEquals(der.encode(), b('\x34\x81\x80' + "0"*128))
|
|
+ self.assertEqual(der.encode(), b('\x34\x81\x80' + "0"*128))
|
|
|
|
def testObjDecode1(self):
|
|
# Decode short payload
|
|
der = DerObject()
|
|
der.decode(b('\x20\x02\x01\x02'))
|
|
- self.assertEquals(der.payload, b("\x01\x02"))
|
|
- self.assertEquals(der.typeTag, 0x20)
|
|
+ self.assertEqual(der.payload, b("\x01\x02"))
|
|
+ self.assertEqual(der.typeTag, 0x20)
|
|
|
|
def testObjDecode2(self):
|
|
# Decode short payload
|
|
der = DerObject()
|
|
der.decode(b('\x22\x81\x80' + "1"*128))
|
|
- self.assertEquals(der.payload, b("1")*128)
|
|
- self.assertEquals(der.typeTag, 0x22)
|
|
+ self.assertEqual(der.payload, b("1")*128)
|
|
+ self.assertEqual(der.typeTag, 0x22)
|
|
|
|
class DerSequenceTests(unittest.TestCase):
|
|
|
|
def testEncode1(self):
|
|
# Empty sequence
|
|
der = DerSequence()
|
|
- self.assertEquals(der.encode(), b('0\x00'))
|
|
- self.failIf(der.hasOnlyInts())
|
|
+ self.assertEqual(der.encode(), b('0\x00'))
|
|
+ self.assertFalse(der.hasOnlyInts())
|
|
# One single-byte integer (zero)
|
|
der.append(0)
|
|
- self.assertEquals(der.encode(), b('0\x03\x02\x01\x00'))
|
|
- self.failUnless(der.hasOnlyInts())
|
|
+ self.assertEqual(der.encode(), b('0\x03\x02\x01\x00'))
|
|
+ self.assertTrue(der.hasOnlyInts())
|
|
# Invariant
|
|
- self.assertEquals(der.encode(), b('0\x03\x02\x01\x00'))
|
|
+ self.assertEqual(der.encode(), b('0\x03\x02\x01\x00'))
|
|
|
|
def testEncode2(self):
|
|
# One single-byte integer (non-zero)
|
|
der = DerSequence()
|
|
der.append(127)
|
|
- self.assertEquals(der.encode(), b('0\x03\x02\x01\x7f'))
|
|
+ self.assertEqual(der.encode(), b('0\x03\x02\x01\x7f'))
|
|
# Indexing
|
|
der[0] = 1
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],1)
|
|
- self.assertEquals(der[-1],1)
|
|
- self.assertEquals(der.encode(), b('0\x03\x02\x01\x01'))
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],1)
|
|
+ self.assertEqual(der[-1],1)
|
|
+ self.assertEqual(der.encode(), b('0\x03\x02\x01\x01'))
|
|
#
|
|
der[:] = [1]
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],1)
|
|
- self.assertEquals(der.encode(), b('0\x03\x02\x01\x01'))
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],1)
|
|
+ self.assertEqual(der.encode(), b('0\x03\x02\x01\x01'))
|
|
|
|
def testEncode3(self):
|
|
# One multi-byte integer (non-zero)
|
|
der = DerSequence()
|
|
- der.append(0x180L)
|
|
- self.assertEquals(der.encode(), b('0\x04\x02\x02\x01\x80'))
|
|
+ der.append(0x180)
|
|
+ self.assertEqual(der.encode(), b('0\x04\x02\x02\x01\x80'))
|
|
|
|
def testEncode4(self):
|
|
# One very long integer
|
|
der = DerSequence()
|
|
der.append(2**2048)
|
|
- self.assertEquals(der.encode(), b('0\x82\x01\x05')+
|
|
+ self.assertEqual(der.encode(), b('0\x82\x01\x05')+
|
|
b('\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00')+
|
|
b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+
|
|
b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+
|
|
@@ -138,31 +138,31 @@ class DerSequenceTests(unittest.TestCase
|
|
def testEncode5(self):
|
|
# One single-byte integer (looks negative)
|
|
der = DerSequence()
|
|
- der.append(0xFFL)
|
|
- self.assertEquals(der.encode(), b('0\x04\x02\x02\x00\xff'))
|
|
+ der.append(0xFF)
|
|
+ self.assertEqual(der.encode(), b('0\x04\x02\x02\x00\xff'))
|
|
|
|
def testEncode6(self):
|
|
# Two integers
|
|
der = DerSequence()
|
|
- der.append(0x180L)
|
|
- der.append(0xFFL)
|
|
- self.assertEquals(der.encode(), b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff'))
|
|
- self.failUnless(der.hasOnlyInts())
|
|
+ der.append(0x180)
|
|
+ der.append(0xFF)
|
|
+ self.assertEqual(der.encode(), b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff'))
|
|
+ self.assertTrue(der.hasOnlyInts())
|
|
#
|
|
der.append(0x01)
|
|
der[1:] = [9,8]
|
|
- self.assertEquals(len(der),3)
|
|
+ self.assertEqual(len(der),3)
|
|
self.assertEqual(der[1:],[9,8])
|
|
self.assertEqual(der[1:-1],[9])
|
|
- self.assertEquals(der.encode(), b('0\x0A\x02\x02\x01\x80\x02\x01\x09\x02\x01\x08'))
|
|
+ self.assertEqual(der.encode(), b('0\x0A\x02\x02\x01\x80\x02\x01\x09\x02\x01\x08'))
|
|
|
|
def testEncode6(self):
|
|
# One integer and another type (no matter what it is)
|
|
der = DerSequence()
|
|
- der.append(0x180L)
|
|
+ der.append(0x180)
|
|
der.append(b('\x00\x02\x00\x00'))
|
|
- self.assertEquals(der.encode(), b('0\x08\x02\x02\x01\x80\x00\x02\x00\x00'))
|
|
- self.failIf(der.hasOnlyInts())
|
|
+ self.assertEqual(der.encode(), b('0\x08\x02\x02\x01\x80\x00\x02\x00\x00'))
|
|
+ self.assertFalse(der.hasOnlyInts())
|
|
|
|
####
|
|
|
|
@@ -170,29 +170,29 @@ class DerSequenceTests(unittest.TestCase
|
|
# Empty sequence
|
|
der = DerSequence()
|
|
der.decode(b('0\x00'))
|
|
- self.assertEquals(len(der),0)
|
|
+ self.assertEqual(len(der),0)
|
|
# One single-byte integer (zero)
|
|
der.decode(b('0\x03\x02\x01\x00'))
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],0)
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],0)
|
|
# Invariant
|
|
der.decode(b('0\x03\x02\x01\x00'))
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],0)
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],0)
|
|
|
|
def testDecode2(self):
|
|
# One single-byte integer (non-zero)
|
|
der = DerSequence()
|
|
der.decode(b('0\x03\x02\x01\x7f'))
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],127)
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],127)
|
|
|
|
def testDecode3(self):
|
|
# One multi-byte integer (non-zero)
|
|
der = DerSequence()
|
|
der.decode(b('0\x04\x02\x02\x01\x80'))
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],0x180L)
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],0x180)
|
|
|
|
def testDecode4(self):
|
|
# One very long integer
|
|
@@ -217,40 +217,40 @@ class DerSequenceTests(unittest.TestCase
|
|
b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+
|
|
b('\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')+
|
|
b('\x00\x00\x00\x00\x00\x00\x00\x00\x00'))
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],2**2048)
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],2**2048)
|
|
|
|
def testDecode5(self):
|
|
# One single-byte integer (looks negative)
|
|
der = DerSequence()
|
|
der.decode(b('0\x04\x02\x02\x00\xff'))
|
|
- self.assertEquals(len(der),1)
|
|
- self.assertEquals(der[0],0xFFL)
|
|
+ self.assertEqual(len(der),1)
|
|
+ self.assertEqual(der[0],0xFF)
|
|
|
|
def testDecode6(self):
|
|
# Two integers
|
|
der = DerSequence()
|
|
der.decode(b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff'))
|
|
- self.assertEquals(len(der),2)
|
|
- self.assertEquals(der[0],0x180L)
|
|
- self.assertEquals(der[1],0xFFL)
|
|
+ self.assertEqual(len(der),2)
|
|
+ self.assertEqual(der[0],0x180)
|
|
+ self.assertEqual(der[1],0xFF)
|
|
|
|
def testDecode7(self):
|
|
# One integer and 2 other types
|
|
der = DerSequence()
|
|
der.decode(b('0\x0A\x02\x02\x01\x80\x24\x02\xb6\x63\x12\x00'))
|
|
- self.assertEquals(len(der),3)
|
|
- self.assertEquals(der[0],0x180L)
|
|
- self.assertEquals(der[1],b('\x24\x02\xb6\x63'))
|
|
- self.assertEquals(der[2],b('\x12\x00'))
|
|
+ self.assertEqual(len(der),3)
|
|
+ self.assertEqual(der[0],0x180)
|
|
+ self.assertEqual(der[1],b('\x24\x02\xb6\x63'))
|
|
+ self.assertEqual(der[2],b('\x12\x00'))
|
|
|
|
def testDecode8(self):
|
|
# Only 2 other types
|
|
der = DerSequence()
|
|
der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00'))
|
|
- self.assertEquals(len(der),2)
|
|
- self.assertEquals(der[0],b('\x24\x02\xb6\x63'))
|
|
- self.assertEquals(der[1],b('\x12\x00'))
|
|
+ self.assertEqual(len(der),2)
|
|
+ self.assertEqual(der[0],b('\x24\x02\xb6\x63'))
|
|
+ self.assertEqual(der[1],b('\x12\x00'))
|
|
|
|
def testErrDecode1(self):
|
|
# Not a sequence
|
|
--- lib/Crypto/SelfTest/Util/test_Counter.py
|
|
+++ lib/Crypto/SelfTest/Util/test_Counter.py
|
|
@@ -73,7 +73,7 @@ class CounterTests(unittest.TestCase):
|
|
self.assertEqual(b("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01"), c())
|
|
self.assertEqual(2, c.next_value())
|
|
self.assertEqual(b("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02"), c())
|
|
- for i in xrange(3, 256):
|
|
+ for i in range(3, 256):
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(b("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")+bchr(i), c())
|
|
self.assertEqual(256, c.next_value())
|
|
@@ -86,7 +86,7 @@ class CounterTests(unittest.TestCase):
|
|
self.assertEqual(b("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), c())
|
|
self.assertEqual(2, c.next_value())
|
|
self.assertEqual(b("\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), c())
|
|
- for i in xrange(3, 256):
|
|
+ for i in range(3, 256):
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i)+b("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), c())
|
|
self.assertEqual(256, c.next_value())
|
|
@@ -95,7 +95,7 @@ class CounterTests(unittest.TestCase):
|
|
def test_BE8_wraparound(self):
|
|
"""8-bit, Big endian, wraparound"""
|
|
c = Counter.new(8)
|
|
- for i in xrange(1, 256):
|
|
+ for i in range(1, 256):
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i), c())
|
|
self.assertRaises(OverflowError, c.next_value)
|
|
@@ -106,7 +106,7 @@ class CounterTests(unittest.TestCase):
|
|
def test_LE8_wraparound(self):
|
|
"""8-bit, Little endian, wraparound"""
|
|
c = Counter.new(8, little_endian=True)
|
|
- for i in xrange(1, 256):
|
|
+ for i in range(1, 256):
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i), c())
|
|
self.assertRaises(OverflowError, c.next_value)
|
|
@@ -117,7 +117,7 @@ class CounterTests(unittest.TestCase):
|
|
def test_BE8_wraparound_allowed(self):
|
|
"""8-bit, Big endian, wraparound with allow_wraparound=True"""
|
|
c = Counter.new(8, allow_wraparound=True)
|
|
- for i in xrange(1, 256):
|
|
+ for i in range(1, 256):
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i), c())
|
|
self.assertEqual(0, c.next_value())
|
|
@@ -127,7 +127,7 @@ class CounterTests(unittest.TestCase):
|
|
def test_LE8_wraparound_allowed(self):
|
|
"""8-bit, Little endian, wraparound with allow_wraparound=True"""
|
|
c = Counter.new(8, little_endian=True, allow_wraparound=True)
|
|
- for i in xrange(1, 256):
|
|
+ for i in range(1, 256):
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i), c())
|
|
self.assertEqual(0, c.next_value())
|
|
@@ -137,7 +137,7 @@ class CounterTests(unittest.TestCase):
|
|
def test_BE8_carry(self):
|
|
"""8-bit, Big endian, carry attribute"""
|
|
c = Counter.new(8)
|
|
- for i in xrange(1, 256):
|
|
+ for i in range(1, 256):
|
|
self.assertEqual(0, c.carry)
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i), c())
|
|
@@ -146,7 +146,7 @@ class CounterTests(unittest.TestCase):
|
|
def test_LE8_carry(self):
|
|
"""8-bit, Little endian, carry attribute"""
|
|
c = Counter.new(8, little_endian=True)
|
|
- for i in xrange(1, 256):
|
|
+ for i in range(1, 256):
|
|
self.assertEqual(0, c.carry)
|
|
self.assertEqual(i, c.next_value())
|
|
self.assertEqual(bchr(i), c())
|
|
--- lib/Crypto/SelfTest/Util/test_number.py
|
|
+++ lib/Crypto/SelfTest/Util/test_number.py
|
|
@@ -71,19 +71,19 @@ class MiscTests(unittest.TestCase):
|
|
for b in range(3, 1+129, 3): # 3, 6, ... , 129
|
|
self.assertEqual(0, number.ceil_shift(0, b))
|
|
|
|
- n = 1L
|
|
- while n <= 2L**(b+2):
|
|
- (q, r) = divmod(n-1, 2L**b)
|
|
+ n = 1
|
|
+ while n <= 2**(b+2):
|
|
+ (q, r) = divmod(n-1, 2**b)
|
|
expected = q + int(not not r)
|
|
self.assertEqual((n-1, b, expected),
|
|
(n-1, b, number.ceil_shift(n-1, b)))
|
|
|
|
- (q, r) = divmod(n, 2L**b)
|
|
+ (q, r) = divmod(n, 2**b)
|
|
expected = q + int(not not r)
|
|
self.assertEqual((n, b, expected),
|
|
(n, b, number.ceil_shift(n, b)))
|
|
|
|
- (q, r) = divmod(n+1, 2L**b)
|
|
+ (q, r) = divmod(n+1, 2**b)
|
|
expected = q + int(not not r)
|
|
self.assertEqual((n+1, b, expected),
|
|
(n+1, b, number.ceil_shift(n+1, b)))
|
|
@@ -182,9 +182,9 @@ class MiscTests(unittest.TestCase):
|
|
n += 1
|
|
|
|
for e in range(16, 1+64, 2):
|
|
- self.assertRaises(ValueError, number.exact_log2, 2L**e-1)
|
|
- self.assertEqual(e, number.exact_log2(2L**e))
|
|
- self.assertRaises(ValueError, number.exact_log2, 2L**e+1)
|
|
+ self.assertRaises(ValueError, number.exact_log2, 2**e-1)
|
|
+ self.assertEqual(e, number.exact_log2(2**e))
|
|
+ self.assertRaises(ValueError, number.exact_log2, 2**e+1)
|
|
|
|
def test_exact_div(self):
|
|
"""Util.number.exact_div"""
|
|
@@ -233,20 +233,20 @@ class MiscTests(unittest.TestCase):
|
|
bits = 512
|
|
x = number.getStrongPrime(bits)
|
|
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+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"""
|
|
@@ -256,28 +256,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/Signature/PKCS1_PSS.py
|
|
+++ lib/Crypto/Signature/PKCS1_PSS.py
|
|
@@ -61,7 +61,7 @@ the RSA key:
|
|
|
|
# Allow nested scopes in Python 2.1
|
|
# See http://oreilly.com/pub/a/python/2001/04/19/pythonnews.html
|
|
-from __future__ import nested_scopes
|
|
+
|
|
|
|
__revision__ = "$Id$"
|
|
__all__ = [ 'new', 'PSS_SigScheme' ]
|
|
@@ -199,7 +199,7 @@ class PSS_SigScheme:
|
|
def MGF1(mgfSeed, maskLen, hash):
|
|
"""Mask Generation Function, described in B.2.1"""
|
|
T = b("")
|
|
- for counter in xrange(ceil_div(maskLen, hash.digest_size)):
|
|
+ for counter in range(ceil_div(maskLen, hash.digest_size)):
|
|
c = long_to_bytes(counter, 4)
|
|
T = T + hash.new(mgfSeed + c).digest()
|
|
assert(len(T)>=maskLen)
|
|
@@ -239,7 +239,7 @@ def EMSA_PSS_ENCODE(mhash, emBits, randF
|
|
|
|
# Bitmask of digits that fill up
|
|
lmask = 0
|
|
- for i in xrange(8*emLen-emBits):
|
|
+ for i in range(8*emLen-emBits):
|
|
lmask = lmask>>1 | 0x80
|
|
|
|
# Step 1 and 2 have been already done
|
|
@@ -297,7 +297,7 @@ def EMSA_PSS_VERIFY(mhash, em, emBits, m
|
|
|
|
# Bitmask of digits that fill up
|
|
lmask = 0
|
|
- for i in xrange(8*emLen-emBits):
|
|
+ for i in range(8*emLen-emBits):
|
|
lmask = lmask>>1 | 0x80
|
|
|
|
# Step 1 and 2 have been already done
|
|
--- lib/Crypto/Util/asn1.py
|
|
+++ lib/Crypto/Util/asn1.py
|
|
@@ -187,7 +187,7 @@ class DerSequence(DerObject):
|
|
|
|
def hasInts(self):
|
|
"""Return the number of items in this sequence that are numbers."""
|
|
- return len(filter(isInt, self._seq))
|
|
+ return len(list(filter(isInt, self._seq)))
|
|
|
|
def hasOnlyInts(self):
|
|
"""Return True if all items in this sequence are numbers."""
|
|
--- lib/Crypto/Util/Counter.py
|
|
+++ lib/Crypto/Util/Counter.py
|
|
@@ -113,7 +113,7 @@ def new(nbits, prefix=b(""), suffix=b(""
|
|
|
|
def _encode(n, nbytes, little_endian=False):
|
|
retval = []
|
|
- n = long(n)
|
|
+ n = int(n)
|
|
for i in range(nbytes):
|
|
if little_endian:
|
|
retval.append(bchr(n & 0xff))
|
|
--- lib/Crypto/Util/_number_new.py
|
|
+++ lib/Crypto/Util/_number_new.py
|
|
@@ -35,11 +35,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:
|
|
@@ -48,7 +48,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)
|
|
@@ -58,7 +58,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)
|
|
@@ -70,10 +70,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")
|
|
|
|
@@ -85,7 +85,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):
|
|
@@ -99,7 +99,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
|
|
+++ 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 _fastma
|
|
_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=Non
|
|
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
|
|
|
|
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
|
|
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_positiv
|
|
|
|
# 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_positiv
|
|
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_positiv
|
|
# 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_positiv
|
|
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,
|
|
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/py3compat.py
|
|
+++ lib/Crypto/Util/py3compat.py
|
|
@@ -79,7 +79,7 @@ if sys.version_info[0] == 2:
|
|
return ''.join(s)
|
|
else:
|
|
def tobytes(s):
|
|
- if isinstance(s, unicode):
|
|
+ if isinstance(s, str):
|
|
return s.encode("latin-1")
|
|
else:
|
|
return ''.join(s)
|
|
--- lib/Crypto/Util/RFC1751.py
|
|
+++ 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:
|
|
|
|
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))
|
|
|
|
|
|
--- pct-speedtest.py
|
|
+++ pct-speedtest.py
|
|
@@ -52,7 +52,7 @@ class Benchmark:
|
|
bytes = bytes_per_block * blocks
|
|
data = self.random_data(bytes)
|
|
retval = []
|
|
- for i in xrange(blocks):
|
|
+ for i in range(blocks):
|
|
p = i * bytes_per_block
|
|
retval.append(data[p:p+bytes_per_block])
|
|
return retval
|
|
--- setup.py
|
|
+++ setup.py
|
|
@@ -44,9 +44,9 @@ from distutils.command.build_ext import
|
|
import os, sys, re
|
|
import struct
|
|
|
|
-if sys.version[0:1] == '1':
|
|
+if sys.version[0:1] != '3':
|
|
raise RuntimeError ("The Python Cryptography Toolkit requires "
|
|
- "Python 2.x or 3.x to build.")
|
|
+ "Python 3.x to build.")
|
|
|
|
# For test development: Set this to 1 to build with gcov support.
|
|
# Use "gcov -p -o build/temp.*/src build/temp.*/src/*.gcda" to build the
|
|
@@ -54,12 +54,7 @@ if sys.version[0:1] == '1':
|
|
USE_GCOV = 0
|
|
|
|
|
|
-try:
|
|
- # Python 3
|
|
- from distutils.command.build_py import build_py_2to3 as build_py
|
|
-except ImportError:
|
|
- # Python 2
|
|
- from distutils.command.build_py import build_py
|
|
+from distutils.command.build_py import build_py
|
|
|
|
# Work around the print / print() issue with Python 2.x and 3.x. We only need
|
|
# to print at one point of the code, which makes this easy
|
|
@@ -390,21 +385,6 @@ kw = {'name':"pycrypto",
|
|
]
|
|
}
|
|
|
|
-# If we're running Python 2.3, add extra information
|
|
-if hasattr(core, 'setup_keywords'):
|
|
- if 'classifiers' in core.setup_keywords:
|
|
- kw['classifiers'] = [
|
|
- 'Development Status :: 5 - Production/Stable',
|
|
- 'License :: Public Domain',
|
|
- 'Intended Audience :: Developers',
|
|
- 'Operating System :: Unix',
|
|
- 'Operating System :: Microsoft :: Windows',
|
|
- 'Operating System :: MacOS :: MacOS X',
|
|
- 'Topic :: Security :: Cryptography',
|
|
- 'Programming Language :: Python :: 2',
|
|
- 'Programming Language :: Python :: 3',
|
|
- ]
|
|
-
|
|
core.setup(**kw)
|
|
|
|
def touch(path):
|