diff options
| author | Legrandin <gooksankoo@hoiptorrow.mailexpire.com> | 2011-10-18 23:20:26 +0200 |
|---|---|---|
| committer | Legrandin <gooksankoo@hoiptorrow.mailexpire.com> | 2011-10-18 23:20:26 +0200 |
| commit | c22fa18c0dedb43a8b19dcb9b29512ba59e1764b (patch) | |
| tree | e7864a848ed2c37d4a2c0d65bcae0f0cbdc6ea27 /lib/Crypto | |
| parent | 897b75983c31a9e2630af92161e6206c2480685e (diff) | |
| parent | b9658a26003ebfcfce1804a2363a29354799b47e (diff) | |
| download | pycrypto-c22fa18c0dedb43a8b19dcb9b29512ba59e1764b.tar.gz | |
Merged from upstream (py3k support) and modified so that all unit tests pass.
Diffstat (limited to 'lib/Crypto')
78 files changed, 1461 insertions, 823 deletions
diff --git a/lib/Crypto/Cipher/PKCS1_OAEP.py b/lib/Crypto/Cipher/PKCS1_OAEP.py index 4c43707..a9f71df 100644 --- a/lib/Crypto/Cipher/PKCS1_OAEP.py +++ b/lib/Crypto/Cipher/PKCS1_OAEP.py @@ -57,6 +57,7 @@ __all__ = [ 'new' ] import Crypto.Signature.PKCS1_PSS import Crypto.Hash.SHA +from Crypto.Util.py3compat import * import Crypto.Util.number from Crypto.Util.number import ceil_div from Crypto.Util.strxor import strxor @@ -144,9 +145,9 @@ class PKCS1OAEP_Cipher: # Step 2a lHash = self._hashObj.new(self._label).digest() # Step 2b - ps = '\x00'*ps_len + ps = bchr(0x00)*ps_len # Step 2c - db = lHash + ps + '\x01' + message + db = lHash + ps + bchr(0x01) + message # Step 2d ros = randFunc(hLen) # Step 2e @@ -158,11 +159,11 @@ class PKCS1OAEP_Cipher: # Step 2h maskedSeed = strxor(ros, seedMask) # Step 2i - em = '\x00' + maskedSeed + maskedDB + em = bchr(0x00) + maskedSeed + maskedDB # Step 3a (OS2IP), step 3b (RSAEP), part of step 3c (I2OSP) m = self._key.encrypt(em, 0)[0] # Complete step 3c (I2OSP) - c = '\x00'*(k-len(m)) + m + c = bchr(0x00)*(k-len(m)) + m return c def decrypt(self, ct): @@ -195,7 +196,7 @@ class PKCS1OAEP_Cipher: # Step 2a (O2SIP), 2b (RSADP), and part of 2c (I2OSP) m = self._key.decrypt(ct) # Complete step 2c (I2OSP) - em = '\x00'*(k-len(m)) + m + em = bchr(0x00)*(k-len(m)) + m # Step 3a lHash = self._hashObj.new(self._label).digest() # Step 3b @@ -214,20 +215,23 @@ class PKCS1OAEP_Cipher: db = strxor(maskedDB, dbMask) # Step 3g valid = 1 - one = db[hLen:].find('\x01') + one = db[hLen:].find(bchr(0x01)) lHash1 = db[:hLen] if lHash1!=lHash: valid = 0 + r = 1 if one<0: valid = 0 - if y!='\x00': + r = 2 + if bord(y)!=0: valid = 0 + r = 3 if not valid: - raise ValueError("Incorrect decryption.") + raise ValueError("Incorrect decryption.",r) # Step 4 return db[hLen+one+1:] -def new(key, hashAlgo=None, mgfunc=None, label=''): +def new(key, hashAlgo=None, mgfunc=None, label=b('')): """Return a cipher object `PKCS1OAEP_Cipher` that can be used to perform PKCS#1 OAEP encryption or decryption. :Parameters: diff --git a/lib/Crypto/Cipher/PKCS1_v1_5.py b/lib/Crypto/Cipher/PKCS1_v1_5.py index 748a327..3f860ee 100644 --- a/lib/Crypto/Cipher/PKCS1_v1_5.py +++ b/lib/Crypto/Cipher/PKCS1_v1_5.py @@ -71,6 +71,7 @@ __revision__ = "$Id$" __all__ = [ 'new' ] from Crypto.Util.number import ceil_div +from Crypto.Util.py3compat import * import Crypto.Util.number class PKCS115_Cipher: @@ -87,11 +88,11 @@ class PKCS115_Cipher: self._key = key def can_encrypt(self): - """Return True/1 if this cipher object can be used for encryption.""" + """Return True if this cipher object can be used for encryption.""" return self._key.can_encrypt() def can_decrypt(self): - """Return True/1 if this cipher object can be used for decryption.""" + """Return True if this cipher object can be used for decryption.""" return self._key.can_decrypt() def encrypt(self, message): @@ -102,11 +103,11 @@ class PKCS115_Cipher: For a complete example see `Crypto.Cipher.PKCS1_v1_5`. :Parameters: - message : string + message : byte string The message to encrypt, also known as plaintext. It can be of variable length, but not longer than the RSA modulus (in bytes) minus 11. - :Return: A string, the ciphertext in which the message is encrypted. + :Return: A byte string, the ciphertext in which the message is encrypted. It is as long as the RSA modulus (in bytes). :Raise ValueError: If the RSA key length is not sufficiently long to deal with the given @@ -129,15 +130,15 @@ class PKCS115_Cipher: class nonZeroRandByte: def __init__(self, rf): self.rf=rf def __call__(self, c): - while c=='\x00': c=self.rf(1) + while bord(c)==0x00: c=self.rf(1)[0] return c - ps = "".join(map(nonZeroRandByte(randFunc), randFunc(k-mLen-3))) + ps = tobytes(map(nonZeroRandByte(randFunc), randFunc(k-mLen-3))) # Step 2b - em = '\x00\x02' + ps + '\x00' + message + em = b('\x00\x02') + ps + bchr(0x00) + message # Step 3a (OS2IP), step 3b (RSAEP), part of step 3c (I2OSP) m = self._key.encrypt(em, 0)[0] # Complete step 3c (I2OSP) - c = '\x00'*(k-len(m)) + m + c = bchr(0x00)*(k-len(m)) + m return c def decrypt(self, ct, sentinel): @@ -148,12 +149,12 @@ class PKCS115_Cipher: For a complete example see `Crypto.Cipher.PKCS1_v1_5`. :Parameters: - ct : string + ct : byte string The ciphertext that contains the message to recover. - sentinel : string - The string to return to indicate that an error was detected during decryption. + sentinel : any type + The object to return to indicate that an error was detected during decryption. - :Return: A string. It is either the original message or the ``sentinel`` (in case of an error). + :Return: A byte string. It is either the original message or the ``sentinel`` (in case of an error). :Raise ValueError: If the ciphertext length is incorrect :Raise TypeError: @@ -204,10 +205,10 @@ class PKCS115_Cipher: # Step 2a (O2SIP), 2b (RSADP), and part of 2c (I2OSP) m = self._key.decrypt(ct) # Complete step 2c (I2OSP) - em = '\x00'*(k-len(m)) + m + em = bchr(0x00)*(k-len(m)) + m # Step 3 - sep = em.find('\x00',2) - if not em.startswith('\x00\x02') or sep<10: + sep = em.find(bchr(0x00),2) + if not em.startswith(b('\x00\x02')) or sep<10: return sentinel # Step 4 return em[sep+1:] diff --git a/lib/Crypto/Hash/HMAC.py b/lib/Crypto/Hash/HMAC.py index 96e0afc..b09cb36 100644 --- a/lib/Crypto/Hash/HMAC.py +++ b/lib/Crypto/Hash/HMAC.py @@ -43,9 +43,8 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] -import string - from Crypto.Util.strxor import strxor_c +from Crypto.Util.py3compat import * # The size of the digests returned by HMAC depends on the underlying # hashing module used. @@ -64,7 +63,7 @@ class HMAC: msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ - if digestmod == None: + if digestmod is None: import MD5 digestmod = MD5 @@ -89,7 +88,7 @@ class HMAC: if len(key) > blocksize: key = digestmod.new(key).digest() - key = key + chr(0) * (blocksize - len(key)) + key = key + bchr(0) * (blocksize - len(key)) self.outer.update(strxor_c(key, opad)) self.inner.update(strxor_c(key, ipad)) if (msg): @@ -108,7 +107,7 @@ class HMAC: An update to this copy won't affect the original object. """ - other = HMAC("") + other = HMAC(b("")) other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() @@ -128,8 +127,8 @@ class HMAC: def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ - return "".join([string.zfill(hex(ord(x))[2:], 2) - for x in tuple(self.digest())]) + return "".join(["%02x" % bord(x) + for x in tuple(self.digest())]) def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. diff --git a/lib/Crypto/Hash/MD2.py b/lib/Crypto/Hash/MD2.py index 9c61fea..953f763 100644 --- a/lib/Crypto/Hash/MD2.py +++ b/lib/Crypto/Hash/MD2.py @@ -23,6 +23,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for MD2 is: # @@ -31,9 +32,9 @@ from Crypto.Util.wrapper import Wrapper # digestAlgorithm(2) 2 # } -oid = '\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02' +oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/MD4.py b/lib/Crypto/Hash/MD4.py index b5b244e..8a9f595 100644 --- a/lib/Crypto/Hash/MD4.py +++ b/lib/Crypto/Hash/MD4.py @@ -23,6 +23,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for MD4 is: # @@ -31,9 +32,9 @@ from Crypto.Util.wrapper import Wrapper # digestAlgorithm(2) 4 # } -oid = '\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04' +oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/MD5.py b/lib/Crypto/Hash/MD5.py index 366cce2..91e5da7 100644 --- a/lib/Crypto/Hash/MD5.py +++ b/lib/Crypto/Hash/MD5.py @@ -25,6 +25,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for MD5 is: # @@ -32,9 +33,9 @@ from Crypto.Util.wrapper import Wrapper # iso(1) member-body(2) us(840) rsadsi(113549) # digestAlgorithm(2) 5 # } -oid = '\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05' +oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/RIPEMD.py b/lib/Crypto/Hash/RIPEMD.py index bcc1409..4a6c7bf 100644 --- a/lib/Crypto/Hash/RIPEMD.py +++ b/lib/Crypto/Hash/RIPEMD.py @@ -23,6 +23,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # # See http://homes.esat.kuleuven.be/~bosselae/ripemd160.html#More @@ -32,9 +33,9 @@ from Crypto.Util.wrapper import Wrapper # algorithm(3) hashAlgorithm(2) ripemd160(1) # } -oid = "\x06\x05\x2b\x24\x03\x02\x01" +oid = b("\x06\x05\x2b\x24\x03\x02\x01") -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/SHA.py b/lib/Crypto/Hash/SHA.py index b7a8041..e9cd118 100644 --- a/lib/Crypto/Hash/SHA.py +++ b/lib/Crypto/Hash/SHA.py @@ -24,6 +24,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] +from Crypto.Util.py3compat import * from Crypto.Util.wrapper import Wrapper # The OID for SHA-1 is: @@ -32,9 +33,9 @@ from Crypto.Util.wrapper import Wrapper # iso(1) identified-organization(3) oiw(14) secsig(3) # algorithms(2) 26 # } -oid = '\x06\x05\x2b\x0e\x03\x02\x1a' +oid = b('\x06\x05\x2b\x0e\x03\x02\x1a') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/SHA224.py b/lib/Crypto/Hash/SHA224.py index 4884390..872ed81 100644 --- a/lib/Crypto/Hash/SHA224.py +++ b/lib/Crypto/Hash/SHA224.py @@ -25,6 +25,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for SHA-224 is: # @@ -33,9 +34,9 @@ from Crypto.Util.wrapper import Wrapper # country(16) us(840) organization(1) gov(101) csor(3) # nistalgorithm(4) hashalgs(2) 4 # } -oid = '\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04' +oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/SHA256.py b/lib/Crypto/Hash/SHA256.py index 4a3d615..f583ed9 100644 --- a/lib/Crypto/Hash/SHA256.py +++ b/lib/Crypto/Hash/SHA256.py @@ -23,6 +23,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for SHA-256 is: # @@ -31,9 +32,9 @@ from Crypto.Util.wrapper import Wrapper # gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 # } # -oid = '\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01' +oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/SHA384.py b/lib/Crypto/Hash/SHA384.py index 76d400a..1549e8e 100644 --- a/lib/Crypto/Hash/SHA384.py +++ b/lib/Crypto/Hash/SHA384.py @@ -25,6 +25,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for SHA-384 is: # @@ -33,9 +34,9 @@ from Crypto.Util.wrapper import Wrapper # country(16) us(840) organization(1) gov(101) csor(3) # nistalgorithm(4) hashalgs(2) 2 # } -oid = '\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02' +oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Hash/SHA512.py b/lib/Crypto/Hash/SHA512.py index bb5ac87..182ec74 100644 --- a/lib/Crypto/Hash/SHA512.py +++ b/lib/Crypto/Hash/SHA512.py @@ -25,6 +25,7 @@ __revision__ = "$Id$" __all__ = ['new', 'digest_size'] from Crypto.Util.wrapper import Wrapper +from Crypto.Util.py3compat import * # The OID for SHA-512 is: # @@ -33,9 +34,9 @@ from Crypto.Util.wrapper import Wrapper # country(16) us(840) organization(1) gov(101) csor(3) # nistalgorithm(4) hashalgs(2) 3 # } -oid = '\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03' +oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03') -def new(data=""): +def new(data=b("")): obj = Wrapper(hashFactory, data) obj.oid = oid obj.new = globals()['new'] diff --git a/lib/Crypto/Protocol/AllOrNothing.py b/lib/Crypto/Protocol/AllOrNothing.py index 4b00c0b..4ece960 100644 --- a/lib/Crypto/Protocol/AllOrNothing.py +++ b/lib/Crypto/Protocol/AllOrNothing.py @@ -45,8 +45,9 @@ http://theory.lcs.mit.edu/~rivest/fusion.pdf __revision__ = "$Id$" import operator -import string +import sys from Crypto.Util.number import bytes_to_long, long_to_bytes +from Crypto.Util.py3compat import * @@ -83,7 +84,7 @@ class AllOrNothing: if self.__key_size == 0: self.__key_size = 16 - __K0digit = chr(0x69) + __K0digit = bchr(0x69) def digest(self, text): """digest(text:string) : [string] @@ -113,7 +114,7 @@ class AllOrNothing: # the undigest() step. block_size = self.__ciphermodule.block_size padbytes = block_size - (len(text) % block_size) - text = text + ' ' * padbytes + text = text + b(' ') * padbytes # Run through the algorithm: # s: number of message blocks (size of text / block_size) @@ -127,7 +128,7 @@ class AllOrNothing: # The one complication I add is that the last message block is hard # coded to the number of padbytes added, so that these can be stripped # during the undigest() step - s = len(text) / block_size + s = divmod(len(text), block_size)[0] blocks = [] hashes = [] for i in range(1, s+1): @@ -189,13 +190,14 @@ class AllOrNothing: # encrypted, and create the hash cipher. K0 = self.__K0digit * self.__key_size hcipher = self.__newcipher(K0) + block_size = self.__ciphermodule.block_size # Since we have all the blocks (or this method would have been called - # prematurely), we can calcualte all the hash blocks. + # prematurely), we can calculate all the hash blocks. hashes = [] for i in range(1, len(blocks)): mticki = blocks[i-1] ^ i - hi = hcipher.encrypt(long_to_bytes(mticki)) + hi = hcipher.encrypt(long_to_bytes(mticki, block_size)) hashes.append(bytes_to_long(hi)) # now we can calculate K' (key). remember the last block contains @@ -203,8 +205,7 @@ class AllOrNothing: key = blocks[-1] ^ reduce(operator.xor, hashes) # and now we can create the cipher object - mcipher = self.__newcipher(long_to_bytes(key)) - block_size = self.__ciphermodule.block_size + mcipher = self.__newcipher(long_to_bytes(key, self.__key_size)) # And we can now decode the original message blocks parts = [] @@ -218,7 +219,7 @@ class AllOrNothing: # of the cipher's block_size. This number should be small enough that # the conversion from long integer to integer should never overflow padbytes = int(parts[-1]) - text = string.join(map(long_to_bytes, parts[:-1]), '') + text = b('').join(map(long_to_bytes, parts[:-1])) return text[:-padbytes] def _inventkey(self, key_size): @@ -289,13 +290,13 @@ Where: # ugly hack to force __import__ to give us the end-path module module = __import__('Crypto.Cipher.'+ciphermodule, None, None, ['new']) - a = AllOrNothing(module) + x = AllOrNothing(module) print 'Original text:\n==========' print __doc__ print '==========' - msgblocks = a.digest(__doc__) + msgblocks = x.digest(b(__doc__)) print 'message blocks:' - for i, blk in map(None, range(len(msgblocks)), msgblocks): + for i, blk in zip(range(len(msgblocks)), msgblocks): # base64 adds a trailing newline print ' %3d' % i, if aslong: @@ -304,9 +305,9 @@ Where: print base64.encodestring(blk)[:-1] # # get a new undigest-only object so there's no leakage - b = AllOrNothing(module) - text = b.undigest(msgblocks) - if text == __doc__: + y = AllOrNothing(module) + text = y.undigest(msgblocks) + if text == b(__doc__): print 'They match!' else: print 'They differ!' diff --git a/lib/Crypto/Protocol/Chaffing.py b/lib/Crypto/Protocol/Chaffing.py index ba272ab..c19e037 100644 --- a/lib/Crypto/Protocol/Chaffing.py +++ b/lib/Crypto/Protocol/Chaffing.py @@ -140,7 +140,7 @@ class Chaff: # chaffed. count = len(blocks) * self.__factor blocksper = range(self.__blocksper) - for i, wheat in map(None, range(len(blocks)), blocks): + for i, wheat in zip(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 @@ -205,7 +205,7 @@ likely to effect their Safety and Happiness. # put these into a form acceptable as input to the chaffing procedure source = [] - m = map(None, range(len(blocks)), blocks, macs) + m = zip(range(len(blocks)), blocks, macs) print m for i, data, mac in m: source.append((i, data, mac)) @@ -237,6 +237,7 @@ likely to effect their Safety and Happiness. # now decode the message packets and check it against the original text 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!' diff --git a/lib/Crypto/Protocol/KDF.py b/lib/Crypto/Protocol/KDF.py index 301ae4f..c6979c8 100644 --- a/lib/Crypto/Protocol/KDF.py +++ b/lib/Crypto/Protocol/KDF.py @@ -38,6 +38,7 @@ __revision__ = "$Id$" import math import struct +from Crypto.Util.py3compat import * from Crypto.Hash import SHA as SHA1, HMAC from Crypto.Util.strxor import strxor @@ -54,7 +55,7 @@ def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=SHA1): :Parameters: password : string The secret password or pass phrase to generate the key from. - salt : string + salt : byte string An 8 byte string to use for better protection from dictionary attacks. This value does not need to be kept secret, but it should be randomly chosen for each derivation. @@ -68,6 +69,7 @@ def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=SHA1): :Return: A byte string of length `dkLen` that can be used as key. """ + password = tobytes(password) pHash = hashAlgo.new(password+salt) digest = pHash.digest_size if dkLen>digest: @@ -102,9 +104,10 @@ def PBKDF2(password, salt, dkLen=16, count=1000, prf=None): :Return: A byte string of length `dkLen` that can be used as key material. If you wanted multiple keys, just break up this string into segments of the desired length. """ + password = tobytes(password) if prf is None: prf = lambda p,s: HMAC.new(p,s,SHA1).digest() - key = '' + key = b('') i = 1 while len(key)<dkLen: U = previousU = prf(password,salt+struct.pack(">I", i)) diff --git a/lib/Crypto/PublicKey/DSA.py b/lib/Crypto/PublicKey/DSA.py index 6349cef..5c349a9 100644 --- a/lib/Crypto/PublicKey/DSA.py +++ b/lib/Crypto/PublicKey/DSA.py @@ -28,7 +28,9 @@ __revision__ = "$Id$" __all__ = ['generate', 'construct', 'error'] -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * from Crypto.PublicKey import _DSA, _slowmath, pubkey from Crypto import Random @@ -118,6 +120,7 @@ class _DSAobj(pubkey.pubkey): attrs.append(k) if self.has_private(): attrs.append("private") + # PY3K: This is meant to be text, do not change to bytes (data) return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs)) class DSAImplementation(object): diff --git a/lib/Crypto/PublicKey/RSA.py b/lib/Crypto/PublicKey/RSA.py index fadfa22..31cd6fa 100644 --- a/lib/Crypto/PublicKey/RSA.py +++ b/lib/Crypto/PublicKey/RSA.py @@ -32,7 +32,11 @@ __revision__ = "$Id$" __all__ = ['generate', 'construct', 'error', 'importKey' ] -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * +#from Crypto.Util.python_compat import * from Crypto.Util.number import getRandomRange, bytes_to_long, long_to_bytes from Crypto.PublicKey import _RSA, _slowmath, pubkey @@ -164,6 +168,7 @@ class _RSAobj(pubkey.pubkey): attrs.append(k) if self.has_private(): attrs.append("private") + # PY3K: This is meant to be text, do not change to bytes (data) return "<%s @0x%x %s>" % (self.__class__.__name__, id(self), ",".join(attrs)) def exportKey(self, format='PEM', passphrase=None, pkcs=1): @@ -192,11 +197,13 @@ class _RSAobj(pubkey.pubkey): :Raise ValueError: When the format is unknown. """ + if passphrase is not None: + passphrase = tobytes(passphrase) if format=='OpenSSH': eb = long_to_bytes(self.e) nb = long_to_bytes(self.n) - if ord(eb[0]) & 0x80: eb='\x00'+eb - if ord(nb[0]) & 0x80: nb='\x00'+nb + if bord(eb[0]) & 0x80: eb=bchr(0x00)+eb + if bord(nb[0]) & 0x80: nb=bchr(0x00)+nb keyparts = [ 'ssh-rsa', eb, nb ] keystring = ''.join([ struct.pack(">I",len(kp))+kp for kp in keyparts]) return 'ssh-rsa '+binascii.b2a_base64(keystring)[:-1] @@ -219,12 +226,12 @@ class _RSAobj(pubkey.pubkey): der.append(algorithmIdentifier) bitmap = DerObject('BIT STRING') derPK = DerSequence( [ self.n, self.e ] ) - bitmap.payload = '\x00' + derPK.encode() + bitmap.payload = bchr(0x00) + derPK.encode() der.append(bitmap.encode()) if format=='DER': return der.encode() if format=='PEM': - pem = "-----BEGIN %s KEY-----\n" % keyType + pem = b("-----BEGIN " + keyType + " KEY-----\n") objenc = None if passphrase and keyType.endswith('PRIVATE'): # We only support 3DES for encryption @@ -235,19 +242,19 @@ class _RSAobj(pubkey.pubkey): key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5) key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5) objenc = DES3.new(key, Crypto.Cipher.DES3.MODE_CBC, salt) - pem += 'Proc-Type: 4,ENCRYPTED\n' - pem += 'DEK-Info: DES-EDE3-CBC,' + binascii.b2a_hex(salt).upper() + '\n\n' + pem += b('Proc-Type: 4,ENCRYPTED\n') + pem += b('DEK-Info: DES-EDE3-CBC,') + binascii.b2a_hex(salt).upper() + b('\n\n') binaryKey = der.encode() if objenc: # Add PKCS#7-like padding padding = objenc.block_size-len(binaryKey)%objenc.block_size - binaryKey = objenc.encrypt(binaryKey+chr(padding)*padding) + binaryKey = objenc.encrypt(binaryKey+bchr(padding)*padding) # Each BASE64 line can take up to 64 characters (=48 bytes of data) chunks = [ binascii.b2a_base64(binaryKey[i:i+48]) for i in range(0, len(binaryKey), 48) ] - pem += ''.join(chunks) - pem += "-----END %s KEY-----" % keyType + pem += b('').join(chunks) + pem += b("-----END " + keyType + " KEY-----") return pem return ValueError("Unknown key format '%s'. Cannot export the RSA key." % format) @@ -345,7 +352,7 @@ class RSAImplementation(object): **e** is not odd or smaller than 2. """ if bits < 1024 or (bits & 0xff) != 0: - # pubkey.getStrongPrime doesn't like anything that's not a multiple of 128 and > 512 + # pubkey.getStrongPrime doesn't like anything that's not a multiple of 256 and >= 1024 raise ValueError("RSA modulus length must be a multiple of 256 and >= 1024") if e%2==0 or e<3: raise ValueError("RSA public exponent must be a positive, odd integer larger than 2.") @@ -407,7 +414,7 @@ class RSAImplementation(object): if der[0]==algorithmIdentifier: bitmap = DerObject() bitmap.decode(der[1], True) - if bitmap.isType('BIT STRING') and bitmap.payload[0]=='\x00': + if bitmap.isType('BIT STRING') and bord(bitmap.payload[0])==0x00: der.decode(bitmap.payload[1:], True) if len(der)==2 and der.hasOnlyInts(): return self.construct(der[:]) @@ -452,26 +459,30 @@ class RSAImplementation(object): :Raise ValueError/IndexError/TypeError: When the given key cannot be parsed (possibly because the pass phrase is wrong). """ - if externKey.startswith('-----'): + externKey = tobytes(externKey) + if passphrase is not None: + passphrase = tobytes(passphrase) + + if externKey.startswith(b('-----')): # This is probably a PEM encoded key - lines = externKey.replace(" ",'').split() + lines = externKey.replace(b(" "),b('')).split() keyobj = None # The encrypted PEM format - if lines[1].startswith('Proc-Type:4,ENCRYPTED'): - DEK = lines[2].split(':') - if len(DEK)!=2 or DEK[0]!='DEK-Info' or not passphrase: + if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')): + DEK = lines[2].split(b(':')) + if len(DEK)!=2 or DEK[0]!=b('DEK-Info') or not passphrase: raise ValueError("PEM encryption format not supported.") - algo, salt = DEK[1].split(',') + algo, salt = DEK[1].split(b(',')) salt = binascii.a2b_hex(salt) import Crypto.Hash.MD5 from Crypto.Cipher import DES, DES3 from Crypto.Protocol.KDF import PBKDF1 - if algo=="DES-CBC": + if algo==b("DES-CBC"): # This is EVP_BytesToKey in OpenSSL key = PBKDF1(passphrase, salt, 8, 1, Crypto.Hash.MD5) keyobj = DES.new(key, Crypto.Cipher.DES.MODE_CBC, salt) - elif algo=="DES-EDE3-CBC": + elif algo==b("DES-EDE3-CBC"): # Note that EVP_BytesToKey is note exactly the same as PBKDF1 key = PBKDF1(passphrase, salt, 16, 1, Crypto.Hash.MD5) key += PBKDF1(key+passphrase, salt, 8, 1, Crypto.Hash.MD5) @@ -480,16 +491,16 @@ class RSAImplementation(object): raise ValueError("Unsupport PEM encryption algorithm.") lines = lines[2:] - der = binascii.a2b_base64(''.join(lines[1:-1])) + der = binascii.a2b_base64(b('').join(lines[1:-1])) if keyobj: der = keyobj.decrypt(der) - padding = ord(der[-1]) + padding = bord(der[-1]) der = der[:-padding] return self._importKeyDER(der) - if externKey.startswith('ssh-rsa '): + if externKey.startswith(b('ssh-rsa ')): # This is probably an OpenSSH key - keystring = binascii.a2b_base64(externKey.split(' ')[1]) + keystring = binascii.a2b_base64(externKey.split(b(' '))[1]) keyparts = [] while len(keystring)>4: l = struct.unpack(">I",keystring[:4])[0] @@ -498,9 +509,10 @@ class RSAImplementation(object): e = bytes_to_long(keyparts[1]) n = bytes_to_long(keyparts[2]) return self.construct([n, e]) - if externKey[0]=='\x30': + if bord(externKey[0])==0x30: # This is probably a DER encoded key return self._importKeyDER(externKey) + raise ValueError("RSA key format is not supported") #: This is the ASN.1 DER object that qualifies an algorithm as @@ -512,7 +524,7 @@ class RSAImplementation(object): # rsaEncryption (1 2 840 113549 1 1 1) (PKCS #1) # 0x05 0x00 NULL algorithmIdentifier = DerSequence( - [ '\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01', + [ b('\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x01'), DerNull().encode() ] ).encode() diff --git a/lib/Crypto/PublicKey/_DSA.py b/lib/Crypto/PublicKey/_DSA.py index de1e0e6..6b7a964 100644 --- a/lib/Crypto/PublicKey/_DSA.py +++ b/lib/Crypto/PublicKey/_DSA.py @@ -31,6 +31,7 @@ from Crypto.PublicKey.pubkey import * from Crypto.Util import number from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.Hash import SHA +from Crypto.Util.py3compat import * class error (Exception): pass @@ -41,7 +42,7 @@ def generateQ(randfunc): hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): - c=ord(hash1[i])^ord(hash2[i]) + c=bord(hash1[i])^bord(hash2[i]) if i==0: c=c | 128 if i==19: @@ -76,7 +77,7 @@ def generate_py(bits, randfunc, progress_func=None): powL1=pow(bignum(2), bits-1) while C<4096: for k in range(0, n+1): - V[k]=bytes_to_long(SHA.new(S+str(N)+str(k)).digest()) + 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] diff --git a/lib/Crypto/PublicKey/_slowmath.py b/lib/Crypto/PublicKey/_slowmath.py index b6c2c20..d926596 100644 --- a/lib/Crypto/PublicKey/_slowmath.py +++ b/lib/Crypto/PublicKey/_slowmath.py @@ -28,8 +28,10 @@ __revision__ = "$Id$" __all__ = ['rsa_construct'] -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * from Crypto.Util.number import size, inverse, GCD class error(Exception): @@ -103,7 +105,7 @@ def rsa_construct(n, e, d=None, p=None, q=None, u=None): # and can be represented as t*2^s. t = ktot while t%2==0: - t=t/2 + t=divmod(t,2)[0] # Cycle through all multiplicative inverses in Zn. # The algorithm is non-deterministic, but there is a 50% chance # any candidate a leads to successful factoring. @@ -130,7 +132,7 @@ def rsa_construct(n, e, d=None, p=None, q=None, u=None): raise ValueError("Unable to compute factors p and q from exponent d.") # Found ! assert ((n % obj.p)==0) - obj.q = n/obj.p + obj.q = divmod(n,obj.p)[0] if u is not None: obj.u = u else: diff --git a/lib/Crypto/PublicKey/qNEW.py b/lib/Crypto/PublicKey/qNEW.py index 484e9e4..fc1fd9b 100644 --- a/lib/Crypto/PublicKey/qNEW.py +++ b/lib/Crypto/PublicKey/qNEW.py @@ -29,6 +29,7 @@ __revision__ = "$Id$" from Crypto.PublicKey import pubkey from Crypto.Util.number import * from Crypto.Hash import SHA +from Crypto.Util.py3compat import * class error (Exception): pass @@ -70,7 +71,7 @@ def generate(bits, randfunc, progress_func=None): # data, that are assembled to produce a candidate # value for p. for k in range(0, n+1): - V[k]=bytes_to_long(SHA.new(S+str(N)+str(k)).digest()) + V[k]=bytes_to_long(SHA.new(S+bytes(N)+bytes(k)).digest()) p = V[n] % powb for k in range(n-1, -1, -1): p= (p << long(HASHBITS) )+V[k] diff --git a/lib/Crypto/Random/Fortuna/FortunaAccumulator.py b/lib/Crypto/Random/Fortuna/FortunaAccumulator.py index 3d35c23..5ebbe2b 100644 --- a/lib/Crypto/Random/Fortuna/FortunaAccumulator.py +++ b/lib/Crypto/Random/Fortuna/FortunaAccumulator.py @@ -24,8 +24,11 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * - +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * + from binascii import b2a_hex import time import warnings @@ -59,7 +62,10 @@ class FortunaPool(object): return self._h.digest() def hexdigest(self): - return b2a_hex(self.digest()) + if sys.version_info[0] == 2: + return b2a_hex(self.digest()) + else: + return b2a_hex(self.digest()).decode() def reset(self): self._h = SHAd256.new() @@ -105,7 +111,7 @@ class FortunaAccumulator(object): def random_data(self, bytes): current_time = time.time() - if self.last_reseed > current_time: + if (self.last_reseed is not None and self.last_reseed > current_time): # Avoid float comparison to None to make Py3k happy warnings.warn("Clock rewind detected. Resetting last_reseed.", ClockRewindWarning) self.last_reseed = None if (self.pools[0].length >= self.min_pool_size and @@ -125,15 +131,15 @@ class FortunaAccumulator(object): seed.append(self.pools[i].digest()) self.pools[i].reset() - seed = "".join(seed) + seed = b("").join(seed) self.generator.reseed(seed) def add_random_event(self, source_number, pool_number, data): assert 1 <= len(data) <= 32 assert 0 <= source_number <= 255 assert 0 <= pool_number <= 31 - self.pools[pool_number].append(chr(source_number)) - self.pools[pool_number].append(chr(len(data))) + self.pools[pool_number].append(bchr(source_number)) + self.pools[pool_number].append(bchr(len(data))) self.pools[pool_number].append(data) # vim:set ts=4 sw=4 sts=4 expandtab: diff --git a/lib/Crypto/Random/Fortuna/FortunaGenerator.py b/lib/Crypto/Random/Fortuna/FortunaGenerator.py index 69733da..723fa63 100644 --- a/lib/Crypto/Random/Fortuna/FortunaGenerator.py +++ b/lib/Crypto/Random/Fortuna/FortunaGenerator.py @@ -24,7 +24,10 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] is 2 and sys.version_info[1] is 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * import struct @@ -57,7 +60,7 @@ class AESGenerator(object): # without rekeying. max_blocks_per_request = 2**16 # Allow no more than this number of blocks per _pseudo_random_data request - _four_kiblocks_of_zeros = "\0" * block_size * 4096 + _four_kiblocks_of_zeros = b("\0") * block_size * 4096 def __init__(self): self.counter = Counter.new(nbits=self.block_size*8, initial_value=0, little_endian=True) @@ -74,7 +77,8 @@ class AESGenerator(object): def reseed(self, seed): if self.key is None: - self.key = "\0" * self.key_size + self.key = b("\0") * self.key_size + self._set_key(SHAd256.new(self.key + seed).digest()) self.counter() # increment counter assert len(self.key) == self.key_size @@ -89,8 +93,8 @@ class AESGenerator(object): for i in xrange(num_full_blocks): retval.append(self._pseudo_random_data(1<<20)) retval.append(self._pseudo_random_data(remainder)) - - return "".join(retval) + + return b("").join(retval) def _set_key(self, key): self.key = key @@ -123,6 +127,6 @@ class AESGenerator(object): 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])) - return "".join(retval) + return b("").join(retval) # vim:set ts=4 sw=4 sts=4 expandtab: diff --git a/lib/Crypto/Random/Fortuna/SHAd256.py b/lib/Crypto/Random/Fortuna/SHAd256.py index 8b63cb2..2e135c9 100644 --- a/lib/Crypto/Random/Fortuna/SHAd256.py +++ b/lib/Crypto/Random/Fortuna/SHAd256.py @@ -31,7 +31,10 @@ This module should comply with PEP 247. __revision__ = "$Id$" __all__ = ['new', 'digest_size'] -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * from binascii import b2a_hex @@ -71,7 +74,10 @@ class _SHAd256(object): """Return the hash value of this object as a (lowercase) hexadecimal string""" retval = b2a_hex(self.digest()) assert len(retval) == 64 - return retval + if sys.version_info[0] == 2: + return retval + else: + return retval.decode() # PEP 247 "update" method def update(self, data): @@ -81,8 +87,10 @@ class _SHAd256(object): digest_size = _SHAd256.digest_size # PEP 247 module-level "new" function -def new(data=""): +def new(data=None): """Return a new SHAd256 hashing object""" + if not data: + data=b("") sha = _SHAd256(_SHAd256._internal, SHA256.new(data)) sha.new = globals()['new'] return sha diff --git a/lib/Crypto/Random/OSRNG/rng_base.py b/lib/Crypto/Random/OSRNG/rng_base.py index 2f49019..54c3aa0 100644 --- a/lib/Crypto/Random/OSRNG/rng_base.py +++ b/lib/Crypto/Random/OSRNG/rng_base.py @@ -23,7 +23,9 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * class BaseRNG(object): diff --git a/lib/Crypto/Random/_UserFriendlyRNG.py b/lib/Crypto/Random/_UserFriendlyRNG.py index fd40e96..c2a2eae 100644 --- a/lib/Crypto/Random/_UserFriendlyRNG.py +++ b/lib/Crypto/Random/_UserFriendlyRNG.py @@ -24,7 +24,9 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * import os import threading diff --git a/lib/Crypto/Random/random.py b/lib/Crypto/Random/random.py index e45a87b..bef02e6 100644 --- a/lib/Crypto/Random/random.py +++ b/lib/Crypto/Random/random.py @@ -28,8 +28,9 @@ __revision__ = "$Id$" __all__ = ['StrongRandom', 'getrandbits', 'randrange', 'randint', 'choice', 'shuffle', 'sample'] from Crypto import Random - -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * class StrongRandom(object): def __init__(self, rng=None, randfunc=None): @@ -108,9 +109,7 @@ class StrongRandom(object): # Choose a random item (without replacement) until all the items have been # chosen. for i in xrange(len(x)): - p = self.randint(len(items)) - x[i] = items[p] - del items[p] + x[i] = items.pop(self.randrange(len(items))) def sample(self, population, k): """Return a k-length list of unique elements chosen from the population sequence.""" @@ -123,7 +122,7 @@ class StrongRandom(object): selected = {} # we emulate a set using a dict here for i in xrange(k): r = None - while r is None or r in selected: + while r is None or selected.has_key(r): r = self.randrange(num_choices) retval.append(population[r]) selected[r] = 1 diff --git a/lib/Crypto/SelfTest/Cipher/common.py b/lib/Crypto/SelfTest/Cipher/common.py index 10d9686..af34e97 100644 --- a/lib/Crypto/SelfTest/Cipher/common.py +++ b/lib/Crypto/SelfTest/Cipher/common.py @@ -29,6 +29,7 @@ __revision__ = "$Id$" import sys import unittest from binascii import a2b_hex, b2a_hex +from Crypto.Util.py3compat import * # For compatibility with Python 2.1 and Python 2.2 if sys.hexversion < 0x02030000: @@ -37,7 +38,7 @@ if sys.hexversion < 0x02030000: def dict(**kwargs): return kwargs.copy() else: - dict = __builtins__['dict'] + dict = dict class _NoDefault: pass # sentinel object def _extract(d, k, default=_NoDefault): @@ -61,9 +62,9 @@ class CipherSelfTest(unittest.TestCase): # Extract the parameters params = params.copy() self.description = _extract(params, 'description') - self.key = _extract(params, 'key') - self.plaintext = _extract(params, 'plaintext') - self.ciphertext = _extract(params, 'ciphertext') + self.key = b(_extract(params, 'key')) + self.plaintext = b(_extract(params, 'plaintext')) + self.ciphertext = b(_extract(params, 'ciphertext')) self.module_name = _extract(params, 'module_name', None) mode = _extract(params, 'mode', None) @@ -72,6 +73,7 @@ class CipherSelfTest(unittest.TestCase): # Block cipher self.mode = getattr(self.module, "MODE_" + mode) self.iv = _extract(params, 'iv', None) + if self.iv is not None: self.iv = b(self.iv) else: # Stream cipher self.mode = None @@ -90,8 +92,8 @@ 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(ctr_params['prefix']) - if ctr_params.has_key('suffix'): ctr_params['suffix'] = a2b_hex(ctr_params['suffix']) + 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'): ctr_params['nbits'] = 8*(self.module.block_size - len(ctr_params.get('prefix', '')) - len(ctr_params.get('suffix', ''))) params['counter'] = ctr_class(**ctr_params) @@ -139,7 +141,7 @@ class CipherStreamingSelfTest(CipherSelfTest): cipher = self._new() for i in range(0, len(plaintext), 3): ct3.append(cipher.encrypt(plaintext[i:i+3])) - ct3 = b2a_hex("".join(ct3)) + ct3 = b2a_hex(b("").join(ct3)) self.assertEqual(self.ciphertext, ct3) # encryption (3 bytes at a time) # Test counter mode decryption, 3 bytes at a time @@ -147,7 +149,8 @@ class CipherStreamingSelfTest(CipherSelfTest): cipher = self._new() for i in range(0, len(ciphertext), 3): pt3.append(cipher.encrypt(ciphertext[i:i+3])) - pt3 = b2a_hex("".join(pt3)) + # PY3K: This is meant to be text, do not change to bytes (data) + pt3 = b2a_hex(b("").join(pt3)) self.assertEqual(self.plaintext, pt3) # decryption (3 bytes at a time) class CTRSegfaultTest(unittest.TestCase): @@ -155,7 +158,7 @@ class CTRSegfaultTest(unittest.TestCase): def __init__(self, module, params): unittest.TestCase.__init__(self) self.module = module - self.key = params['key'] + self.key = b(params['key']) self.module_name = params.get('module_name', None) def shortDescription(self): @@ -169,7 +172,7 @@ class CTRWraparoundTest(unittest.TestCase): def __init__(self, module, params): unittest.TestCase.__init__(self) self.module = module - self.key = params['key'] + self.key = b(params['key']) self.module_name = params.get('module_name', None) def shortDescription(self): @@ -182,7 +185,7 @@ class CTRWraparoundTest(unittest.TestCase): 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) cipher = self.module.new(a2b_hex(self.key), self.module.MODE_CTR, counter=ctr) - block = "\x00" * self.module.block_size + block = b("\x00") * self.module.block_size cipher.encrypt(block) self.assertRaises(OverflowError, cipher.encrypt, block) @@ -191,7 +194,7 @@ class CFBSegmentSizeTest(unittest.TestCase): def __init__(self, module, params): unittest.TestCase.__init__(self) self.module = module - self.key = params['key'] + self.key = b(params['key']) self.description = params['description'] def shortDescription(self): @@ -204,14 +207,13 @@ class CFBSegmentSizeTest(unittest.TestCase): self.module.new(a2b_hex(self.key), self.module.MODE_CFB, segment_size=8) # should succeed class RoundtripTest(unittest.TestCase): - def __init__(self, module, params): from Crypto import Random unittest.TestCase.__init__(self) self.module = module self.iv = Random.get_random_bytes(module.block_size) - self.key = params['key'] - self.plaintext = 100 * params['plaintext'] + self.key = b(params['key']) + self.plaintext = 100 * b(params['plaintext']) self.module_name = params.get('module_name', None) def shortDescription(self): diff --git a/lib/Crypto/SelfTest/Cipher/test_AES.py b/lib/Crypto/SelfTest/Cipher/test_AES.py index c96dd10..cc54afb 100644 --- a/lib/Crypto/SelfTest/Cipher/test_AES.py +++ b/lib/Crypto/SelfTest/Cipher/test_AES.py @@ -27,6 +27,7 @@ __revision__ = "$Id$" from common import dict # For compatibility with Python 2.1 and 2.2 +from Crypto.Util.py3compat import * # This is a list of (plaintext, ciphertext, key[, description[, params]]) tuples. test_data = [ @@ -50,261 +51,389 @@ test_data = [ # ecb_tbl.txt, KEYSIZE=128 ('506812a45f08c889b97f5980038b8359', 'd8f532538289ef7d06b506a4fd5be9c9', - '00010203050607080a0b0c0d0f101112', 'ecb-tbl-128: I=1'), + '00010203050607080a0b0c0d0f101112', + 'ecb-tbl-128: I=1'), ('5c6d71ca30de8b8b00549984d2ec7d4b', '59ab30f4d4ee6e4ff9907ef65b1fb68c', - '14151617191a1b1c1e1f202123242526', 'ecb-tbl-128: I=2'), + '14151617191a1b1c1e1f202123242526', + 'ecb-tbl-128: I=2'), ('53f3f4c64f8616e4e7c56199f48f21f6', 'bf1ed2fcb2af3fd41443b56d85025cb1', - '28292a2b2d2e2f30323334353738393a', 'ecb-tbl-128: I=3'), + '28292a2b2d2e2f30323334353738393a', + 'ecb-tbl-128: I=3'), ('a1eb65a3487165fb0f1c27ff9959f703', '7316632d5c32233edcb0780560eae8b2', - '3c3d3e3f41424344464748494b4c4d4e', 'ecb-tbl-128: I=4'), + '3c3d3e3f41424344464748494b4c4d4e', + 'ecb-tbl-128: I=4'), ('3553ecf0b1739558b08e350a98a39bfa', '408c073e3e2538072b72625e68b8364b', - '50515253555657585a5b5c5d5f606162', 'ecb-tbl-128: I=5'), + '50515253555657585a5b5c5d5f606162', + 'ecb-tbl-128: I=5'), ('67429969490b9711ae2b01dc497afde8', 'e1f94dfa776597beaca262f2f6366fea', - '64656667696a6b6c6e6f707173747576', 'ecb-tbl-128: I=6'), + '64656667696a6b6c6e6f707173747576', + 'ecb-tbl-128: I=6'), ('93385c1f2aec8bed192f5a8e161dd508', 'f29e986c6a1c27d7b29ffd7ee92b75f1', - '78797a7b7d7e7f80828384858788898a', 'ecb-tbl-128: I=7'), + '78797a7b7d7e7f80828384858788898a', + 'ecb-tbl-128: I=7'), ('b5bf946be19beb8db3983b5f4c6e8ddb', '131c886a57f8c2e713aba6955e2b55b5', - '8c8d8e8f91929394969798999b9c9d9e', 'ecb-tbl-128: I=8'), + '8c8d8e8f91929394969798999b9c9d9e', + 'ecb-tbl-128: I=8'), ('41321ee10e21bd907227c4450ff42324', 'd2ab7662df9b8c740210e5eeb61c199d', - 'a0a1a2a3a5a6a7a8aaabacadafb0b1b2', 'ecb-tbl-128: I=9'), + 'a0a1a2a3a5a6a7a8aaabacadafb0b1b2', + 'ecb-tbl-128: I=9'), ('00a82f59c91c8486d12c0a80124f6089', '14c10554b2859c484cab5869bbe7c470', - 'b4b5b6b7b9babbbcbebfc0c1c3c4c5c6', 'ecb-tbl-128: I=10'), + 'b4b5b6b7b9babbbcbebfc0c1c3c4c5c6', + 'ecb-tbl-128: I=10'), ('7ce0fd076754691b4bbd9faf8a1372fe', 'db4d498f0a49cf55445d502c1f9ab3b5', - 'c8c9cacbcdcecfd0d2d3d4d5d7d8d9da', 'ecb-tbl-128: I=11'), + 'c8c9cacbcdcecfd0d2d3d4d5d7d8d9da', + 'ecb-tbl-128: I=11'), ('23605a8243d07764541bc5ad355b3129', '6d96fef7d66590a77a77bb2056667f7f', - 'dcdddedfe1e2e3e4e6e7e8e9ebecedee', 'ecb-tbl-128: I=12'), + 'dcdddedfe1e2e3e4e6e7e8e9ebecedee', + 'ecb-tbl-128: I=12'), ('12a8cfa23ea764fd876232b4e842bc44', '316fb68edba736c53e78477bf913725c', - 'f0f1f2f3f5f6f7f8fafbfcfdfe010002', 'ecb-tbl-128: I=13'), + 'f0f1f2f3f5f6f7f8fafbfcfdfe010002', + 'ecb-tbl-128: I=13'), ('bcaf32415e8308b3723e5fdd853ccc80', '6936f2b93af8397fd3a771fc011c8c37', - '04050607090a0b0c0e0f101113141516', 'ecb-tbl-128: I=14'), + '04050607090a0b0c0e0f101113141516', + 'ecb-tbl-128: I=14'), ('89afae685d801ad747ace91fc49adde0', 'f3f92f7a9c59179c1fcc2c2ba0b082cd', - '2c2d2e2f31323334363738393b3c3d3e', 'ecb-tbl-128: I=15'), + '2c2d2e2f31323334363738393b3c3d3e', + 'ecb-tbl-128: I=15'), ('f521d07b484357c4a69e76124a634216', '6a95ea659ee3889158e7a9152ff04ebc', - '40414243454647484a4b4c4d4f505152', 'ecb-tbl-128: I=16'), + '40414243454647484a4b4c4d4f505152', + 'ecb-tbl-128: I=16'), ('3e23b3bc065bcc152407e23896d77783', '1959338344e945670678a5d432c90b93', - '54555657595a5b5c5e5f606163646566', 'ecb-tbl-128: I=17'), + '54555657595a5b5c5e5f606163646566', + 'ecb-tbl-128: I=17'), ('79f0fba002be1744670e7e99290d8f52', 'e49bddd2369b83ee66e6c75a1161b394', - '68696a6b6d6e6f70727374757778797a', 'ecb-tbl-128: I=18'), + '68696a6b6d6e6f70727374757778797a', + 'ecb-tbl-128: I=18'), ('da23fe9d5bd63e1d72e3dafbe21a6c2a', 'd3388f19057ff704b70784164a74867d', - '7c7d7e7f81828384868788898b8c8d8e', 'ecb-tbl-128: I=19'), + '7c7d7e7f81828384868788898b8c8d8e', + 'ecb-tbl-128: I=19'), ('e3f5698ba90b6a022efd7db2c7e6c823', '23aa03e2d5e4cd24f3217e596480d1e1', - 'a4a5a6a7a9aaabacaeafb0b1b3b4b5b6', 'ecb-tbl-128: I=20'), + 'a4a5a6a7a9aaabacaeafb0b1b3b4b5b6', + 'ecb-tbl-128: I=20'), ('bdc2691d4f1b73d2700679c3bcbf9c6e', 'c84113d68b666ab2a50a8bdb222e91b9', - 'e0e1e2e3e5e6e7e8eaebecedeff0f1f2', 'ecb-tbl-128: I=21'), + 'e0e1e2e3e5e6e7e8eaebecedeff0f1f2', + 'ecb-tbl-128: I=21'), ('ba74e02093217ee1ba1b42bd5624349a', 'ac02403981cd4340b507963db65cb7b6', - '08090a0b0d0e0f10121314151718191a', 'ecb-tbl-128: I=22'), + '08090a0b0d0e0f10121314151718191a', + 'ecb-tbl-128: I=22'), ('b5c593b5851c57fbf8b3f57715e8f680', '8d1299236223359474011f6bf5088414', - '6c6d6e6f71727374767778797b7c7d7e', 'ecb-tbl-128: I=23'), + '6c6d6e6f71727374767778797b7c7d7e', + 'ecb-tbl-128: I=23'), ('3da9bd9cec072381788f9387c3bbf4ee', '5a1d6ab8605505f7977e55b9a54d9b90', - '80818283858687888a8b8c8d8f909192', 'ecb-tbl-128: I=24'), + '80818283858687888a8b8c8d8f909192', + 'ecb-tbl-128: I=24'), ('4197f3051121702ab65d316b3c637374', '72e9c2d519cf555e4208805aabe3b258', - '94959697999a9b9c9e9fa0a1a3a4a5a6', 'ecb-tbl-128: I=25'), + '94959697999a9b9c9e9fa0a1a3a4a5a6', + 'ecb-tbl-128: I=25'), ('9f46c62ec4f6ee3f6e8c62554bc48ab7', 'a8f3e81c4a23a39ef4d745dffe026e80', - 'a8a9aaabadaeafb0b2b3b4b5b7b8b9ba', 'ecb-tbl-128: I=26'), + 'a8a9aaabadaeafb0b2b3b4b5b7b8b9ba', + 'ecb-tbl-128: I=26'), ('0220673fe9e699a4ebc8e0dbeb6979c8', '546f646449d31458f9eb4ef5483aee6c', - 'bcbdbebfc1c2c3c4c6c7c8c9cbcccdce', 'ecb-tbl-128: I=27'), + 'bcbdbebfc1c2c3c4c6c7c8c9cbcccdce', + 'ecb-tbl-128: I=27'), ('b2b99171337ded9bc8c2c23ff6f18867', '4dbe4bc84ac797c0ee4efb7f1a07401c', - 'd0d1d2d3d5d6d7d8dadbdcdddfe0e1e2', 'ecb-tbl-128: I=28'), + 'd0d1d2d3d5d6d7d8dadbdcdddfe0e1e2', + 'ecb-tbl-128: I=28'), ('a7facf4e301e984e5efeefd645b23505', '25e10bfb411bbd4d625ac8795c8ca3b3', - 'e4e5e6e7e9eaebeceeeff0f1f3f4f5f6', 'ecb-tbl-128: I=29'), + 'e4e5e6e7e9eaebeceeeff0f1f3f4f5f6', + 'ecb-tbl-128: I=29'), ('f7c762e4a9819160fd7acfb6c4eedcdd', '315637405054ec803614e43def177579', - 'f8f9fafbfdfefe00020304050708090a', 'ecb-tbl-128: I=30'), + 'f8f9fafbfdfefe00020304050708090a', + 'ecb-tbl-128: I=30'), ('9b64fc21ea08709f4915436faa70f1be', '60c5bc8a1410247295c6386c59e572a8', - '0c0d0e0f11121314161718191b1c1d1e', 'ecb-tbl-128: I=31'), + '0c0d0e0f11121314161718191b1c1d1e', + 'ecb-tbl-128: I=31'), ('52af2c3de07ee6777f55a4abfc100b3f', '01366fc8ca52dfe055d6a00a76471ba6', - '20212223252627282a2b2c2d2f303132', 'ecb-tbl-128: I=32'), + '20212223252627282a2b2c2d2f303132', + 'ecb-tbl-128: I=32'), ('2fca001224386c57aa3f968cbe2c816f', 'ecc46595516ec612449c3f581e7d42ff', - '34353637393a3b3c3e3f404143444546', 'ecb-tbl-128: I=33'), + '34353637393a3b3c3e3f404143444546', + 'ecb-tbl-128: I=33'), ('4149c73658a4a9c564342755ee2c132f', '6b7ffe4c602a154b06ee9c7dab5331c9', - '48494a4b4d4e4f50525354555758595a', 'ecb-tbl-128: I=34'), + '48494a4b4d4e4f50525354555758595a', + 'ecb-tbl-128: I=34'), ('af60005a00a1772f7c07a48a923c23d2', '7da234c14039a240dd02dd0fbf84eb67', - '5c5d5e5f61626364666768696b6c6d6e', 'ecb-tbl-128: I=35'), + '5c5d5e5f61626364666768696b6c6d6e', + 'ecb-tbl-128: I=35'), ('6fccbc28363759914b6f0280afaf20c6', 'c7dc217d9e3604ffe7e91f080ecd5a3a', - '70717273757677787a7b7c7d7f808182', 'ecb-tbl-128: I=36'), + '70717273757677787a7b7c7d7f808182', + 'ecb-tbl-128: I=36'), ('7d82a43ddf4fefa2fc5947499884d386', '37785901863f5c81260ea41e7580cda5', - '84858687898a8b8c8e8f909193949596', 'ecb-tbl-128: I=37'), + '84858687898a8b8c8e8f909193949596', + 'ecb-tbl-128: I=37'), ('5d5a990eaab9093afe4ce254dfa49ef9', 'a07b9338e92ed105e6ad720fccce9fe4', - '98999a9b9d9e9fa0a2a3a4a5a7a8a9aa', 'ecb-tbl-128: I=38'), + '98999a9b9d9e9fa0a2a3a4a5a7a8a9aa', + 'ecb-tbl-128: I=38'), ('4cd1e2fd3f4434b553aae453f0ed1a02', 'ae0fb9722418cc21a7da816bbc61322c', - 'acadaeafb1b2b3b4b6b7b8b9bbbcbdbe', 'ecb-tbl-128: I=39'), + 'acadaeafb1b2b3b4b6b7b8b9bbbcbdbe', + 'ecb-tbl-128: I=39'), ('5a2c9a9641d4299125fa1b9363104b5e', 'c826a193080ff91ffb21f71d3373c877', - 'c0c1c2c3c5c6c7c8cacbcccdcfd0d1d2', 'ecb-tbl-128: I=40'), + 'c0c1c2c3c5c6c7c8cacbcccdcfd0d1d2', + 'ecb-tbl-128: I=40'), ('b517fe34c0fa217d341740bfd4fe8dd4', '1181b11b0e494e8d8b0aa6b1d5ac2c48', - 'd4d5d6d7d9dadbdcdedfe0e1e3e4e5e6', 'ecb-tbl-128: I=41'), + 'd4d5d6d7d9dadbdcdedfe0e1e3e4e5e6', + 'ecb-tbl-128: I=41'), ('014baf2278a69d331d5180103643e99a', '6743c3d1519ab4f2cd9a78ab09a511bd', - 'e8e9eaebedeeeff0f2f3f4f5f7f8f9fa', 'ecb-tbl-128: I=42'), + 'e8e9eaebedeeeff0f2f3f4f5f7f8f9fa', + 'ecb-tbl-128: I=42'), ('b529bd8164f20d0aa443d4932116841c', 'dc55c076d52bacdf2eefd952946a439d', - 'fcfdfeff01020304060708090b0c0d0e', 'ecb-tbl-128: I=43'), + 'fcfdfeff01020304060708090b0c0d0e', + 'ecb-tbl-128: I=43'), ('2e596dcbb2f33d4216a1176d5bd1e456', '711b17b590ffc72b5c8e342b601e8003', - '10111213151617181a1b1c1d1f202122', 'ecb-tbl-128: I=44'), + '10111213151617181a1b1c1d1f202122', + 'ecb-tbl-128: I=44'), ('7274a1ea2b7ee2424e9a0e4673689143', '19983bb0950783a537e1339f4aa21c75', - '24252627292a2b2c2e2f303133343536', 'ecb-tbl-128: I=45'), + '24252627292a2b2c2e2f303133343536', + 'ecb-tbl-128: I=45'), ('ae20020bd4f13e9d90140bee3b5d26af', '3ba7762e15554169c0f4fa39164c410c', - '38393a3b3d3e3f40424344454748494a', 'ecb-tbl-128: I=46'), + '38393a3b3d3e3f40424344454748494a', + 'ecb-tbl-128: I=46'), ('baac065da7ac26e855e79c8849d75a02', 'a0564c41245afca7af8aa2e0e588ea89', - '4c4d4e4f51525354565758595b5c5d5e', 'ecb-tbl-128: I=47'), + '4c4d4e4f51525354565758595b5c5d5e', + 'ecb-tbl-128: I=47'), ('7c917d8d1d45fab9e2540e28832540cc', '5e36a42a2e099f54ae85ecd92e2381ed', - '60616263656667686a6b6c6d6f707172', 'ecb-tbl-128: I=48'), + '60616263656667686a6b6c6d6f707172', + 'ecb-tbl-128: I=48'), ('bde6f89e16daadb0e847a2a614566a91', '770036f878cd0f6ca2268172f106f2fe', - '74757677797a7b7c7e7f808183848586', 'ecb-tbl-128: I=49'), + '74757677797a7b7c7e7f808183848586', + 'ecb-tbl-128: I=49'), ('c9de163725f1f5be44ebb1db51d07fbc', '7e4e03908b716116443ccf7c94e7c259', - '88898a8b8d8e8f90929394959798999a', 'ecb-tbl-128: I=50'), + '88898a8b8d8e8f90929394959798999a', + 'ecb-tbl-128: I=50'), ('3af57a58f0c07dffa669572b521e2b92', '482735a48c30613a242dd494c7f9185d', - '9c9d9e9fa1a2a3a4a6a7a8a9abacadae', 'ecb-tbl-128: I=51'), + '9c9d9e9fa1a2a3a4a6a7a8a9abacadae', + 'ecb-tbl-128: I=51'), ('3d5ebac306dde4604f1b4fbbbfcdae55', 'b4c0f6c9d4d7079addf9369fc081061d', - 'b0b1b2b3b5b6b7b8babbbcbdbfc0c1c2', 'ecb-tbl-128: I=52'), + 'b0b1b2b3b5b6b7b8babbbcbdbfc0c1c2', + 'ecb-tbl-128: I=52'), ('c2dfa91bceb76a1183c995020ac0b556', 'd5810fe0509ac53edcd74f89962e6270', - 'c4c5c6c7c9cacbcccecfd0d1d3d4d5d6', 'ecb-tbl-128: I=53'), + 'c4c5c6c7c9cacbcccecfd0d1d3d4d5d6', + 'ecb-tbl-128: I=53'), ('c70f54305885e9a0746d01ec56c8596b', '03f17a16b3f91848269ecdd38ebb2165', - 'd8d9dadbdddedfe0e2e3e4e5e7e8e9ea', 'ecb-tbl-128: I=54'), + 'd8d9dadbdddedfe0e2e3e4e5e7e8e9ea', + 'ecb-tbl-128: I=54'), ('c4f81b610e98012ce000182050c0c2b2', 'da1248c3180348bad4a93b4d9856c9df', - 'ecedeeeff1f2f3f4f6f7f8f9fbfcfdfe', 'ecb-tbl-128: I=55'), + 'ecedeeeff1f2f3f4f6f7f8f9fbfcfdfe', + 'ecb-tbl-128: I=55'), ('eaab86b1d02a95d7404eff67489f97d4', '3d10d7b63f3452c06cdf6cce18be0c2c', - '00010203050607080a0b0c0d0f101112', 'ecb-tbl-128: I=56'), + '00010203050607080a0b0c0d0f101112', + 'ecb-tbl-128: I=56'), ('7c55bdb40b88870b52bec3738de82886', '4ab823e7477dfddc0e6789018fcb6258', - '14151617191a1b1c1e1f202123242526', 'ecb-tbl-128: I=57'), + '14151617191a1b1c1e1f202123242526', + 'ecb-tbl-128: I=57'), ('ba6eaa88371ff0a3bd875e3f2a975ce0', 'e6478ba56a77e70cfdaa5c843abde30e', - '28292a2b2d2e2f30323334353738393a', 'ecb-tbl-128: I=58'), + '28292a2b2d2e2f30323334353738393a', + 'ecb-tbl-128: I=58'), ('08059130c4c24bd30cf0575e4e0373dc', '1673064895fbeaf7f09c5429ff75772d', - '3c3d3e3f41424344464748494b4c4d4e', 'ecb-tbl-128: I=59'), + '3c3d3e3f41424344464748494b4c4d4e', + 'ecb-tbl-128: I=59'), ('9a8eab004ef53093dfcf96f57e7eda82', '4488033ae9f2efd0ca9383bfca1a94e9', - '50515253555657585a5b5c5d5f606162', 'ecb-tbl-128: I=60'), + '50515253555657585a5b5c5d5f606162', + 'ecb-tbl-128: I=60'), ('0745b589e2400c25f117b1d796c28129', '978f3b8c8f9d6f46626cac3c0bcb9217', - '64656667696a6b6c6e6f707173747576', 'ecb-tbl-128: I=61'), + '64656667696a6b6c6e6f707173747576', + 'ecb-tbl-128: I=61'), ('2f1777781216cec3f044f134b1b92bbe', 'e08c8a7e582e15e5527f1d9e2eecb236', - '78797a7b7d7e7f80828384858788898a', 'ecb-tbl-128: I=62'), + '78797a7b7d7e7f80828384858788898a', + 'ecb-tbl-128: I=62'), ('353a779ffc541b3a3805d90ce17580fc', 'cec155b76ac5ffda4cf4f9ca91e49a7a', - '8c8d8e8f91929394969798999b9c9d9e', 'ecb-tbl-128: I=63'), + '8c8d8e8f91929394969798999b9c9d9e', + 'ecb-tbl-128: I=63'), ('1a1eae4415cefcf08c4ac1c8f68bea8f', 'd5ac7165763225dd2a38cdc6862c29ad', - 'a0a1a2a3a5a6a7a8aaabacadafb0b1b2', 'ecb-tbl-128: I=64'), + 'a0a1a2a3a5a6a7a8aaabacadafb0b1b2', + 'ecb-tbl-128: I=64'), ('e6e7e4e5b0b3b2b5d4d5aaab16111013', '03680fe19f7ce7275452020be70e8204', - 'b4b5b6b7b9babbbcbebfc0c1c3c4c5c6', 'ecb-tbl-128: I=65'), + 'b4b5b6b7b9babbbcbebfc0c1c3c4c5c6', + 'ecb-tbl-128: I=65'), ('f8f9fafbfbf8f9e677767170efe0e1e2', '461df740c9781c388e94bb861ceb54f6', - 'c8c9cacbcdcecfd0d2d3d4d5d7d8d9da', 'ecb-tbl-128: I=66'), + 'c8c9cacbcdcecfd0d2d3d4d5d7d8d9da', + 'ecb-tbl-128: I=66'), ('63626160a1a2a3a445444b4a75727370', '451bd60367f96483042742219786a074', - 'dcdddedfe1e2e3e4e6e7e8e9ebecedee', 'ecb-tbl-128: I=67'), + 'dcdddedfe1e2e3e4e6e7e8e9ebecedee', + 'ecb-tbl-128: I=67'), ('717073720605040b2d2c2b2a05fafbf9', 'e4dfa42671a02e57ef173b85c0ea9f2b', - 'f0f1f2f3f5f6f7f8fafbfcfdfe010002', 'ecb-tbl-128: I=68'), + 'f0f1f2f3f5f6f7f8fafbfcfdfe010002', + 'ecb-tbl-128: I=68'), ('78797a7beae9e8ef3736292891969794', 'ed11b89e76274282227d854700a78b9e', - '04050607090a0b0c0e0f101113141516', 'ecb-tbl-128: I=69'), + '04050607090a0b0c0e0f101113141516', + 'ecb-tbl-128: I=69'), ('838281803231300fdddcdbdaa0afaead', '433946eaa51ea47af33895f2b90b3b75', - '18191a1b1d1e1f20222324252728292a', 'ecb-tbl-128: I=70'), + '18191a1b1d1e1f20222324252728292a', + 'ecb-tbl-128: I=70'), ('18191a1bbfbcbdba75747b7a7f78797a', '6bc6d616a5d7d0284a5910ab35022528', - '2c2d2e2f31323334363738393b3c3d3e', 'ecb-tbl-128: I=71'), + '2c2d2e2f31323334363738393b3c3d3e', + 'ecb-tbl-128: I=71'), ('848586879b989996a3a2a5a4849b9a99', 'd2a920ecfe919d354b5f49eae9719c98', - '40414243454647484a4b4c4d4f505152', 'ecb-tbl-128: I=72'), + '40414243454647484a4b4c4d4f505152', + 'ecb-tbl-128: I=72'), ('0001020322212027cacbf4f551565754', '3a061b17f6a92885efbd0676985b373d', - '54555657595a5b5c5e5f606163646566', 'ecb-tbl-128: I=73'), + '54555657595a5b5c5e5f606163646566', + 'ecb-tbl-128: I=73'), ('cecfcccdafacadb2515057564a454447', 'fadeec16e33ea2f4688499d157e20d8f', - '68696a6b6d6e6f70727374757778797a', 'ecb-tbl-128: I=74'), + '68696a6b6d6e6f70727374757778797a', + 'ecb-tbl-128: I=74'), ('92939091cdcecfc813121d1c80878685', '5cdefede59601aa3c3cda36fa6b1fa13', - '7c7d7e7f81828384868788898b8c8d8e', 'ecb-tbl-128: I=75'), + '7c7d7e7f81828384868788898b8c8d8e', + 'ecb-tbl-128: I=75'), ('d2d3d0d16f6c6d6259585f5ed1eeefec', '9574b00039844d92ebba7ee8719265f8', - '90919293959697989a9b9c9d9fa0a1a2', 'ecb-tbl-128: I=76'), + '90919293959697989a9b9c9d9fa0a1a2', + 'ecb-tbl-128: I=76'), ('acadaeaf878485820f0e1110d5d2d3d0', '9a9cf33758671787e5006928188643fa', - 'a4a5a6a7a9aaabacaeafb0b1b3b4b5b6', 'ecb-tbl-128: I=77'), + 'a4a5a6a7a9aaabacaeafb0b1b3b4b5b6', + 'ecb-tbl-128: I=77'), ('9091929364676619e6e7e0e1757a7b78', '2cddd634c846ba66bb46cbfea4a674f9', - 'b8b9babbbdbebfc0c2c3c4c5c7c8c9ca', 'ecb-tbl-128: I=78'), + 'b8b9babbbdbebfc0c2c3c4c5c7c8c9ca', + 'ecb-tbl-128: I=78'), ('babbb8b98a89888f74757a7b92959497', 'd28bae029393c3e7e26e9fafbbb4b98f', - 'cccdcecfd1d2d3d4d6d7d8d9dbdcddde', 'ecb-tbl-128: I=79'), + 'cccdcecfd1d2d3d4d6d7d8d9dbdcddde', + 'ecb-tbl-128: I=79'), ('8d8c8f8e6e6d6c633b3a3d3ccad5d4d7', 'ec27529b1bee0a9ab6a0d73ebc82e9b7', - 'e0e1e2e3e5e6e7e8eaebecedeff0f1f2', 'ecb-tbl-128: I=80'), + 'e0e1e2e3e5e6e7e8eaebecedeff0f1f2', + 'ecb-tbl-128: I=80'), ('86878485010203040808f7f767606162', '3cb25c09472aff6ee7e2b47ccd7ccb17', - 'f4f5f6f7f9fafbfcfefe010103040506', 'ecb-tbl-128: I=81'), + 'f4f5f6f7f9fafbfcfefe010103040506', + 'ecb-tbl-128: I=81'), ('8e8f8c8d656667788a8b8c8d010e0f0c', 'dee33103a7283370d725e44ca38f8fe5', - '08090a0b0d0e0f10121314151718191a', 'ecb-tbl-128: I=82'), + '08090a0b0d0e0f10121314151718191a', + 'ecb-tbl-128: I=82'), ('c8c9cacb858687807a7b7475e7e0e1e2', '27f9bcd1aac64bffc11e7815702c1a69', - '1c1d1e1f21222324262728292b2c2d2e', 'ecb-tbl-128: I=83'), + '1c1d1e1f21222324262728292b2c2d2e', + 'ecb-tbl-128: I=83'), ('6d6c6f6e5053525d8c8d8a8badd2d3d0', '5df534ffad4ed0749a9988e9849d0021', - '30313233353637383a3b3c3d3f404142', 'ecb-tbl-128: I=84'), + '30313233353637383a3b3c3d3f404142', + 'ecb-tbl-128: I=84'), ('28292a2b393a3b3c0607181903040506', 'a48bee75db04fb60ca2b80f752a8421b', - '44454647494a4b4c4e4f505153545556', 'ecb-tbl-128: I=85'), + '44454647494a4b4c4e4f505153545556', + 'ecb-tbl-128: I=85'), ('a5a4a7a6b0b3b28ddbdadddcbdb2b3b0', '024c8cf70bc86ee5ce03678cb7af45f9', - '58595a5b5d5e5f60626364656768696a', 'ecb-tbl-128: I=86'), + '58595a5b5d5e5f60626364656768696a', + 'ecb-tbl-128: I=86'), ('323330316467666130313e3f2c2b2a29', '3c19ac0f8a3a3862ce577831301e166b', - '6c6d6e6f71727374767778797b7c7d7e', 'ecb-tbl-128: I=87'), + '6c6d6e6f71727374767778797b7c7d7e', + 'ecb-tbl-128: I=87'), ('27262524080b0a05171611100b141516', 'c5e355b796a57421d59ca6be82e73bca', - '80818283858687888a8b8c8d8f909192', 'ecb-tbl-128: I=88'), + '80818283858687888a8b8c8d8f909192', + 'ecb-tbl-128: I=88'), ('040506074142434435340b0aa3a4a5a6', 'd94033276417abfb05a69d15b6e386e2', - '94959697999a9b9c9e9fa0a1a3a4a5a6', 'ecb-tbl-128: I=89'), + '94959697999a9b9c9e9fa0a1a3a4a5a6', + 'ecb-tbl-128: I=89'), ('242526271112130c61606766bdb2b3b0', '24b36559ea3a9b9b958fe6da3e5b8d85', - 'a8a9aaabadaeafb0b2b3b4b5b7b8b9ba', 'ecb-tbl-128: I=90'), + 'a8a9aaabadaeafb0b2b3b4b5b7b8b9ba', + 'ecb-tbl-128: I=90'), ('4b4a4948252627209e9f9091cec9c8cb', '20fd4feaa0e8bf0cce7861d74ef4cb72', - 'bcbdbebfc1c2c3c4c6c7c8c9cbcccdce', 'ecb-tbl-128: I=91'), + 'bcbdbebfc1c2c3c4c6c7c8c9cbcccdce', + 'ecb-tbl-128: I=91'), ('68696a6b6665646b9f9e9998d9e6e7e4', '350e20d5174277b9ec314c501570a11d', - 'd0d1d2d3d5d6d7d8dadbdcdddfe0e1e2', 'ecb-tbl-128: I=92'), + 'd0d1d2d3d5d6d7d8dadbdcdddfe0e1e2', + 'ecb-tbl-128: I=92'), ('34353637c5c6c7c0f0f1eeef7c7b7a79', '87a29d61b7c604d238fe73045a7efd57', - 'e4e5e6e7e9eaebeceeeff0f1f3f4f5f6', 'ecb-tbl-128: I=93'), + 'e4e5e6e7e9eaebeceeeff0f1f3f4f5f6', + 'ecb-tbl-128: I=93'), ('32333031c2c1c13f0d0c0b0a050a0b08', '2c3164c1cc7d0064816bdc0faa362c52', - 'f8f9fafbfdfefe00020304050708090a', 'ecb-tbl-128: I=94'), + 'f8f9fafbfdfefe00020304050708090a', + 'ecb-tbl-128: I=94'), ('cdcccfcebebdbcbbabaaa5a4181f1e1d', '195fe5e8a05a2ed594f6e4400eee10b3', - '0c0d0e0f11121314161718191b1c1d1e', 'ecb-tbl-128: I=95'), + '0c0d0e0f11121314161718191b1c1d1e', + 'ecb-tbl-128: I=95'), ('212023223635343ba0a1a6a7445b5a59', 'e4663df19b9a21a5a284c2bd7f905025', - '20212223252627282a2b2c2d2f303132', 'ecb-tbl-128: I=96'), + '20212223252627282a2b2c2d2f303132', + 'ecb-tbl-128: I=96'), ('0e0f0c0da8abaaad2f2e515002050407', '21b88714cfb4e2a933bd281a2c4743fd', - '34353637393a3b3c3e3f404143444546', 'ecb-tbl-128: I=97'), + '34353637393a3b3c3e3f404143444546', + 'ecb-tbl-128: I=97'), ('070605042a2928378e8f8889bdb2b3b0', 'cbfc3980d704fd0fc54378ab84e17870', - '48494a4b4d4e4f50525354555758595a', 'ecb-tbl-128: I=98'), + '48494a4b4d4e4f50525354555758595a', + 'ecb-tbl-128: I=98'), ('cbcac9c893909196a9a8a7a6a5a2a3a0', 'bc5144baa48bdeb8b63e22e03da418ef', - '5c5d5e5f61626364666768696b6c6d6e', 'ecb-tbl-128: I=99'), + '5c5d5e5f61626364666768696b6c6d6e', + 'ecb-tbl-128: I=99'), ('80818283c1c2c3cc9c9d9a9b0cf3f2f1', '5a1dbaef1ee2984b8395da3bdffa3ccc', - '70717273757677787a7b7c7d7f808182', 'ecb-tbl-128: I=100'), + '70717273757677787a7b7c7d7f808182', + 'ecb-tbl-128: I=100'), ('1213101125262720fafbe4e5b1b6b7b4', 'f0b11cd0729dfcc80cec903d97159574', - '84858687898a8b8c8e8f909193949596', 'ecb-tbl-128: I=101'), + '84858687898a8b8c8e8f909193949596', + 'ecb-tbl-128: I=101'), ('7f7e7d7c3033320d97969190222d2c2f', '9f95314acfddc6d1914b7f19a9cc8209', - '98999a9b9d9e9fa0a2a3a4a5a7a8a9aa', 'ecb-tbl-128: I=102'), + '98999a9b9d9e9fa0a2a3a4a5a7a8a9aa', + 'ecb-tbl-128: I=102'), ('4e4f4c4d484b4a4d81808f8e53545556', '595736f6f0f70914a94e9e007f022519', - 'acadaeafb1b2b3b4b6b7b8b9bbbcbdbe', 'ecb-tbl-128: I=103'), + 'acadaeafb1b2b3b4b6b7b8b9bbbcbdbe', + 'ecb-tbl-128: I=103'), ('dcdddedfb0b3b2bd15141312a1bebfbc', '1f19f57892cae586fcdfb4c694deb183', - 'c0c1c2c3c5c6c7c8cacbcccdcfd0d1d2', 'ecb-tbl-128: I=104'), + 'c0c1c2c3c5c6c7c8cacbcccdcfd0d1d2', + 'ecb-tbl-128: I=104'), ('93929190282b2a2dc4c5fafb92959497', '540700ee1f6f3dab0b3eddf6caee1ef5', - 'd4d5d6d7d9dadbdcdedfe0e1e3e4e5e6', 'ecb-tbl-128: I=105'), + 'd4d5d6d7d9dadbdcdedfe0e1e3e4e5e6', + 'ecb-tbl-128: I=105'), ('f5f4f7f6c4c7c6d9373631307e717073', '14a342a91019a331687a2254e6626ca2', - 'e8e9eaebedeeeff0f2f3f4f5f7f8f9fa', 'ecb-tbl-128: I=106'), + 'e8e9eaebedeeeff0f2f3f4f5f7f8f9fa', + 'ecb-tbl-128: I=106'), ('93929190b6b5b4b364656a6b05020300', '7b25f3c3b2eea18d743ef283140f29ff', - 'fcfdfeff01020304060708090b0c0d0e', 'ecb-tbl-128: I=107'), + 'fcfdfeff01020304060708090b0c0d0e', + 'ecb-tbl-128: I=107'), ('babbb8b90d0e0f00a4a5a2a3043b3a39', '46c2587d66e5e6fa7f7ca6411ad28047', - '10111213151617181a1b1c1d1f202122', 'ecb-tbl-128: I=108'), + '10111213151617181a1b1c1d1f202122', + 'ecb-tbl-128: I=108'), ('d8d9dadb7f7c7d7a10110e0f787f7e7d', '09470e72229d954ed5ee73886dfeeba9', - '24252627292a2b2c2e2f303133343536', 'ecb-tbl-128: I=109'), + '24252627292a2b2c2e2f303133343536', + 'ecb-tbl-128: I=109'), ('fefffcfdefeced923b3a3d3c6768696a', 'd77c03de92d4d0d79ef8d4824ef365eb', - '38393a3b3d3e3f40424344454748494a', 'ecb-tbl-128: I=110'), + '38393a3b3d3e3f40424344454748494a', + 'ecb-tbl-128: I=110'), ('d6d7d4d58a89888f96979899a5a2a3a0', '1d190219f290e0f1715d152d41a23593', - '4c4d4e4f51525354565758595b5c5d5e', 'ecb-tbl-128: I=111'), + '4c4d4e4f51525354565758595b5c5d5e', + 'ecb-tbl-128: I=111'), ('18191a1ba8abaaa5303136379b848586', 'a2cd332ce3a0818769616292e87f757b', - '60616263656667686a6b6c6d6f707172', 'ecb-tbl-128: I=112'), + '60616263656667686a6b6c6d6f707172', + 'ecb-tbl-128: I=112'), ('6b6a6968a4a7a6a1d6d72829b0b7b6b5', 'd54afa6ce60fbf9341a3690e21385102', - '74757677797a7b7c7e7f808183848586', 'ecb-tbl-128: I=113'), + '74757677797a7b7c7e7f808183848586', + 'ecb-tbl-128: I=113'), ('000102038a89889755545352a6a9a8ab', '06e5c364ded628a3f5e05e613e356f46', - '88898a8b8d8e8f90929394959798999a', 'ecb-tbl-128: I=114'), + '88898a8b8d8e8f90929394959798999a', + 'ecb-tbl-128: I=114'), ('2d2c2f2eb3b0b1b6b6b7b8b9f2f5f4f7', 'eae63c0e62556dac85d221099896355a', - '9c9d9e9fa1a2a3a4a6a7a8a9abacadae', 'ecb-tbl-128: I=115'), + '9c9d9e9fa1a2a3a4a6a7a8a9abacadae', + 'ecb-tbl-128: I=115'), ('979695943536373856575051e09f9e9d', '1fed060e2c6fc93ee764403a889985a2', - 'b0b1b2b3b5b6b7b8babbbcbdbfc0c1c2', 'ecb-tbl-128: I=116'), + 'b0b1b2b3b5b6b7b8babbbcbdbfc0c1c2', + 'ecb-tbl-128: I=116'), ('a4a5a6a7989b9a9db1b0afae7a7d7c7f', 'c25235c1a30fdec1c7cb5c5737b2a588', - 'c4c5c6c7c9cacbcccecfd0d1d3d4d5d6', 'ecb-tbl-128: I=117'), + 'c4c5c6c7c9cacbcccecfd0d1d3d4d5d6', + 'ecb-tbl-128: I=117'), ('c1c0c3c2686b6a55a8a9aeafeae5e4e7', '796dbef95147d4d30873ad8b7b92efc0', - 'd8d9dadbdddedfe0e2e3e4e5e7e8e9ea', 'ecb-tbl-128: I=118'), + 'd8d9dadbdddedfe0e2e3e4e5e7e8e9ea', + 'ecb-tbl-128: I=118'), ('c1c0c3c2141716118c8d828364636261', 'cbcf0fb34d98d0bd5c22ce37211a46bf', - 'ecedeeeff1f2f3f4f6f7f8f9fbfcfdfe', 'ecb-tbl-128: I=119'), + 'ecedeeeff1f2f3f4f6f7f8f9fbfcfdfe', + 'ecb-tbl-128: I=119'), ('93929190cccfcec196979091e0fffefd', '94b44da6466126cafa7c7fd09063fc24', - '00010203050607080a0b0c0d0f101112', 'ecb-tbl-128: I=120'), + '00010203050607080a0b0c0d0f101112', + 'ecb-tbl-128: I=120'), ('b4b5b6b7f9fafbfc25241b1a6e69686b', 'd78c5b5ebf9b4dbda6ae506c5074c8fe', - '14151617191a1b1c1e1f202123242526', 'ecb-tbl-128: I=121'), + '14151617191a1b1c1e1f202123242526', + 'ecb-tbl-128: I=121'), ('868784850704051ac7c6c1c08788898a', '6c27444c27204b043812cf8cf95f9769', - '28292a2b2d2e2f30323334353738393a', 'ecb-tbl-128: I=122'), + '28292a2b2d2e2f30323334353738393a', + 'ecb-tbl-128: I=122'), ('f4f5f6f7aaa9a8affdfcf3f277707172', 'be94524ee5a2aa50bba8b75f4c0aebcf', - '3c3d3e3f41424344464748494b4c4d4e', 'ecb-tbl-128: I=123'), + '3c3d3e3f41424344464748494b4c4d4e', + 'ecb-tbl-128: I=123'), ('d3d2d1d00605040bc3c2c5c43e010003', 'a0aeaae91ba9f31f51aeb3588cf3a39e', - '50515253555657585a5b5c5d5f606162', 'ecb-tbl-128: I=124'), + '50515253555657585a5b5c5d5f606162', + 'ecb-tbl-128: I=124'), ('73727170424140476a6b74750d0a0b08', '275297779c28266ef9fe4c6a13c08488', - '64656667696a6b6c6e6f707173747576', 'ecb-tbl-128: I=125'), + '64656667696a6b6c6e6f707173747576', + 'ecb-tbl-128: I=125'), ('c2c3c0c10a0908f754555253a1aeafac', '86523d92bb8672cb01cf4a77fd725882', - '78797a7b7d7e7f80828384858788898a', 'ecb-tbl-128: I=126'), + '78797a7b7d7e7f80828384858788898a', + 'ecb-tbl-128: I=126'), ('6d6c6f6ef8fbfafd82838c8df8fffefd', '4b8327640e9f33322a04dd96fcbf9a36', - '8c8d8e8f91929394969798999b9c9d9e', 'ecb-tbl-128: I=127'), + '8c8d8e8f91929394969798999b9c9d9e', + 'ecb-tbl-128: I=127'), ('f5f4f7f684878689a6a7a0a1d2cdcccf', 'ce52af650d088ca559425223f4d32694', - 'a0a1a2a3a5a6a7a8aaabacadafb0b1b2', 'ecb-tbl-128: I=128'), + 'a0a1a2a3a5a6a7a8aaabacadafb0b1b2', + 'ecb-tbl-128: I=128'), # ecb_tbl.txt, KEYSIZE=192 ('2d33eef2c0430a8a9ebf45e809c40bb6', 'dff4945e0336df4c1c56bc700eff837f', @@ -1083,47 +1212,47 @@ test_data = [ ('53696e676c6520626c6f636b206d7367', 'e4095d4fb7a7b3792d6175a3261311b8', 'ae6852f8121067cc4bf7a5765577f39e', 'RFC 3686 Test Vector #1: Encrypting 16 octets using AES-CTR with 128-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="00000030"+"0000000000000000"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='00000030'+'0000000000000000'))), ('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f', '5104a106168a72d9790d41ee8edad388eb2e1efc46da57c8fce630df9141be28', '7e24067817fae0d743d6ce1f32539163', 'RFC 3686 Test Vector #2: Encrypting 32 octets using AES-CTR with 128-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="006cb6db"+"c0543b59da48d90b"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='006cb6db'+'c0543b59da48d90b'))), ('000102030405060708090a0b0c0d0e0f'+'101112131415161718191a1b1c1d1e1f'+'20212223', 'c1cf48a89f2ffdd9cf4652e9efdb72d7'+'4540a42bde6d7836d59a5ceaaef31053'+'25b2072f', '7691be035e5020a8ac6e618529f9a0dc', 'RFC 3686 Test Vector #3: Encrypting 36 octets using AES-CTR with 128-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="00e0017b"+"27777f3f4a1786f0"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='00e0017b'+'27777f3f4a1786f0'))), ('53696e676c6520626c6f636b206d7367', '4b55384fe259c9c84e7935a003cbe928', '16af5b145fc9f579c175f93e3bfb0eed'+'863d06ccfdb78515', 'RFC 3686 Test Vector #4: Encrypting 16 octets using AES-CTR with 192-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="00000048"+"36733c147d6d93cb"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='00000048'+'36733c147d6d93cb'))), ('000102030405060708090a0b0c0d0e0f'+'101112131415161718191a1b1c1d1e1f', '453243fc609b23327edfaafa7131cd9f'+'8490701c5ad4a79cfc1fe0ff42f4fb00', '7c5cb2401b3dc33c19e7340819e0f69c'+'678c3db8e6f6a91a', 'RFC 3686 Test Vector #5: Encrypting 32 octets using AES-CTR with 192-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="0096b03b"+"020c6eadc2cb500d"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='0096b03b'+'020c6eadc2cb500d'))), ('000102030405060708090a0b0c0d0e0f'+'101112131415161718191a1b1c1d1e1f'+'20212223', '96893fc55e5c722f540b7dd1ddf7e758'+'d288bc95c69165884536c811662f2188'+'abee0935', '02bf391ee8ecb159b959617b0965279b'+'f59b60a786d3e0fe', 'RFC 3686 Test Vector #6: Encrypting 36 octets using AES-CTR with 192-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="0007bdfd"+"5cbd60278dcc0912"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='0007bdfd'+'5cbd60278dcc0912'))), ('53696e676c6520626c6f636b206d7367', '145ad01dbf824ec7560863dc71e3e0c0', '776beff2851db06f4c8a0542c8696f6c'+'6a81af1eec96b4d37fc1d689e6c1c104', 'RFC 3686 Test Vector #7: Encrypting 16 octets using AES-CTR with 256-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="00000060"+"db5672c97aa8f0b2"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='00000060'+'db5672c97aa8f0b2'))), ('000102030405060708090a0b0c0d0e0f'+'101112131415161718191a1b1c1d1e1f', 'f05e231b3894612c49ee000b804eb2a9'+'b8306b508f839d6a5530831d9344af1c', 'f6d66d6bd52d59bb0796365879eff886'+'c66dd51a5b6a99744b50590c87a23884', 'RFC 3686 Test Vector #8: Encrypting 32 octets using AES-CTR with 256-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="00faac24"+"c1585ef15a43d875"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='00faac24'+'c1585ef15a43d875'))), ('000102030405060708090a0b0c0d0e0f'+'101112131415161718191a1b1c1d1e1f'+'20212223', 'eb6c52821d0bbbf7ce7594462aca4faa'+'b407df866569fd07f48cc0b583d6071f'+'1ec0e6b8', 'ff7a617ce69148e4f1726e2f43581de2'+'aa62d9f805532edff1eed687fb54153d', 'RFC 3686 Test Vector #9: Encrypting 36 octets using AES-CTR with 256-bit key', - dict(mode='CTR', ctr_params=dict(nbits=32, prefix="001cc5b7"+"51a51d70a1c11148"))), + dict(mode='CTR', ctr_params=dict(nbits=32, prefix='001cc5b7'+'51a51d70a1c11148'))), ] def get_tests(config={}): diff --git a/lib/Crypto/SelfTest/Cipher/test_ARC2.py b/lib/Crypto/SelfTest/Cipher/test_ARC2.py index 77251c1..b6bc519 100644 --- a/lib/Crypto/SelfTest/Cipher/test_ARC2.py +++ b/lib/Crypto/SelfTest/Cipher/test_ARC2.py @@ -29,6 +29,7 @@ __revision__ = "$Id$" from common import dict # For compatibility with Python 2.1 and 2.2 import unittest +from Crypto.Util.py3compat import * # This is a list of (plaintext, ciphertext, key[, description[, extra_params]]) tuples. test_data = [ @@ -67,26 +68,30 @@ test_data = [ 'PCTv201-2'), ('0011223344556677', '078656aaba61cbfb', '5068696c6970476c617373', 'PCTv201-3'), - ('0000000000000000', 'd7bcc5dbb4d6e56a', 'ffffffffffffffff', 'PCTv201-4'), - ('ffffffffffffffff', '7259018ec557b357', 'ffffffffffffffff', 'PCTv201-5'), - ('0001020304050607', '93d20a497f2ccb62', 'ffffffffffffffff', 'PCTv201-6'), - ('0011223344556677', 'cb15a7f819c0014d', 'ffffffffffffffff', 'PCTv201-7'), - ('0000000000000000', '63ac98cdf3843a7a', - 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', + ('0000000000000000', 'd7bcc5dbb4d6e56a', 'ffffffffffffffff', + 'PCTv201-4'), + ('ffffffffffffffff', '7259018ec557b357', 'ffffffffffffffff', + 'PCTv201-5'), + ('0001020304050607', '93d20a497f2ccb62', 'ffffffffffffffff', + 'PCTv201-6'), + ('0011223344556677', 'cb15a7f819c0014d', 'ffffffffffffffff', + 'PCTv201-7'), + ('0000000000000000', '63ac98cdf3843a7a', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', 'PCTv201-8'), - ('ffffffffffffffff', '3fb49e2fa12371dd', - 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', + ('ffffffffffffffff', '3fb49e2fa12371dd', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', 'PCTv201-9'), - ('0001020304050607', '46414781ab387d5f', - 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', + ('0001020304050607', '46414781ab387d5f', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', 'PCTv201-10'), - ('0011223344556677', 'be09dc81feaca271', - 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', + ('0011223344556677', 'be09dc81feaca271', 'ffffffffffffffff5065746572477265656e6177617953e5ffe553', 'PCTv201-11'), - ('0000000000000000', 'e64221e608be30ab', '53e5ffe553', 'PCTv201-12'), - ('ffffffffffffffff', '862bc60fdcd4d9a9', '53e5ffe553', 'PCTv201-13'), - ('0001020304050607', '6a34da50fa5e47de', '53e5ffe553', 'PCTv201-14'), - ('0011223344556677', '584644c34503122c', '53e5ffe553', 'PCTv201-15'), + ('0000000000000000', 'e64221e608be30ab', '53e5ffe553', + 'PCTv201-12'), + ('ffffffffffffffff', '862bc60fdcd4d9a9', '53e5ffe553', + 'PCTv201-13'), + ('0001020304050607', '6a34da50fa5e47de', '53e5ffe553', + 'PCTv201-14'), + ('0011223344556677', '584644c34503122c', '53e5ffe553', + 'PCTv201-15'), ] class BufferOverflowTest(unittest.TestCase): diff --git a/lib/Crypto/SelfTest/Cipher/test_ARC4.py b/lib/Crypto/SelfTest/Cipher/test_ARC4.py index d354a3e..4e039d1 100644 --- a/lib/Crypto/SelfTest/Cipher/test_ARC4.py +++ b/lib/Crypto/SelfTest/Cipher/test_ARC4.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (plaintext, ciphertext, key[, description]) tuples. test_data = [ # Test vectors from Eric Rescorla's message with the subject diff --git a/lib/Crypto/SelfTest/Cipher/test_Blowfish.py b/lib/Crypto/SelfTest/Cipher/test_Blowfish.py index 3ccef4a..e8f73a6 100644 --- a/lib/Crypto/SelfTest/Cipher/test_Blowfish.py +++ b/lib/Crypto/SelfTest/Cipher/test_Blowfish.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (plaintext, ciphertext, key) tuples. test_data = [ # Test vectors from http://www.schneier.com/code/vectors.txt @@ -63,7 +65,6 @@ test_data = [ ('0000000000000000', 'f21e9a77b71c49bc', 'ffffffffffffffff'), ('0000000000000000', '245946885754369a', '0123456789abcdef'), ('ffffffffffffffff', '6b5c5a9c5d9e0a5a', 'fedcba9876543210'), - ('fedcba9876543210', 'f9ad597c49db005e', 'f0'), ('fedcba9876543210', 'e91d21c1d961a6d6', 'f0e1'), ('fedcba9876543210', 'e9c2b70a1bc65cf3', 'f0e1d2'), diff --git a/lib/Crypto/SelfTest/Cipher/test_CAST.py b/lib/Crypto/SelfTest/Cipher/test_CAST.py index ddc12e5..1cfcec0 100644 --- a/lib/Crypto/SelfTest/Cipher/test_CAST.py +++ b/lib/Crypto/SelfTest/Cipher/test_CAST.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (plaintext, ciphertext, key) tuples. test_data = [ # Test vectors from RFC 2144, B.1 diff --git a/lib/Crypto/SelfTest/Cipher/test_DES.py b/lib/Crypto/SelfTest/Cipher/test_DES.py index 76f0f79..c5d114b 100644 --- a/lib/Crypto/SelfTest/Cipher/test_DES.py +++ b/lib/Crypto/SelfTest/Cipher/test_DES.py @@ -27,10 +27,12 @@ __revision__ = "$Id$" from common import dict # For compatibility with Python 2.1 and 2.2 +from Crypto.Util.py3compat import * +import unittest # This is a list of (plaintext, ciphertext, key, description) tuples. -SP800_17_B1_KEY = "01" * 8 -SP800_17_B2_PT = "00" * 8 +SP800_17_B1_KEY = '01' * 8 +SP800_17_B2_PT = '00' * 8 test_data = [ # Test vectors from Appendix A of NIST SP 800-17 # "Modes of Operation Validation System (MOVS): Requirements and Procedures" @@ -285,10 +287,49 @@ test_data = [ 'NIST SP800-17 B.2 #55'), ] +class RonRivestTest(unittest.TestCase): + """ Ronald L. Rivest's DES test, see + http://people.csail.mit.edu/rivest/Destest.txt + ABSTRACT + -------- + + We present a simple way to test the correctness of a DES implementation: + Use the recurrence relation: + + X0 = 9474B8E8C73BCA7D (hexadecimal) + + X(i+1) = IF (i is even) THEN E(Xi,Xi) ELSE D(Xi,Xi) + + to compute a sequence of 64-bit values: X0, X1, X2, ..., X16. Here + E(X,K) denotes the DES encryption of X using key K, and D(X,K) denotes + the DES decryption of X using key K. If you obtain + + X16 = 1B1A2DDB4C642438 + + your implementation does not have any of the 36,568 possible single-fault + errors described herein. + """ + def runTest(self): + from Crypto.Cipher import DES + from binascii import b2a_hex + + X = [] + X[0:] = [b('\x94\x74\xB8\xE8\xC7\x3B\xCA\x7D')] + + for i in range(16): + c = DES.new(X[i],DES.MODE_ECB) + if not (i&1): # (num&1) returns 1 for odd numbers + X[i+1:] = [c.encrypt(X[i])] # even + else: + X[i+1:] = [c.decrypt(X[i])] # odd + + self.assertEqual(b2a_hex(X[16]), + b2a_hex(b('\x1B\x1A\x2D\xDB\x4C\x64\x24\x38'))) + def get_tests(config={}): from Crypto.Cipher import DES from common import make_block_tests - return make_block_tests(DES, "DES", test_data) + return make_block_tests(DES, "DES", test_data) + [RonRivestTest()] if __name__ == '__main__': import unittest diff --git a/lib/Crypto/SelfTest/Cipher/test_DES3.py b/lib/Crypto/SelfTest/Cipher/test_DES3.py index 2984e54..6a8626e 100644 --- a/lib/Crypto/SelfTest/Cipher/test_DES3.py +++ b/lib/Crypto/SelfTest/Cipher/test_DES3.py @@ -27,10 +27,11 @@ __revision__ = "$Id$" from common import dict # For compatibility with Python 2.1 and 2.2 +from Crypto.Util.py3compat import * # This is a list of (plaintext, ciphertext, key, description) tuples. -SP800_20_A1_KEY = "01" * 24 -SP800_20_A2_PT = "00" * 8 +SP800_20_A1_KEY = '01' * 24 +SP800_20_A2_PT = '00' * 8 test_data = [ # Test vector from Appendix B of NIST SP 800-67 # "Recommendation for the Triple Data Encryption Algorithm (TDEA) Block diff --git a/lib/Crypto/SelfTest/Cipher/test_XOR.py b/lib/Crypto/SelfTest/Cipher/test_XOR.py index c18e50a..a4d542a 100644 --- a/lib/Crypto/SelfTest/Cipher/test_XOR.py +++ b/lib/Crypto/SelfTest/Cipher/test_XOR.py @@ -28,6 +28,8 @@ import unittest __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (plaintext, ciphertext, key) tuples. test_data = [ # Test vectors written from scratch. (Nobody posts XOR test vectors on the web? How disappointing.) diff --git a/lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py b/lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py index 566cbf5..7aa1703 100644 --- a/lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py +++ b/lib/Crypto/SelfTest/Cipher/test_pkcs1_15.py @@ -23,22 +23,25 @@ __revision__ = "$Id$" import unittest - -from string import maketrans +import sys from Crypto.PublicKey import RSA from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex from Crypto import Random from Crypto.Cipher import PKCS1_v1_5 as PKCS +from Crypto.Util.py3compat import * def rws(t): """Remove white spaces, tabs, and new lines from a string""" - return t.translate(maketrans("",""),'\n\t ') + for c in ['\n', '\t', ' ']: + t = t.replace(c,'') + return t def t2b(t): """Convert a text string with bytes in hex form to a byte string""" - clean = rws(t) + clean = b(rws(t)) if len(clean)%2 == 1: + print clean raise ValueError("Even number of characters expected") return a2b_hex(clean) @@ -116,7 +119,7 @@ HKukWBcq9f/UOmS0oEhai/6g+Uf7VHJdWaeO5LzuvwU= # The real test key._randfunc = randGen(t2b(test[3])) cipher = PKCS.new(key) - ct = cipher.encrypt(test[1]) + ct = cipher.encrypt(b(test[1])) self.assertEqual(ct, t2b(test[2])) def testEncrypt2(self): @@ -132,7 +135,7 @@ HKukWBcq9f/UOmS0oEhai/6g+Uf7VHJdWaeO5LzuvwU= # The real test cipher = PKCS.new(key) pt = cipher.decrypt(t2b(test[2]), "---") - self.assertEqual(pt, test[1]) + self.assertEqual(pt, b(test[1])) def testVerify2(self): # Verify that decryption fails if ciphertext is not as long as @@ -143,9 +146,9 @@ HKukWBcq9f/UOmS0oEhai/6g+Uf7VHJdWaeO5LzuvwU= # Verify that decryption fails if there are less then 8 non-zero padding # bytes - pt = '\x00\x02' + '\xFF'*7 + '\x00' + '\x45'*118 + pt = b('\x00\x02' + '\xFF'*7 + '\x00' + '\x45'*118) ct = self.key1024.encrypt(pt, 0)[0] - ct = '\x00'*(128-len(ct)) + ct + ct = b('\x00'*(128-len(ct))) + ct self.assertEqual("---", cipher.decrypt(ct, "---")) def testEncryptVerify1(self): diff --git a/lib/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py b/lib/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py index 0244fe2..accca61 100644 --- a/lib/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py +++ b/lib/Crypto/SelfTest/Cipher/test_pkcs1_oaep.py @@ -26,9 +26,9 @@ __revision__ = "$Id$" import unittest -from string import maketrans from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex +from Crypto.Util.py3compat import * from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_OAEP as PKCS from Crypto.Hash import MD2,MD5,SHA as SHA1,SHA256,RIPEMD @@ -36,7 +36,9 @@ from Crypto import Random def rws(t): """Remove white spaces, tabs, and new lines from a string""" - return t.translate(maketrans("",""),'\n\t ') + for c in ['\n', '\t', ' ']: + t = t.replace(c,'') + return t def t2b(t): """Convert a text string with bytes in hex form to a byte string""" @@ -306,7 +308,7 @@ class PKCS1_OAEP_Tests(unittest.TestCase): # Simplest possible negative tests for ct_size in (127,128,129): cipher = PKCS.new(self.key1024) - self.assertRaises(ValueError, cipher.decrypt, '\x00'*ct_size) + self.assertRaises(ValueError, cipher.decrypt, bchr(0x00)*ct_size) def testEncryptDecrypt1(self): # Encrypt/Decrypt messages of length [0..128-2*20-2] @@ -350,7 +352,7 @@ class PKCS1_OAEP_Tests(unittest.TestCase): def newMGF(seed,maskLen): global mgfcalls mgfcalls += 1 - return '\x00'*maskLen + return bchr(0x00)*maskLen mgfcalls = 0 pt = self.rng(32) cipher = PKCS.new(self.key1024, mgfunc=newMGF) diff --git a/lib/Crypto/SelfTest/Hash/__init__.py b/lib/Crypto/SelfTest/Hash/__init__.py index b6e6053..d457519 100644 --- a/lib/Crypto/SelfTest/Hash/__init__.py +++ b/lib/Crypto/SelfTest/Hash/__init__.py @@ -34,10 +34,14 @@ def get_tests(config={}): import test_MD5; tests += test_MD5.get_tests(config=config) import test_RIPEMD; tests += test_RIPEMD.get_tests(config=config) import test_SHA; tests += test_SHA.get_tests(config=config) - import test_SHA224; tests += test_SHA224.get_tests(config=config) import test_SHA256; tests += test_SHA256.get_tests(config=config) - import test_SHA384; tests += test_SHA384.get_tests(config=config) - import test_SHA512; tests += test_SHA512.get_tests(config=config) + try: + import test_SHA224; tests += test_SHA224.get_tests(config=config) + import test_SHA384; tests += test_SHA384.get_tests(config=config) + import test_SHA512; tests += test_SHA512.get_tests(config=config) + except ImportError: + import sys + sys.stderr.write("SelfTest: warning: not testing SHA224/SHA384/SHA512 modules (not available)\n") return tests if __name__ == '__main__': diff --git a/lib/Crypto/SelfTest/Hash/common.py b/lib/Crypto/SelfTest/Hash/common.py index 4e6261a..f77fb0f 100644 --- a/lib/Crypto/SelfTest/Hash/common.py +++ b/lib/Crypto/SelfTest/Hash/common.py @@ -29,7 +29,7 @@ __revision__ = "$Id$" import sys import unittest import binascii -import string +from Crypto.Util.py3compat import * # For compatibility with Python 2.1 and Python 2.2 if sys.hexversion < 0x02030000: @@ -38,7 +38,7 @@ if sys.hexversion < 0x02030000: def dict(**kwargs): return kwargs.copy() else: - dict = __builtins__['dict'] + dict = dict class HashDigestSizeSelfTest(unittest.TestCase): @@ -84,9 +84,14 @@ class HashSelfTest(unittest.TestCase): out3 = h.hexdigest() out4 = binascii.b2a_hex(h.digest()) + # PY3K: hexdigest() should return str(), and digest() bytes self.assertEqual(self.expected, out1) # h = .new(); h.update(data); h.digest() - self.assertEqual(self.expected, out2) # h = .new(); h.update(data); h.hexdigest() - self.assertEqual(self.expected, out3) # h = .new(data); h.hexdigest() + if sys.version_info[0] == 2: + self.assertEqual(self.expected, out2) # h = .new(); h.update(data); h.hexdigest() + self.assertEqual(self.expected, out3) # h = .new(data); h.hexdigest() + else: + self.assertEqual(self.expected.decode(), out2) # h = .new(); h.update(data); h.hexdigest() + self.assertEqual(self.expected.decode(), out3) # h = .new(data); h.hexdigest() self.assertEqual(self.expected, out4) # h = .new(data); h.digest() # Verify that new() object method produces a fresh hash object @@ -130,13 +135,11 @@ class MACSelfTest(unittest.TestCase): def runTest(self): for hashname in self.expected_dict.keys(): hashmod = self.hashmods[hashname] - key = binascii.a2b_hex(self.key) - data = binascii.a2b_hex(self.input) + key = binascii.a2b_hex(b(self.key)) + data = binascii.a2b_hex(b(self.input)) # Strip whitespace from the expected string (which should be in lowercase-hex) - expected = self.expected_dict[hashname] - for ch in string.whitespace: - expected = expected.replace(ch, "") + expected = b("".join(self.expected_dict[hashname].split())) h = self.hashmod.new(key, digestmod=hashmod) h.update(data) @@ -150,12 +153,17 @@ class MACSelfTest(unittest.TestCase): # Test .copy() h2 = h.copy() - h.update("blah blah blah") # Corrupt the original hash object + h.update(b("blah blah blah")) # Corrupt the original hash object out5 = binascii.b2a_hex(h2.digest()) # The copied hash object should return the correct result + # PY3K: hexdigest() should return str(), and digest() bytes self.assertEqual(expected, out1) - self.assertEqual(expected, out2) - self.assertEqual(expected, out3) + if sys.version_info[0] == 2: + self.assertEqual(expected, out2) + self.assertEqual(expected, out3) + else: + self.assertEqual(expected.decode(), out2) + self.assertEqual(expected.decode(), out3) self.assertEqual(expected, out4) self.assertEqual(expected, out5) @@ -163,13 +171,15 @@ def make_hash_tests(module, module_name, test_data, digest_size, oid=None): tests = [] for i in range(len(test_data)): row = test_data[i] + (expected, input) = map(b,row[0:2]) if len(row) < 3: - (expected, input) = row description = repr(input) else: - (expected, input, description) = row + description = row[2].encode('latin-1') name = "%s #%d: %s" % (module_name, i+1, description) tests.append(HashSelfTest(module, name, expected, input)) + if oid is not None: + oid = b(oid) name = "%s #%d: digest_size" % (module_name, i+1) tests.append(HashDigestSizeSelfTest(module, name, digest_size)) tests.append(HashTestOID(module, oid)) diff --git a/lib/Crypto/SelfTest/Hash/test_HMAC.py b/lib/Crypto/SelfTest/Hash/test_HMAC.py index 44b4022..c01c97b 100644 --- a/lib/Crypto/SelfTest/Hash/test_HMAC.py +++ b/lib/Crypto/SelfTest/Hash/test_HMAC.py @@ -27,6 +27,7 @@ __revision__ = "$Id$" 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. test_data = [ @@ -174,7 +175,9 @@ test_data = [ bfdc63644f0713938a7f51535c3a35e2 '''), 'RFC 4231 #7 (HMAC-SHA256)'), +] +hashlib_test_data = [ # Test case 8 (SHA224) ('4a656665', '7768617420646f2079612077616e74' @@ -199,9 +202,17 @@ test_data = [ ] def get_tests(config={}): - from Crypto.Hash import HMAC, MD5, SHA as SHA1, SHA256, SHA224, SHA384, SHA512 + global test_data + from Crypto.Hash import HMAC, MD5, SHA as SHA1, SHA256 from common import make_mac_tests - hashmods = dict(MD5=MD5, SHA1=SHA1, SHA224=SHA224, SHA256=SHA256, SHA384=SHA384, SHA512=SHA512, default=None) + hashmods = dict(MD5=MD5, SHA1=SHA1, SHA256=SHA256, default=None) + try: + from Crypto.Hash import SHA224, SHA384, SHA512 + hashmods.update(dict(SHA224=SHA224, SHA384=SHA384, SHA512=SHA512)) + test_data += hashlib_test_data + except ImportError: + import sys + sys.stderr.write("SelfTest: warning: not testing HMAC-SHA224/384/512 (not available)\n") return make_mac_tests(HMAC, "HMAC", test_data, hashmods) if __name__ == '__main__': diff --git a/lib/Crypto/SelfTest/Hash/test_MD2.py b/lib/Crypto/SelfTest/Hash/test_MD2.py index 4f7817e..db636d4 100644 --- a/lib/Crypto/SelfTest/Hash/test_MD2.py +++ b/lib/Crypto/SelfTest/Hash/test_MD2.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (expected_result, input[, description]) tuples. test_data = [ # Test vectors from RFC 1319 diff --git a/lib/Crypto/SelfTest/Hash/test_MD4.py b/lib/Crypto/SelfTest/Hash/test_MD4.py index 48a6c24..1727bb6 100644 --- a/lib/Crypto/SelfTest/Hash/test_MD4.py +++ b/lib/Crypto/SelfTest/Hash/test_MD4.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (expected_result, input[, description]) tuples. test_data = [ # Test vectors from RFC 1320 diff --git a/lib/Crypto/SelfTest/Hash/test_MD5.py b/lib/Crypto/SelfTest/Hash/test_MD5.py index 4636ea3..2e293fc 100644 --- a/lib/Crypto/SelfTest/Hash/test_MD5.py +++ b/lib/Crypto/SelfTest/Hash/test_MD5.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (expected_result, input[, description]) tuples. test_data = [ # Test vectors from RFC 1321 diff --git a/lib/Crypto/SelfTest/Hash/test_RIPEMD.py b/lib/Crypto/SelfTest/Hash/test_RIPEMD.py index 1d1dd4d..6673a93 100644 --- a/lib/Crypto/SelfTest/Hash/test_RIPEMD.py +++ b/lib/Crypto/SelfTest/Hash/test_RIPEMD.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # This is a list of (expected_result, input[, description]) tuples. test_data = [ # Test vectors downloaded 2008-09-12 from diff --git a/lib/Crypto/SelfTest/Hash/test_SHA.py b/lib/Crypto/SelfTest/Hash/test_SHA.py index 5291f00..7d72e77 100644 --- a/lib/Crypto/SelfTest/Hash/test_SHA.py +++ b/lib/Crypto/SelfTest/Hash/test_SHA.py @@ -26,6 +26,8 @@ __revision__ = "$Id$" +from Crypto.Util.py3compat import * + # Test vectors from various sources # This is a list of (expected_result, input[, description]) tuples. test_data = [ @@ -43,7 +45,7 @@ test_data = [ # RFC 3174: Section 7.3, "TEST4" (multiple of 512 bits) ('dea356a2cddd90c7a7ecedc5ebb563934f460452', - "01234567" * 80, + '01234567' * 80, '"01234567" * 80'), ] diff --git a/lib/Crypto/SelfTest/Hash/test_SHA224.py b/lib/Crypto/SelfTest/Hash/test_SHA224.py index f47470f..a60f35a 100644 --- a/lib/Crypto/SelfTest/Hash/test_SHA224.py +++ b/lib/Crypto/SelfTest/Hash/test_SHA224.py @@ -37,7 +37,7 @@ test_data = [ ('75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525', 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'), # RFC 3874: Section 3.3, "Test Vector #3 - ('20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67', 'a' * 10**6), + ('20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67', 'a' * 10**6, "'a' * 10**6"), # Examples from http://de.wikipedia.org/wiki/Secure_Hash_Algorithm ('d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f', ''), diff --git a/lib/Crypto/SelfTest/Hash/test_SHA256.py b/lib/Crypto/SelfTest/Hash/test_SHA256.py index f759b39..4b45110 100644 --- a/lib/Crypto/SelfTest/Hash/test_SHA256.py +++ b/lib/Crypto/SelfTest/Hash/test_SHA256.py @@ -27,12 +27,13 @@ __revision__ = "$Id$" import unittest +from Crypto.Util.py3compat import * class LargeSHA256Test(unittest.TestCase): def runTest(self): """SHA256: 512/520 MiB test""" from Crypto.Hash import SHA256 - zeros = '\0' * (1024*1024) + zeros = bchr(0x00) * (1024*1024) h = SHA256.new(zeros) for i in xrange(511): diff --git a/lib/Crypto/SelfTest/Hash/test_SHA384.py b/lib/Crypto/SelfTest/Hash/test_SHA384.py index 49da8b8..b7a72c0 100644 --- a/lib/Crypto/SelfTest/Hash/test_SHA384.py +++ b/lib/Crypto/SelfTest/Hash/test_SHA384.py @@ -37,7 +37,7 @@ test_data = [ ('09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039', 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu'), # RFC 4634: Section Page 8.4, "Test 3" - ('9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985', 'a' * 10**6), + ('9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985', 'a' * 10**6, "'a' * 10**6"), # Taken from http://de.wikipedia.org/wiki/Secure_Hash_Algorithm ('38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b', ''), diff --git a/lib/Crypto/SelfTest/Hash/test_SHA512.py b/lib/Crypto/SelfTest/Hash/test_SHA512.py index fb9269f..cb86177 100644 --- a/lib/Crypto/SelfTest/Hash/test_SHA512.py +++ b/lib/Crypto/SelfTest/Hash/test_SHA512.py @@ -37,7 +37,7 @@ test_data = [ ('8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909', 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu'), # RFC 4634: Section Page 8.4, "Test 3" - ('e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b', 'a' * 10**6), + ('e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b', 'a' * 10**6, "'a' * 10**6"), # Taken from http://de.wikipedia.org/wiki/Secure_Hash_Algorithm ('cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e', ''), diff --git a/lib/Crypto/SelfTest/Protocol/__init__.py b/lib/Crypto/SelfTest/Protocol/__init__.py index 5d1867c..f1726a8 100644 --- a/lib/Crypto/SelfTest/Protocol/__init__.py +++ b/lib/Crypto/SelfTest/Protocol/__init__.py @@ -31,6 +31,7 @@ def get_tests(config={}): import test_chaffing; tests += test_chaffing.get_tests(config=config) import test_rfc1751; tests += test_rfc1751.get_tests(config=config) import test_KDF; tests += test_KDF.get_tests(config=config) + import test_AllOrNothing; tests += test_AllOrNothing.get_tests(config=config) return tests if __name__ == '__main__': diff --git a/lib/Crypto/SelfTest/Protocol/test_AllOrNothing.py b/lib/Crypto/SelfTest/Protocol/test_AllOrNothing.py new file mode 100644 index 0000000..a211eab --- /dev/null +++ b/lib/Crypto/SelfTest/Protocol/test_AllOrNothing.py @@ -0,0 +1,76 @@ +# +# Test script for Crypto.Protocol.AllOrNothing +# +# Part of the Python Cryptography Toolkit +# +# Written by Andrew Kuchling and others +# +# =================================================================== +# The contents of this file are dedicated to the public domain. To +# the extent that dedication to the public domain is not available, +# everyone is granted a worldwide, perpetual, royalty-free, +# non-exclusive license to exercise all rights associated with the +# contents of this file for any purpose whatsoever. +# No rights are reserved. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# =================================================================== + +__revision__ = "$Id$" + +import unittest +from Crypto.Protocol import AllOrNothing +from Crypto.Util.py3compat import * + +text = b("""\ +When in the Course of human events, it becomes necessary for one people to +dissolve the political bands which have connected them with another, and to +assume among the powers of the earth, the separate and equal station to which +the Laws of Nature and of Nature's God entitle them, a decent respect to the +opinions of mankind requires that they should declare the causes which impel +them to the separation. + +We hold these truths to be self-evident, that all men are created equal, that +they are endowed by their Creator with certain unalienable Rights, that among +these are Life, Liberty, and the pursuit of Happiness. That to secure these +rights, Governments are instituted among Men, deriving their just powers from +the consent of the governed. That whenever any Form of Government becomes +destructive of these ends, it is the Right of the People to alter or to +abolish it, and to institute new Government, laying its foundation on such +principles and organizing its powers in such form, as to them shall seem most +likely to effect their Safety and Happiness. +""") + +class AllOrNothingTest (unittest.TestCase): + + def runTest(self): + "Simple test of AllOrNothing" + + from Crypto.Cipher import AES + import base64 + + # The current AllOrNothing will fail + # every so often. Repeat the test + # several times to force this. + for i in range(50): + x = AllOrNothing.AllOrNothing(AES) + + msgblocks = x.digest(text) + + # get a new undigest-only object so there's no leakage + y = AllOrNothing.AllOrNothing(AES) + text2 = y.undigest(msgblocks) + self.assertEqual(text, text2) + +def get_tests(config={}): + return [AllOrNothingTest()] + +if __name__ == "__main__": + unittest.main() diff --git a/lib/Crypto/SelfTest/Protocol/test_KDF.py b/lib/Crypto/SelfTest/Protocol/test_KDF.py index c303718..46082a5 100644 --- a/lib/Crypto/SelfTest/Protocol/test_KDF.py +++ b/lib/Crypto/SelfTest/Protocol/test_KDF.py @@ -30,7 +30,7 @@ from Crypto.Hash import SHA as SHA1,HMAC from Crypto.Protocol.KDF import * -def t2b(t): return unhexlify(t) +def t2b(t): return unhexlify(b(t)) class PBKDF1_Tests(unittest.TestCase): diff --git a/lib/Crypto/SelfTest/Protocol/test_chaffing.py b/lib/Crypto/SelfTest/Protocol/test_chaffing.py index 26c57f8..5fa0120 100644 --- a/lib/Crypto/SelfTest/Protocol/test_chaffing.py +++ b/lib/Crypto/SelfTest/Protocol/test_chaffing.py @@ -61,11 +61,11 @@ class ChaffingTest (unittest.TestCase): c = Chaffing.Chaff(1.0, 1) c.chaff(data) chaff = c.chaff(data) - self.assertEquals(len(chaff), 4) + self.assertEqual(len(chaff), 4) c = Chaffing.Chaff(0.0, 1) chaff = c.chaff(data) - self.assertEquals(len(chaff), 2) + self.assertEqual(len(chaff), 2) def get_tests(config={}): return [ChaffingTest()] diff --git a/lib/Crypto/SelfTest/Protocol/test_rfc1751.py b/lib/Crypto/SelfTest/Protocol/test_rfc1751.py index 84e9aef..0878cc5 100644 --- a/lib/Crypto/SelfTest/Protocol/test_rfc1751.py +++ b/lib/Crypto/SelfTest/Protocol/test_rfc1751.py @@ -28,6 +28,7 @@ __revision__ = "$Id$" import binascii import unittest from Crypto.Util import RFC1751 +from Crypto.Util.py3compat import * test_data = [('EB33F77EE73D4053', 'TIDE ITCH SLOW REIN RULE MOT'), ('CCAC2AED591056BE4F90FD441C534766', @@ -41,16 +42,16 @@ class RFC1751Test_k2e (unittest.TestCase): def runTest (self): "Check converting keys to English" for key, words in test_data: - key=binascii.a2b_hex(key) - self.assertEquals(RFC1751.key_to_english(key), words) + key=binascii.a2b_hex(b(key)) + self.assertEqual(RFC1751.key_to_english(key), words) class RFC1751Test_e2k (unittest.TestCase): def runTest (self): "Check converting English strings to keys" for key, words in test_data: - key=binascii.a2b_hex(key) - self.assertEquals(RFC1751.english_to_key(words), key) + key=binascii.a2b_hex(b(key)) + self.assertEqual(RFC1751.english_to_key(words), key) # class RFC1751Test diff --git a/lib/Crypto/SelfTest/PublicKey/test_DSA.py b/lib/Crypto/SelfTest/PublicKey/test_DSA.py index 0fa7df6..b05f69a 100644 --- a/lib/Crypto/SelfTest/PublicKey/test_DSA.py +++ b/lib/Crypto/SelfTest/PublicKey/test_DSA.py @@ -26,17 +26,21 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +import os +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * import unittest -import string from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex def _sws(s): - """Strip whitespace""" - s = s.translate(string.maketrans(string.whitespace, " "*len(string.whitespace))) - s = s.replace(" ", "") - return s + """Remove whitespace from a text or byte string""" + if isinstance(s,str): + return "".join(s.split()) + else: + return b("").join(s.split()) class DSATest(unittest.TestCase): # Test vector from "Appendix 5. Example of the DSA" of @@ -63,7 +67,7 @@ class DSATest(unittest.TestCase): k = _sws("""358dad57 1462710f 50e254cf 1a376b2b deaadfbf""") k_inverse = _sws("""0d516729 8202e49b 4116ac10 4fc3f415 ae52f917""") - m = b2a_hex("abc") + m = b2a_hex(b("abc")) m_hash = _sws("""a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d""") r = _sws("""8bac1ab6 6410435c b7181f95 b16ab97c 92b341c0""") s = _sws("""41e2345f 1f56df24 58f426d1 55b4ba2d b6dcd8c8""") @@ -153,8 +157,8 @@ class DSATest(unittest.TestCase): self.assertRaises(TypeError, dsaObj.sign, m_hash, k) # Check __eq__ and __ne__ - self.assert_(dsaObj.publickey() == dsaObj.publickey()) - self.assert_(not (dsaObj.publickey() != dsaObj.publickey())) + self.assertEqual(dsaObj.publickey() == dsaObj.publickey(),True) # assert_ + self.assertEqual(dsaObj.publickey() != dsaObj.publickey(),False) # failIf def _test_signing(self, dsaObj): k = a2b_hex(self.k) @@ -169,7 +173,7 @@ class DSATest(unittest.TestCase): r = bytes_to_long(a2b_hex(self.r)) s = bytes_to_long(a2b_hex(self.s)) self.assertEqual(1, dsaObj.verify(m_hash, (r, s))) - self.assertEqual(0, dsaObj.verify(m_hash + "\0", (r, s))) + self.assertEqual(0, dsaObj.verify(m_hash + b("\0"), (r, s))) class DSAFastMathTest(DSATest): def setUp(self): @@ -221,9 +225,16 @@ def get_tests(config={}): from Crypto.PublicKey import _fastmath tests += list_test_cases(DSAFastMathTest) except ImportError: - pass - if config.get('slow_tests',1): - tests += list_test_cases(DSASlowMathTest) + from distutils.sysconfig import get_config_var + import inspect + _fm_path = os.path.normpath(os.path.dirname(os.path.abspath( + inspect.getfile(inspect.currentframe()))) + +"/../../PublicKey/_fastmath"+get_config_var("SO")) + if os.path.exists(_fm_path): + raise ImportError("While the _fastmath module exists, importing "+ + "it failed. This may point to the gmp or mpir shared library "+ + "not being in the path. _fastmath was found at "+_fm_path) + tests += list_test_cases(DSASlowMathTest) return tests if __name__ == '__main__': diff --git a/lib/Crypto/SelfTest/PublicKey/test_RSA.py b/lib/Crypto/SelfTest/PublicKey/test_RSA.py index 17573cc..c971042 100644 --- a/lib/Crypto/SelfTest/PublicKey/test_RSA.py +++ b/lib/Crypto/SelfTest/PublicKey/test_RSA.py @@ -26,7 +26,11 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +import os +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * import unittest from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex @@ -225,12 +229,12 @@ class RSATest(unittest.TestCase): self.assertEqual(1, rsaObj.e > 1) # e > 1 # Public keys should not be able to sign or decrypt - self.assertRaises(TypeError, rsaObj.sign, ciphertext, "") + self.assertRaises(TypeError, rsaObj.sign, ciphertext, b("")) self.assertRaises(TypeError, rsaObj.decrypt, ciphertext) # Check __eq__ and __ne__ - self.assert_(rsaObj.publickey() == rsaObj.publickey()) - self.assert_(not (rsaObj.publickey() != rsaObj.publickey())) + self.assertEqual(rsaObj.publickey() == rsaObj.publickey(),True) # assert_ + self.assertEqual(rsaObj.publickey() != rsaObj.publickey(),False) # failIf def _exercise_primitive(self, rsaObj): # Since we're using a randomly-generated key, we can't check the test @@ -242,7 +246,7 @@ class RSATest(unittest.TestCase): plaintext = rsaObj.decrypt((ciphertext,)) # Test encryption (2 arguments) - (new_ciphertext2,) = rsaObj.encrypt(plaintext, "") + (new_ciphertext2,) = rsaObj.encrypt(plaintext, b("")) self.assertEqual(b2a_hex(ciphertext), b2a_hex(new_ciphertext2)) # Test blinded decryption @@ -253,7 +257,7 @@ class RSATest(unittest.TestCase): self.assertEqual(b2a_hex(plaintext), b2a_hex(unblinded_plaintext)) # Test signing (2 arguments) - signature2 = rsaObj.sign(ciphertext, "") + signature2 = rsaObj.sign(ciphertext, b("")) self.assertEqual((bytes_to_long(plaintext),), signature2) # Test verification @@ -263,7 +267,7 @@ class RSATest(unittest.TestCase): plaintext = a2b_hex(self.plaintext) # Test encryption (2 arguments) - (new_ciphertext2,) = rsaObj.encrypt(plaintext, "") + (new_ciphertext2,) = rsaObj.encrypt(plaintext, b("")) # Exercise verification rsaObj.verify(new_ciphertext2, (bytes_to_long(plaintext),)) @@ -273,7 +277,7 @@ class RSATest(unittest.TestCase): ciphertext = a2b_hex(self.ciphertext) # Test encryption (2 arguments) - (new_ciphertext2,) = rsaObj.encrypt(plaintext, "") + (new_ciphertext2,) = rsaObj.encrypt(plaintext, b("")) self.assertEqual(b2a_hex(ciphertext), b2a_hex(new_ciphertext2)) def _check_decryption(self, rsaObj): @@ -310,7 +314,7 @@ class RSATest(unittest.TestCase): message = a2b_hex(self.ciphertext) # Test signing (2 argument) - self.assertEqual((signature,), rsaObj.sign(message, "")) + self.assertEqual((signature,), rsaObj.sign(message, b(""))) class RSAFastMathTest(RSATest): def setUp(self): @@ -391,7 +395,15 @@ def get_tests(config={}): from Crypto.PublicKey import _fastmath tests += list_test_cases(RSAFastMathTest) except ImportError: - print "Failed to import fastmath module." + from distutils.sysconfig import get_config_var + import inspect + _fm_path = os.path.normpath(os.path.dirname(os.path.abspath( + inspect.getfile(inspect.currentframe()))) + +"/../../PublicKey/_fastmath"+get_config_var("SO")) + if os.path.exists(_fm_path): + raise ImportError("While the _fastmath module exists, importing "+ + "it failed. This may point to the gmp or mpir shared library "+ + "not being in the path. _fastmath was found at "+_fm_path) if config.get('slow_tests',1): tests += list_test_cases(RSASlowMathTest) return tests diff --git a/lib/Crypto/SelfTest/PublicKey/test_importKey.py b/lib/Crypto/SelfTest/PublicKey/test_importKey.py index e54a647..ed4d004 100644 --- a/lib/Crypto/SelfTest/PublicKey/test_importKey.py +++ b/lib/Crypto/SelfTest/PublicKey/test_importKey.py @@ -28,13 +28,12 @@ import unittest from Crypto.PublicKey import RSA from Crypto.SelfTest.st_common import * -from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex +from Crypto.Util.py3compat import * from Crypto.Util.number import inverse class ImportKeyTests(unittest.TestCase): - - # 512-bit RSA key generated with openssl (pure PEM format) - rsaKeyPEM = '''-----BEGIN RSA PRIVATE KEY----- + # 512-bit RSA key generated with openssl + rsaKeyPEM = '''-----BEGIN RSA PRIVATE KEY----- MIIBOwIBAAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+TLr7UkvEtFrRhDDKMtuII q19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQJACUSDEp8RTe32ftq8IwG8 Wojl5mAd1wFiIOrZ/Uv8b963WJOJiuQcVN29vxU5+My9GPZ7RA3hrDBEAoHUDPrI @@ -44,8 +43,8 @@ JACAr3sJQJGxIQIgarRp+m1WSKV1MciwMaTOnbU7wxFs9DP1pva76lYBzgUCIQC9 n0CnZCJ6IZYqSt0H5N7+Q+2Ro64nuwV/OSQfM6sBwQ== -----END RSA PRIVATE KEY-----''' - # As above, but this is actually an unencrypted PKCS#8 key - rsaKeyPEM8 = '''-----BEGIN PRIVATE KEY----- + # As above, but this is actually an unencrypted PKCS#8 key + rsaKeyPEM8 = '''-----BEGIN PRIVATE KEY----- MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEAvx4nkAqgiyNRGlwS ga5tkzEsPv6RP5MuvtSS8S0WtGEMMoy24girX0WsvilQgzKY8xIsGfeEkt7fQPDj wZAzhQIDAQABAkAJRIMSnxFN7fZ+2rwjAbxaiOXmYB3XAWIg6tn9S/xv3rdYk4mK @@ -56,11 +55,11 @@ yLAxpM6dtTvDEWz0M/Wm9rvqVgHOBQIhAL2fQKdkInohlipK3Qfk3v5D7ZGjrie7 BX85JB8zqwHB -----END PRIVATE KEY-----''' - # The same RSA private key as in rsaKeyPEM, but now encrypted - rsaKeyEncryptedPEM=( + # The same RSA private key as in rsaKeyPEM, but now encrypted + rsaKeyEncryptedPEM=( - # With DES and passphrase 'test' - ('test', '''-----BEGIN RSA PRIVATE KEY----- + # With DES and passphrase 'test' + ('test', '''-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-CBC,AF8F9A40BD2FA2FC @@ -72,10 +71,10 @@ BCNRMdcexozWtAFNNqSzfW58MJL2OdMi21ED184EFytIc1BlB+FZiGZduwKGuaKy IRX3TgQI0IjrVuLmvlZKbGWP18FXj7I7k9tSsNOOzllTTdq3ny5vgM3A+ynfAaxp dysKznQ6P+IoqML1WxAID4aGRMWka+uArOJ148Rbj9s= -----END RSA PRIVATE KEY-----''', - "\xAF\x8F\x9A\x40\xBD\x2F\xA2\xFC"), + "\xAF\x8F\x9A\x40\xBD\x2F\xA2\xFC"), - # With Triple-DES and passphrase 'rocking' - ('rocking', '''-----BEGIN RSA PRIVATE KEY----- + # With Triple-DES and passphrase 'rocking' + ('rocking', '''-----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,C05D6C07F7FC02F6 @@ -87,188 +86,188 @@ sopxQQtP8XEHIJEdd5/p1oieRcWTCNyY8EkslxDSsrf0OtZp6mZH9N+KU47cgQtt 9qGORmlWnsIoFFKcDohbtOaWBTKhkj5h6OkLjFjfU/sBeV1c+7wDT3dAy5tawXjG YSxC7qDQIT/RECvV3+oQKEcmpEujn45wAnkTi12BH30= -----END RSA PRIVATE KEY-----''', - "\xC0\x5D\x6C\x07\xF7\xFC\x02\xF6"), - ) + "\xC0\x5D\x6C\x07\xF7\xFC\x02\xF6"), + ) - rsaPublicKeyPEM = '''-----BEGIN PUBLIC KEY----- + rsaPublicKeyPEM = '''-----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL8eJ5AKoIsjURpcEoGubZMxLD7+kT+T Lr7UkvEtFrRhDDKMtuIIq19FrL4pUIMymPMSLBn3hJLe30Dw48GQM4UCAwEAAQ== -----END PUBLIC KEY-----''' - # Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM' - rsaPublicKeyOpenSSH = '''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n''' - - # The private key, in PKCS#1 format encoded with DER - rsaKeyDER = a2b_hex( - '''3082013b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe - 913f932ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f312 - 2c19f78492dedf40f0e3c190338502030100010240094483129f114dedf6 - 7edabc2301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c - 54ddbdbf1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f - 2f3e1da61883f62980922bd8df545ce407c726241103b5e2c53723124a23 - 022100ca1fe924792cfcc96bfab74f344a68b418df578338064806000fe2 - a5c99a023702210087be1c3029504bcf34ec713d877947447813288975ca - 240080af7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53b - c3116cf433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07 - e4defe43ed91a3ae27bb057f39241f33ab01c1 - '''.replace(" ","")) - - # The private key, in unencrypted PKCS#8 format encoded with DER - rsaKeyDER8 = a2b_hex( - '''30820155020100300d06092a864886f70d01010105000482013f3082013 - b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe913f932 - ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f3122c19f78 - 492dedf40f0e3c190338502030100010240094483129f114dedf67edabc2 - 301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c54ddbdb - f1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f2f3e1da - 61883f62980922bd8df545ce407c726241103b5e2c53723124a23022100c - a1fe924792cfcc96bfab74f344a68b418df578338064806000fe2a5c99a0 - 23702210087be1c3029504bcf34ec713d877947447813288975ca240080a - f7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53bc3116cf - 433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07e4defe4 - 3ed91a3ae27bb057f39241f33ab01c1 - '''.replace(" ","")) - - rsaPublicKeyDER = a2b_hex( - '''305c300d06092a864886f70d0101010500034b003048024100bf1e27900a - a08b23511a5c1281ae6d93312c3efe913f932ebed492f12d16b4610c328c - b6e208ab5f45acbe2950833298f3122c19f78492dedf40f0e3c190338502 - 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) - - # 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) - pInv = inverse(p,q) - - def testImportKey1(self): - key = self.rsa.importKey(self.rsaKeyDER) - self.failUnless(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - self.assertEqual(key.d, self.d) - self.assertEqual(key.p, self.p) - self.assertEqual(key.q, self.q) - - def testImportKey2(self): - key = self.rsa.importKey(self.rsaPublicKeyDER) - self.failIf(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - - def testImportKey3(self): - key = self.rsa.importKey(self.rsaKeyPEM) - self.failUnless(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - self.assertEqual(key.d, self.d) - self.assertEqual(key.p, self.p) - self.assertEqual(key.q, self.q) - - def testImportKey4(self): - key = self.rsa.importKey(self.rsaPublicKeyPEM) - self.failIf(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - - def testImportKey5(self): - """Verifies that the imported key is still a valid RSA pair""" - key = self.rsa.importKey(self.rsaKeyPEM) - idem = key.encrypt(key.decrypt("Test"),0) - self.assertEqual(idem[0],"Test") - - def testImportKey6(self): - """Verifies that the imported key is still a valid RSA pair""" - key = self.rsa.importKey(self.rsaKeyDER) - idem = key.encrypt(key.decrypt("Test"),0) - self.assertEqual(idem[0],"Test") - - def testImportKey7(self): - key = self.rsa.importKey(self.rsaPublicKeyOpenSSH) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - - def testImportKey8(self): - for t in self.rsaKeyEncryptedPEM: - key = self.rsa.importKey(t[1], t[0]) - self.failUnless(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - self.assertEqual(key.d, self.d) - self.assertEqual(key.p, self.p) - self.assertEqual(key.q, self.q) - - def testImportKey9(self): - key = self.rsa.importKey(self.rsaKeyDER8) - self.failUnless(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - self.assertEqual(key.d, self.d) - self.assertEqual(key.p, self.p) - self.assertEqual(key.q, self.q) - - def testImportKey10(self): - key = self.rsa.importKey(self.rsaKeyPEM8) - self.failUnless(key.has_private()) - self.assertEqual(key.n, self.n) - self.assertEqual(key.e, self.e) - self.assertEqual(key.d, self.d) - self.assertEqual(key.p, self.p) - self.assertEqual(key.q, self.q) - - - ### - def testExportKey1(self): - key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) - derKey = key.exportKey("DER") - self.assertEqual(derKey, self.rsaKeyDER) - - def testExportKey2(self): - key = self.rsa.construct([self.n, self.e]) - derKey = key.exportKey("DER") - self.assertEqual(derKey, self.rsaPublicKeyDER) - - def testExportKey3(self): - key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) - pemKey = key.exportKey("PEM") - self.assertEqual(pemKey, self.rsaKeyPEM) - - def testExportKey4(self): - key = self.rsa.construct([self.n, self.e]) - pemKey = key.exportKey("PEM") - self.assertEqual(pemKey, self.rsaPublicKeyPEM) - - def testExportKey5(self): - key = self.rsa.construct([self.n, self.e]) - openssh_1 = key.exportKey("OpenSSH").split() - openssh_2 = self.rsaPublicKeyOpenSSH.split() - self.assertEqual(openssh_1[0], openssh_2[0]) - self.assertEqual(openssh_1[1], openssh_2[1]) - - 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 = 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]) - self.assertEqual(pemKey, t[1]) - - def testExportKey5(self): - key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) - derKey = key.exportKey("DER", pkcs=8) - self.assertEqual(derKey, self.rsaKeyDER8) - - def testExportKey6(self): - key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) - pemKey = key.exportKey("PEM", pkcs=8) - self.assertEqual(pemKey, self.rsaKeyPEM8) + # Obtained using 'ssh-keygen -i -m PKCS8 -f rsaPublicKeyPEM' + rsaPublicKeyOpenSSH = '''ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAQQC/HieQCqCLI1EaXBKBrm2TMSw+/pE/ky6+1JLxLRa0YQwyjLbiCKtfRay+KVCDMpjzEiwZ94SS3t9A8OPBkDOF comment\n''' + + # The private key, in PKCS#1 format encoded with DER + rsaKeyDER = a2b_hex( + '''3082013b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe + 913f932ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f312 + 2c19f78492dedf40f0e3c190338502030100010240094483129f114dedf6 + 7edabc2301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c + 54ddbdbf1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f + 2f3e1da61883f62980922bd8df545ce407c726241103b5e2c53723124a23 + 022100ca1fe924792cfcc96bfab74f344a68b418df578338064806000fe2 + a5c99a023702210087be1c3029504bcf34ec713d877947447813288975ca + 240080af7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53b + c3116cf433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07 + e4defe43ed91a3ae27bb057f39241f33ab01c1 + '''.replace(" ","")) + + # The private key, in unencrypted PKCS#8 format encoded with DER + rsaKeyDER8 = a2b_hex( + '''30820155020100300d06092a864886f70d01010105000482013f3082013 + b020100024100bf1e27900aa08b23511a5c1281ae6d93312c3efe913f932 + ebed492f12d16b4610c328cb6e208ab5f45acbe2950833298f3122c19f78 + 492dedf40f0e3c190338502030100010240094483129f114dedf67edabc2 + 301bc5a88e5e6601dd7016220ead9fd4bfc6fdeb75893898ae41c54ddbdb + f1539f8ccbd18f67b440de1ac30440281d40cfac839022100f20f2f3e1da + 61883f62980922bd8df545ce407c726241103b5e2c53723124a23022100c + a1fe924792cfcc96bfab74f344a68b418df578338064806000fe2a5c99a0 + 23702210087be1c3029504bcf34ec713d877947447813288975ca240080a + f7b094091b12102206ab469fa6d5648a57531c8b031a4ce9db53bc3116cf + 433f5a6f6bbea5601ce05022100bd9f40a764227a21962a4add07e4defe4 + 3ed91a3ae27bb057f39241f33ab01c1 + '''.replace(" ","")) + + rsaPublicKeyDER = a2b_hex( + '''305c300d06092a864886f70d0101010500034b003048024100bf1e27900a + a08b23511a5c1281ae6d93312c3efe913f932ebed492f12d16b4610c328c + b6e208ab5f45acbe2950833298f3122c19f78492dedf40f0e3c190338502 + 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) + + # 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) + pInv = inverse(p,q) + + def testImportKey1(self): + key = self.rsa.importKey(self.rsaKeyDER) + self.failUnless(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + self.assertEqual(key.d, self.d) + self.assertEqual(key.p, self.p) + self.assertEqual(key.q, self.q) + + def testImportKey2(self): + key = self.rsa.importKey(self.rsaPublicKeyDER) + self.failIf(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + + def testImportKey3(self): + key = self.rsa.importKey(self.rsaKeyPEM) + self.failUnless(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + self.assertEqual(key.d, self.d) + self.assertEqual(key.p, self.p) + self.assertEqual(key.q, self.q) + + def testImportKey4(self): + key = self.rsa.importKey(self.rsaPublicKeyPEM) + self.failIf(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + + def testImportKey5(self): + """Verifies that the imported key is still a valid RSA pair""" + key = self.rsa.importKey(self.rsaKeyPEM) + idem = key.encrypt(key.decrypt(b("Test")),0) + self.assertEqual(idem[0],b("Test")) + + def testImportKey6(self): + """Verifies that the imported key is still a valid RSA pair""" + key = self.rsa.importKey(self.rsaKeyDER) + idem = key.encrypt(key.decrypt(b("Test")),0) + self.assertEqual(idem[0],b("Test")) + + def testImportKey7(self): + key = self.rsa.importKey(self.rsaPublicKeyOpenSSH) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + + def testImportKey8(self): + for t in self.rsaKeyEncryptedPEM: + key = self.rsa.importKey(t[1], t[0]) + self.failUnless(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + self.assertEqual(key.d, self.d) + self.assertEqual(key.p, self.p) + self.assertEqual(key.q, self.q) + + def testImportKey9(self): + key = self.rsa.importKey(self.rsaKeyDER8) + self.failUnless(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + self.assertEqual(key.d, self.d) + self.assertEqual(key.p, self.p) + self.assertEqual(key.q, self.q) + + def testImportKey10(self): + key = self.rsa.importKey(self.rsaKeyPEM8) + self.failUnless(key.has_private()) + self.assertEqual(key.n, self.n) + self.assertEqual(key.e, self.e) + self.assertEqual(key.d, self.d) + self.assertEqual(key.p, self.p) + self.assertEqual(key.q, self.q) + + + ### + def testExportKey1(self): + key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) + derKey = key.exportKey("DER") + self.assertEqual(derKey, self.rsaKeyDER) + + def testExportKey2(self): + key = self.rsa.construct([self.n, self.e]) + derKey = key.exportKey("DER") + self.assertEqual(derKey, self.rsaPublicKeyDER) + + def testExportKey3(self): + key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) + pemKey = key.exportKey("PEM") + self.assertEqual(pemKey, b(self.rsaKeyPEM)) + + def testExportKey4(self): + key = self.rsa.construct([self.n, self.e]) + pemKey = key.exportKey("PEM") + self.assertEqual(pemKey, b(self.rsaPublicKeyPEM)) + + def testExportKey5(self): + key = self.rsa.construct([self.n, self.e]) + openssh_1 = key.exportKey("OpenSSH").split() + openssh_2 = self.rsaPublicKeyOpenSSH.split() + self.assertEqual(openssh_1[0], openssh_2[0]) + self.assertEqual(openssh_1[1], openssh_2[1]) + + 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]) + # 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]) + self.assertEqual(pemKey, t[1]) + + def testExportKey5(self): + key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) + derKey = key.exportKey("DER", pkcs=8) + self.assertEqual(derKey, self.rsaKeyDER8) + + def testExportKey6(self): + key = self.rsa.construct([self.n, self.e, self.d, self.p, self.q, self.pInv]) + pemKey = key.exportKey("PEM", pkcs=8) + self.assertEqual(pemKey, b(self.rsaKeyPEM8)) class ImportKeyTestsSlow(ImportKeyTests): def setUp(self): diff --git a/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py b/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py index 7fae57c..c4e6ccf 100644 --- a/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py +++ b/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaAccumulator.py @@ -26,7 +26,10 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * import unittest from binascii import b2a_hex @@ -42,24 +45,24 @@ class FortunaAccumulatorTests(unittest.TestCase): self.assertEqual(0, pool.length) self.assertEqual("5df6e0e2761359d30a8275058e299fcc0381534545f55cf43e41983f5d4c9456", pool.hexdigest()) - pool.append("abc") + pool.append(b('abc')) self.assertEqual(3, pool.length) self.assertEqual("4f8b42c22dd3729b519ba6f68d2da7cc5b2d606d05daed5ad5128cc03e6c6358", pool.hexdigest()) - pool.append("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") + pool.append(b("dbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")) self.assertEqual(56, pool.length) - self.assertEqual("0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af", b2a_hex(pool.digest())) + self.assertEqual(b('0cffe17f68954dac3a84fb1458bd5ec99209449749b2b308b7cb55812f9563af'), b2a_hex(pool.digest())) pool.reset() self.assertEqual(0, pool.length) - pool.append("a" * 10**6) + pool.append(b('a') * 10**6) self.assertEqual(10**6, pool.length) - self.assertEqual("80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688", b2a_hex(pool.digest())) + self.assertEqual(b('80d1189477563e1b5206b2749f1afe4807e5705e8bd77887a60187a712156688'), b2a_hex(pool.digest())) def test_which_pools(self): """FortunaAccumulator.which_pools""" @@ -98,7 +101,7 @@ class FortunaAccumulatorTests(unittest.TestCase): # Spread some test data across the pools (source number 42) # This would be horribly insecure in a real system. for p in range(32): - fa.add_random_event(42, p, "X" * 32) + fa.add_random_event(42, p, b("X") * 32) self.assertEqual(32+2, fa.pools[p].length) # This should still fail, because we haven't seeded the PRNG with 64 bytes yet @@ -106,7 +109,7 @@ class FortunaAccumulatorTests(unittest.TestCase): # Add more data for p in range(32): - fa.add_random_event(42, p, "X" * 32) + fa.add_random_event(42, p, b("X") * 32) self.assertEqual((32+2)*2, fa.pools[p].length) # The underlying RandomGenerator should get seeded with Pool 0 @@ -146,8 +149,8 @@ class FortunaAccumulatorTests(unittest.TestCase): result = fa.random_data(32) - self.assertEqual("b7b86bd9a27d96d7bb4add1b6b10d157" "2350b1c61253db2f8da233be726dc15f", b2a_hex(result)) - self.assertEqual("f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c", b2a_hex(fa.generator.key)) + self.assertEqual(b("b7b86bd9a27d96d7bb4add1b6b10d157" "2350b1c61253db2f8da233be726dc15f"), b2a_hex(result)) + self.assertEqual(b("f23ad749f33066ff53d307914fbf5b21da9667c7e86ba247655c9490e9d94a7c"), b2a_hex(fa.generator.key)) self.assertEqual(5, fa.generator.counter.next_value()) def test_accumulator_pool_length(self): @@ -164,13 +167,13 @@ class FortunaAccumulatorTests(unittest.TestCase): for i in range(15): for p in range(32): # Add the bytes to the pool - fa.add_random_event(2, p, "XX") + fa.add_random_event(2, p, b("XX")) # The PRNG should not allow us to get random data from it yet self.assertRaises(AssertionError, fa.random_data, 1) # Add 4 more bytes to pool 0 - fa.add_random_event(2, 0, "XX") + fa.add_random_event(2, 0, b("XX")) # We should now be able to get data from the accumulator fa.random_data(1) diff --git a/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaGenerator.py b/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaGenerator.py index fed314a..d41bb02 100644 --- a/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaGenerator.py +++ b/lib/Crypto/SelfTest/Random/Fortuna/test_FortunaGenerator.py @@ -26,7 +26,10 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * import unittest from binascii import b2a_hex @@ -45,24 +48,24 @@ class FortunaGeneratorTests(unittest.TestCase): self.assertEqual(0, fg.counter.next_value()) # Seed the generator, which should set the key and increment the counter. - fg.reseed("Hello") - self.assertEqual("0ea6919d4361551364242a4ba890f8f073676e82cf1a52bb880f7e496648b565", b2a_hex(fg.key)) + fg.reseed(b("Hello")) + self.assertEqual(b("0ea6919d4361551364242a4ba890f8f073676e82cf1a52bb880f7e496648b565"), b2a_hex(fg.key)) self.assertEqual(1, fg.counter.next_value()) # Read 2 full blocks from the generator - self.assertEqual("7cbe2c17684ac223d08969ee8b565616" + # counter=1 - "717661c0d2f4758bd6ba140bf3791abd", # counter=2 + self.assertEqual(b("7cbe2c17684ac223d08969ee8b565616") + # counter=1 + b("717661c0d2f4758bd6ba140bf3791abd"), # counter=2 b2a_hex(fg.pseudo_random_data(32))) # Meanwhile, the generator will have re-keyed itself and incremented its counter - self.assertEqual("33a1bb21987859caf2bbfc5615bef56d" + # counter=3 - "e6b71ff9f37112d0c193a135160862b7", # counter=4 + self.assertEqual(b("33a1bb21987859caf2bbfc5615bef56d") + # counter=3 + b("e6b71ff9f37112d0c193a135160862b7"), # counter=4 b2a_hex(fg.key)) self.assertEqual(5, fg.counter.next_value()) # Read another 2 blocks from the generator - self.assertEqual("fd6648ba3086e919cee34904ef09a7ff" + # counter=5 - "021f77580558b8c3e9248275f23042bf", # counter=6 + self.assertEqual(b("fd6648ba3086e919cee34904ef09a7ff") + # counter=5 + b("021f77580558b8c3e9248275f23042bf"), # counter=6 b2a_hex(fg.pseudo_random_data(32))) diff --git a/lib/Crypto/SelfTest/Random/Fortuna/test_SHAd256.py b/lib/Crypto/SelfTest/Random/Fortuna/test_SHAd256.py index a4a5ea9..f94db8a 100644 --- a/lib/Crypto/SelfTest/Random/Fortuna/test_SHAd256.py +++ b/lib/Crypto/SelfTest/Random/Fortuna/test_SHAd256.py @@ -25,6 +25,7 @@ """Self-test suite for Crypto.Random.Fortuna.SHAd256""" __revision__ = "$Id$" +from Crypto.Util.py3compat import * # This is a list of (expected_result, input[, description]) tuples. test_data = [ diff --git a/lib/Crypto/SelfTest/Random/test_random.py b/lib/Crypto/SelfTest/Random/test_random.py index 39aaf42..f9ffc66 100644 --- a/lib/Crypto/SelfTest/Random/test_random.py +++ b/lib/Crypto/SelfTest/Random/test_random.py @@ -27,6 +27,10 @@ __revision__ = "$Id$" import unittest +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * class SimpleTest(unittest.TestCase): def runTest(self): @@ -40,6 +44,122 @@ class SimpleTest(unittest.TestCase): z = Random.get_random_bytes(16) self.assertNotEqual(x, z) self.assertNotEqual(y, z) + # Test the Random.random module, which + # implements a subset of Python's random API + # Not implemented: + # seed(), getstate(), setstate(), jumpahead() + # random(), uniform(), triangular(), betavariate() + # expovariate(), gammavariate(), gauss(), + # longnormvariate(), normalvariate(), + # vonmisesvariate(), paretovariate() + # weibullvariate() + # WichmannHill(), whseed(), SystemRandom() + from Crypto.Random import random + x = random.getrandbits(16*8) + y = random.getrandbits(16*8) + self.assertNotEqual(x, y) + # Test randrange + if x>y: + start = y + stop = x + else: + start = x + stop = y + for step in range(1,10): + x = random.randrange(start,stop,step) + y = random.randrange(start,stop,step) + self.assertNotEqual(x, y) + self.assertEqual(start <= x < stop, True) + self.assertEqual(start <= y < stop, True) + self.assertEqual((x - start) % step, 0) + self.assertEqual((y - start) % step, 0) + for i in range(10): + self.assertEqual(random.randrange(1,2), 1) + self.assertRaises(ValueError, random.randrange, start, start) + self.assertRaises(ValueError, random.randrange, stop, start, step) + self.assertRaises(TypeError, random.randrange, start, stop, step, step) + self.assertRaises(TypeError, random.randrange, start, stop, "1") + self.assertRaises(TypeError, random.randrange, "1", stop, step) + self.assertRaises(TypeError, random.randrange, 1, "2", step) + self.assertRaises(ValueError, random.randrange, start, stop, 0) + # Test randint + x = random.randint(start,stop) + y = random.randint(start,stop) + self.assertNotEqual(x, y) + self.assertEqual(start <= x <= stop, True) + self.assertEqual(start <= y <= stop, True) + for i in range(10): + self.assertEqual(random.randint(1,1), 1) + self.assertRaises(ValueError, random.randint, stop, start) + self.assertRaises(TypeError, random.randint, start, stop, step) + self.assertRaises(TypeError, random.randint, "1", stop) + self.assertRaises(TypeError, random.randint, 1, "2") + # Test choice + seq = range(10000) + x = random.choice(seq) + y = random.choice(seq) + self.assertNotEqual(x, y) + self.assertEqual(x in seq, True) + self.assertEqual(y in seq, True) + for i in range(10): + self.assertEqual(random.choice((1,2,3)) in (1,2,3), True) + self.assertEqual(random.choice([1,2,3]) in [1,2,3], True) + if sys.version_info[0] is 3: + self.assertEqual(random.choice(bytearray(b('123'))) in bytearray(b('123')), True) + self.assertEqual(1, random.choice([1])) + self.assertRaises(IndexError, random.choice, []) + self.assertRaises(TypeError, random.choice, 1) + # Test shuffle. Lacks random parameter to specify function. + # Make copies of seq + seq = range(500) + x = list(seq) + y = list(seq) + random.shuffle(x) + random.shuffle(y) + self.assertNotEqual(x, y) + self.assertEqual(len(seq), len(x)) + self.assertEqual(len(seq), len(y)) + for i in range(len(seq)): + self.assertEqual(x[i] in seq, True) + self.assertEqual(y[i] in seq, True) + self.assertEqual(seq[i] in x, True) + self.assertEqual(seq[i] in y, True) + z = [1] + random.shuffle(z) + self.assertEqual(z, [1]) + if sys.version_info[0] == 3: + z = bytearray(b('12')) + random.shuffle(z) + self.assertEqual(b('1') in z, True) + self.assertRaises(TypeError, random.shuffle, b('12')) + self.assertRaises(TypeError, random.shuffle, 1) + self.assertRaises(TypeError, random.shuffle, "1") + self.assertRaises(TypeError, random.shuffle, (1,2)) + # 2to3 wraps a list() around it, alas - but I want to shoot + # myself in the foot here! :D + # if sys.version_info[0] == 3: + # self.assertRaises(TypeError, random.shuffle, range(3)) + # Test sample + x = random.sample(seq, 20) + y = random.sample(seq, 20) + self.assertNotEqual(x, y) + for i in range(20): + self.assertEqual(x[i] in seq, True) + self.assertEqual(y[i] in seq, True) + z = random.sample([1], 1) + self.assertEqual(z, [1]) + z = random.sample((1,2,3), 1) + 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) + self.assertEqual(z[0] in range(3), True) + if sys.version_info[0] == 3: + z = random.sample(b("123"), 1) + self.assertEqual(z[0] in b("123"), True) + z = random.sample(bytearray(b("123")), 1) + self.assertEqual(z[0] in bytearray(b("123")), True) + self.assertRaises(TypeError, random.sample, 1) def get_tests(config={}): return [SimpleTest()] diff --git a/lib/Crypto/SelfTest/Signature/test_pkcs1_15.py b/lib/Crypto/SelfTest/Signature/test_pkcs1_15.py index ce5ad75..bc36696 100644 --- a/lib/Crypto/SelfTest/Signature/test_pkcs1_15.py +++ b/lib/Crypto/SelfTest/Signature/test_pkcs1_15.py @@ -29,8 +29,7 @@ from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex from Crypto.Hash import * from Crypto import Random from Crypto.Signature import PKCS1_v1_5 as PKCS - -from string import maketrans +from Crypto.Util.py3compat import * def isStr(s): t = '' @@ -42,11 +41,13 @@ def isStr(s): def rws(t): """Remove white spaces, tabs, and new lines from a string""" - return t.translate(maketrans("",""),'\n\t ') + for c in ['\n', '\t', ' ']: + t = t.replace(c,'') + return t def t2b(t): """Convert a text string with bytes in hex form to a byte string""" - clean = rws(t) + clean = b(rws(t)) if len(clean)%2 == 1: raise ValueError("Even number of characters expected") return a2b_hex(clean) @@ -152,42 +153,44 @@ class PKCS1_15_Tests(unittest.TestCase): def testSign1(self): for i in range(len(self._testData)): + row = self._testData[i] # Build the key - if isStr(self._testData[i][0]): - key = RSA.importKey(self._testData[i][0]) + if isStr(row[0]): + key = RSA.importKey(row[0]) else: - comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e','d') ] + comps = [ long(rws(row[0][x]),16) for x in ('n','e','d') ] key = RSA.construct(comps) - h = self._testData[i][3].new() + h = row[3].new() # Data to sign can either be in hex form or not try: - h.update(t2b(self._testData[i][1])) + h.update(t2b(row[1])) except: - h.update(self._testData[i][1]) + h.update(b(row[1])) # The real test signer = PKCS.new(key) self.failUnless(signer.can_sign()) s = signer.sign(h) - self.assertEqual(s, t2b(self._testData[i][2])) + self.assertEqual(s, t2b(row[2])) def testVerify1(self): for i in range(len(self._testData)): + row = self._testData[i] # Build the key - if isStr(self._testData[i][0]): - key = RSA.importKey(self._testData[i][0]).publickey() + if isStr(row[0]): + key = RSA.importKey(row[0]).publickey() else: - comps = [ long(rws(self._testData[i][0][x]),16) for x in ('n','e') ] + comps = [ long(rws(row[0][x]),16) for x in ('n','e') ] key = RSA.construct(comps) - h = self._testData[i][3].new() + h = row[3].new() # Data to sign can either be in hex form or not try: - h.update(t2b(self._testData[i][1])) + h.update(t2b(row[1])) except: - h.update(self._testData[i][1]) + h.update(b(row[1])) # The real test verifier = PKCS.new(key) self.failIf(verifier.can_sign()) - result = verifier.verify(h, t2b(self._testData[i][2])) + result = verifier.verify(h, t2b(row[2])) self.failUnless(result) def testSignVerify(self): @@ -196,7 +199,7 @@ class PKCS1_15_Tests(unittest.TestCase): for hashmod in (MD2,MD5,SHA,SHA224,SHA256,SHA384,SHA512,RIPEMD): h = hashmod.new() - h.update('blah blah blah') + h.update(b('blah blah blah')) signer = PKCS.new(key) s = signer.sign(h) diff --git a/lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py b/lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py index 42e5a06..f5256a5 100644 --- a/lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py +++ b/lib/Crypto/SelfTest/Signature/test_pkcs1_pss.py @@ -31,8 +31,7 @@ from Crypto import Random from Crypto.SelfTest.st_common import list_test_cases, a2b_hex, b2a_hex from Crypto.Hash import * from Crypto.Signature import PKCS1_PSS as PKCS - -from string import maketrans +from Crypto.Util.py3compat import * def isStr(s): t = '' @@ -44,11 +43,13 @@ def isStr(s): def rws(t): """Remove white spaces, tabs, and new lines from a string""" - return t.translate(maketrans("",""),'\n\t ') + for c in ['\t', '\n', ' ']: + t = t.replace(c,'') + return t def t2b(t): """Convert a text string with bytes in hex form to a byte string""" - clean = rws(t) + clean = b(rws(t)) if len(clean)%2 == 1: raise ValueError("Even number of characters expected") return a2b_hex(clean) @@ -380,7 +381,7 @@ class PKCS1_PSS_Tests(unittest.TestCase): def testSignVerify(self): h = SHA.new() - h.update('blah blah blah') + h.update(b('blah blah blah')) rng = Random.new().read key = MyKey(RSA.generate(1024,rng)) @@ -390,12 +391,12 @@ class PKCS1_PSS_Tests(unittest.TestCase): def newMGF(seed,maskLen): global mgfcalls mgfcalls += 1 - return '\x00'*maskLen + return bchr(0x00)*maskLen # Verify that PSS is friendly to all ciphers for hashmod in (MD2,MD5,SHA,SHA224,SHA256,SHA384,RIPEMD): h = hashmod.new() - h.update('blah blah blah') + h.update(b('blah blah blah')) # Verify that sign() asks for as many random bytes # as the hash output size @@ -406,7 +407,7 @@ class PKCS1_PSS_Tests(unittest.TestCase): self.assertEqual(key.asked, h.digest_size) h = SHA.new() - h.update('blah blah blah') + h.update(b('blah blah blah')) # Verify that sign() uses a different salt length for sLen in (0,3,21): diff --git a/lib/Crypto/SelfTest/Util/test_Counter.py b/lib/Crypto/SelfTest/Util/test_Counter.py index 0ccf2d4..33c9bd7 100644 --- a/lib/Crypto/SelfTest/Util/test_Counter.py +++ b/lib/Crypto/SelfTest/Util/test_Counter.py @@ -26,7 +26,10 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * import unittest @@ -38,20 +41,20 @@ class CounterTests(unittest.TestCase): def test_BE_shortcut(self): """Big endian, shortcut enabled""" c = Counter.new(128) - self.assert_(c.__PCT_CTR_SHORTCUT__) + self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_ c = Counter.new(128, little_endian=False) - self.assert_(c.__PCT_CTR_SHORTCUT__) + self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_ c = Counter.new(128, disable_shortcut=False) - self.assert_(c.__PCT_CTR_SHORTCUT__) + self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_ c = Counter.new(128, little_endian=False, disable_shortcut=False) - self.assert_(c.__PCT_CTR_SHORTCUT__) + self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_ def test_LE_shortcut(self): """Little endian, shortcut enabled""" c = Counter.new(128, little_endian=True) - self.assert_(c.__PCT_CTR_SHORTCUT__) + self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_ c = Counter.new(128, little_endian=True, disable_shortcut=False) - self.assert_(c.__PCT_CTR_SHORTCUT__) + self.assertEqual(c.__PCT_CTR_SHORTCUT__,True) # assert_ def test_BE_no_shortcut(self): """Big endian, shortcut disabled""" @@ -69,34 +72,34 @@ class CounterTests(unittest.TestCase): """128-bit, Big endian, defaults""" c = Counter.new(128) self.assertEqual(1, c.next_value()) - self.assertEqual("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01", c()) + 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("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02", c()) + 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): self.assertEqual(i, c.next_value()) - self.assertEqual("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"+chr(i), c()) + 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()) - self.assertEqual("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00", c()) + self.assertEqual(b("\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00"), c()) def test_LE_defaults(self): """128-bit, Little endian, defaults""" c = Counter.new(128, little_endian=True) self.assertEqual(1, c.next_value()) - self.assertEqual("\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", c()) + 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("\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", c()) + 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): self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i)+"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", c()) + 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()) - self.assertEqual("\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", c()) + self.assertEqual(b("\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), c()) def test_BE8_wraparound(self): """8-bit, Big endian, wraparound""" c = Counter.new(8) for i in xrange(1, 256): self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i), c()) + self.assertEqual(bchr(i), c()) self.assertRaises(OverflowError, c.next_value) self.assertRaises(OverflowError, c) self.assertRaises(OverflowError, c.next_value) @@ -107,7 +110,7 @@ class CounterTests(unittest.TestCase): c = Counter.new(8, little_endian=True) for i in xrange(1, 256): self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i), c()) + self.assertEqual(bchr(i), c()) self.assertRaises(OverflowError, c.next_value) self.assertRaises(OverflowError, c) self.assertRaises(OverflowError, c.next_value) @@ -118,9 +121,9 @@ class CounterTests(unittest.TestCase): c = Counter.new(8, allow_wraparound=True) for i in xrange(1, 256): self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i), c()) + self.assertEqual(bchr(i), c()) self.assertEqual(0, c.next_value()) - self.assertEqual("\x00", c()) + self.assertEqual(b("\x00"), c()) self.assertEqual(1, c.next_value()) def test_LE8_wraparound_allowed(self): @@ -128,9 +131,9 @@ class CounterTests(unittest.TestCase): c = Counter.new(8, little_endian=True, allow_wraparound=True) for i in xrange(1, 256): self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i), c()) + self.assertEqual(bchr(i), c()) self.assertEqual(0, c.next_value()) - self.assertEqual("\x00", c()) + self.assertEqual(b("\x00"), c()) self.assertEqual(1, c.next_value()) def test_BE8_carry(self): @@ -139,7 +142,7 @@ class CounterTests(unittest.TestCase): for i in xrange(1, 256): self.assertEqual(0, c.carry) self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i), c()) + self.assertEqual(bchr(i), c()) self.assertEqual(1, c.carry) def test_LE8_carry(self): @@ -148,7 +151,7 @@ class CounterTests(unittest.TestCase): for i in xrange(1, 256): self.assertEqual(0, c.carry) self.assertEqual(i, c.next_value()) - self.assertEqual(chr(i), c()) + self.assertEqual(bchr(i), c()) self.assertEqual(1, c.carry) def get_tests(config={}): diff --git a/lib/Crypto/SelfTest/Util/test_asn1.py b/lib/Crypto/SelfTest/Util/test_asn1.py index 7ba0beb..2166d11 100644 --- a/lib/Crypto/SelfTest/Util/test_asn1.py +++ b/lib/Crypto/SelfTest/Util/test_asn1.py @@ -27,121 +27,122 @@ __revision__ = "$Id$" import unittest import sys +from Crypto.Util.py3compat import * from Crypto.Util.asn1 import DerSequence, DerObject class DerObjectTests(unittest.TestCase): def testObjEncode1(self): # No payload - der = DerObject('\x33') - self.assertEquals(der.encode(), '\x33\x00') + der = DerObject(b('\x33')) + self.assertEquals(der.encode(), b('\x33\x00')) # Small payload - der.payload = '\x45' - self.assertEquals(der.encode(), '\x33\x01\x45') + der.payload = b('\x45') + self.assertEquals(der.encode(), b('\x33\x01\x45')) # Invariant - self.assertEquals(der.encode(), '\x33\x01\x45') + self.assertEquals(der.encode(), b('\x33\x01\x45')) def testObjEncode2(self): # Known types der = DerObject('SEQUENCE') - self.assertEquals(der.encode(), '\x30\x00') + self.assertEquals(der.encode(), b('\x30\x00')) der = DerObject('BIT STRING') - self.assertEquals(der.encode(), '\x03\x00') + self.assertEquals(der.encode(), b('\x03\x00')) def testObjEncode3(self): # Long payload - der = DerObject('\x34') - der.payload = "0"*128 - self.assertEquals(der.encode(), '\x34\x81\x80' + ("0"*128)) + der = DerObject(b('\x34')) + der.payload = b("0")*128 + self.assertEquals(der.encode(), b('\x34\x81\x80' + "0"*128)) def testObjDecode1(self): # Decode short payload der = DerObject() - der.decode('\x20\x02\x01\x02') - self.assertEquals(der.payload, "\x01\x02") - self.assertEquals(der.typeTag, "\x20") + der.decode(b('\x20\x02\x01\x02')) + self.assertEquals(der.payload, b("\x01\x02")) + self.assertEquals(der.typeTag, 0x20) def testObjDecode2(self): # Decode short payload der = DerObject() - der.decode('\x22\x81\x80' + ("1"*128)) - self.assertEquals(der.payload, "1"*128) - self.assertEquals(der.typeTag, "\x22") + der.decode(b('\x22\x81\x80' + "1"*128)) + self.assertEquals(der.payload, b("1")*128) + self.assertEquals(der.typeTag, 0x22) class DerSequenceTests(unittest.TestCase): def testEncode1(self): # Empty sequence der = DerSequence() - self.assertEquals(der.encode(), '0\x00') + self.assertEquals(der.encode(), b('0\x00')) self.failIf(der.hasOnlyInts()) # One single-byte integer (zero) der.append(0) - self.assertEquals(der.encode(), '0\x03\x02\x01\x00') + self.assertEquals(der.encode(), b('0\x03\x02\x01\x00')) self.failUnless(der.hasOnlyInts()) # Invariant - self.assertEquals(der.encode(), '0\x03\x02\x01\x00') + self.assertEquals(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(), '0\x03\x02\x01\x7f') + self.assertEquals(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(), '0\x03\x02\x01\x01') + self.assertEquals(der.encode(), b('0\x03\x02\x01\x01')) # der[:] = [1] self.assertEquals(len(der),1) self.assertEquals(der[0],1) - self.assertEquals(der.encode(), '0\x03\x02\x01\x01') + self.assertEquals(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(), '0\x04\x02\x02\x01\x80') + self.assertEquals(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(), '0\x82\x01\x05' - '\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00') + self.assertEquals(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')+ + 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\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')+ + 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\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')+ + 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\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')+ + b('\x00\x00\x00\x00\x00\x00\x00\x00\x00')) def testEncode5(self): # One single-byte integer (looks negative) der = DerSequence() der.append(0xFFL) - self.assertEquals(der.encode(), '0\x04\x02\x02\x00\xff') + self.assertEquals(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(), '0\x08\x02\x02\x01\x80\x02\x02\x00\xff') + self.assertEquals(der.encode(), b('0\x08\x02\x02\x01\x80\x02\x02\x00\xff')) self.failUnless(der.hasOnlyInts()) # der.append(0x01) @@ -149,14 +150,14 @@ class DerSequenceTests(unittest.TestCase): self.assertEquals(len(der),3) self.assertEqual(der[1:],[9,8]) self.assertEqual(der[1:-1],[9]) - self.assertEquals(der.encode(), '0\x0A\x02\x02\x01\x80\x02\x01\x09\x02\x01\x08') + self.assertEquals(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('\x00\x02\x00\x00') - self.assertEquals(der.encode(), '0\x08\x02\x02\x01\x80\x00\x02\x00\x00') + 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()) #### @@ -164,68 +165,68 @@ class DerSequenceTests(unittest.TestCase): def testDecode1(self): # Empty sequence der = DerSequence() - der.decode('0\x00') + der.decode(b('0\x00')) self.assertEquals(len(der),0) # One single-byte integer (zero) - der.decode('0\x03\x02\x01\x00') + der.decode(b('0\x03\x02\x01\x00')) self.assertEquals(len(der),1) self.assertEquals(der[0],0) # Invariant - der.decode('0\x03\x02\x01\x00') + der.decode(b('0\x03\x02\x01\x00')) self.assertEquals(len(der),1) self.assertEquals(der[0],0) def testDecode2(self): # One single-byte integer (non-zero) der = DerSequence() - der.decode('0\x03\x02\x01\x7f') + der.decode(b('0\x03\x02\x01\x7f')) self.assertEquals(len(der),1) self.assertEquals(der[0],127) def testDecode3(self): # One multi-byte integer (non-zero) der = DerSequence() - der.decode('0\x04\x02\x02\x01\x80') + der.decode(b('0\x04\x02\x02\x01\x80')) self.assertEquals(len(der),1) self.assertEquals(der[0],0x180L) def testDecode4(self): # One very long integer der = DerSequence() - der.decode('0\x82\x01\x05' - '\x02\x82\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' - '\x00\x00\x00\x00\x00\x00\x00\x00\x00') + der.decode(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')+ + 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\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')+ + 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\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')+ + 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\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')+ + b('\x00\x00\x00\x00\x00\x00\x00\x00\x00')) self.assertEquals(len(der),1) self.assertEquals(der[0],2**2048) def testDecode5(self): # One single-byte integer (looks negative) der = DerSequence() - der.decode('0\x04\x02\x02\x00\xff') + der.decode(b('0\x04\x02\x02\x00\xff')) self.assertEquals(len(der),1) self.assertEquals(der[0],0xFFL) def testDecode6(self): # Two integers der = DerSequence() - der.decode('0\x08\x02\x02\x01\x80\x02\x02\x00\xff') + 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) @@ -233,38 +234,38 @@ class DerSequenceTests(unittest.TestCase): def testDecode7(self): # One integer and 2 other types der = DerSequence() - der.decode('0\x0A\x02\x02\x01\x80\x24\x02\xb6\x63\x12\x00') + 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],'\x24\x02\xb6\x63') - self.assertEquals(der[2],'\x12\x00') + self.assertEquals(der[1],b('\x24\x02\xb6\x63')) + self.assertEquals(der[2],b('\x12\x00')) def testDecode8(self): # Only 2 other types der = DerSequence() - der.decode('0\x06\x24\x02\xb6\x63\x12\x00') + der.decode(b('0\x06\x24\x02\xb6\x63\x12\x00')) self.assertEquals(len(der),2) - self.assertEquals(der[0],'\x24\x02\xb6\x63') - self.assertEquals(der[1],'\x12\x00') + self.assertEquals(der[0],b('\x24\x02\xb6\x63')) + self.assertEquals(der[1],b('\x12\x00')) def testErrDecode1(self): # Not a sequence der = DerSequence() - self.assertRaises(ValueError, der.decode, '') - self.assertRaises(ValueError, der.decode, '\x00') - self.assertRaises(ValueError, der.decode, '\x30') + self.assertRaises(ValueError, der.decode, b('')) + self.assertRaises(ValueError, der.decode, b('\x00')) + self.assertRaises(ValueError, der.decode, b('\x30')) def testErrDecode2(self): # Wrong payload type der = DerSequence() - self.assertRaises(ValueError, der.decode, '\x30\x00\x00', True) + self.assertRaises(ValueError, der.decode, b('\x30\x00\x00'), True) def testErrDecode3(self): # Wrong length format der = DerSequence() - self.assertRaises(ValueError, der.decode, '\x30\x04\x02\x01\x01\x00') - self.assertRaises(ValueError, der.decode, '\x30\x81\x03\x02\x01\x01') - self.assertRaises(ValueError, der.decode, '\x30\x04\x02\x81\x01\x01') + self.assertRaises(ValueError, der.decode, b('\x30\x04\x02\x01\x01\x00')) + self.assertRaises(ValueError, der.decode, b('\x30\x81\x03\x02\x01\x01')) + self.assertRaises(ValueError, der.decode, b('\x30\x04\x02\x81\x01\x01')) def testErrDecode4(self): # Wrong integer format @@ -272,7 +273,7 @@ class DerSequenceTests(unittest.TestCase): # Multi-byte encoding for zero #self.assertRaises(ValueError, der.decode, '\x30\x04\x02\x02\x00\x00') # Negative integer - self.assertRaises(ValueError, der.decode, '\x30\x04\x02\x01\xFF') + self.assertRaises(ValueError, der.decode, b('\x30\x04\x02\x01\xFF')) def get_tests(config={}): from Crypto.SelfTest.st_common import list_test_cases @@ -286,5 +287,3 @@ if __name__ == '__main__': unittest.main(defaultTest='suite') # vim:set ts=4 sw=4 sts=4 expandtab: - - diff --git a/lib/Crypto/SelfTest/Util/test_number.py b/lib/Crypto/SelfTest/Util/test_number.py index e135e9d..7a74e3a 100644 --- a/lib/Crypto/SelfTest/Util/test_number.py +++ b/lib/Crypto/SelfTest/Util/test_number.py @@ -26,7 +26,9 @@ __revision__ = "$Id$" -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * import unittest diff --git a/lib/Crypto/SelfTest/st_common.py b/lib/Crypto/SelfTest/st_common.py index 7689c98..c56eac5 100644 --- a/lib/Crypto/SelfTest/st_common.py +++ b/lib/Crypto/SelfTest/st_common.py @@ -27,8 +27,11 @@ __revision__ = "$Id$" import unittest -import string import binascii +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * class _list_testloader(unittest.TestLoader): suiteClass = list @@ -41,10 +44,11 @@ def list_test_cases(class_): return _list_testloader().loadTestsFromTestCase(class_) def strip_whitespace(s): - """Remove whitespace from a string""" - table = string.maketrans(string.whitespace, " " * len(string.whitespace)) - s = s.translate(table).replace(" ", "") - return s + """Remove whitespace from a text or byte string""" + if isinstance(s,str): + return b("".join(s.split())) + else: + return b("").join(s.split()) def a2b_hex(s): """Convert hexadecimal to binary, ignoring whitespace""" diff --git a/lib/Crypto/Signature/PKCS1_PSS.py b/lib/Crypto/Signature/PKCS1_PSS.py index 31c10b2..248884e 100644 --- a/lib/Crypto/Signature/PKCS1_PSS.py +++ b/lib/Crypto/Signature/PKCS1_PSS.py @@ -66,6 +66,7 @@ from __future__ import nested_scopes __revision__ = "$Id$" __all__ = [ 'new' ] +from Crypto.Util.py3compat import * import Crypto.Util.number from Crypto.Util.number import ceil_shift, ceil_div, long_to_bytes from Crypto.Util.strxor import strxor @@ -139,7 +140,7 @@ class PSS_SigScheme: # Step 2a (OS2IP) and 2b (RSASP1) m = self._key.decrypt(em) # Step 2c (I2OSP) - S = '\x00'*(k-len(m)) + m + S = bchr(0x00)*(k-len(m)) + m return S def verify(self, mhash, S): @@ -186,7 +187,7 @@ class PSS_SigScheme: em = self._key.encrypt(S, 0)[0] # Step 2c emLen = ceil_div(modBits-1,8) - em = '\x00'*(emLen-len(em)) + em + em = bchr(0x00)*(emLen-len(em)) + em # Step 3 try: result = EMSA_PSS_VERIFY(mhash, em, modBits-1, mgf, sLen) @@ -197,7 +198,7 @@ class PSS_SigScheme: def MGF1(mgfSeed, maskLen, hash): """Mask Generation Function, described in B.2.1""" - T = "" + T = b("") for counter in xrange(ceil_div(maskLen, hash.digest_size)): c = long_to_bytes(counter, 4) T = T + hash.new(mgfSeed + c).digest() @@ -246,21 +247,21 @@ def EMSA_PSS_ENCODE(mhash, emBits, randFunc, mgf, sLen): if emLen < mhash.digest_size+sLen+2: raise ValueError("Digest or salt length are too long for given key size.") # Step 4 - salt = "" + salt = b("") if randFunc and sLen>0: salt = randFunc(sLen) # Step 5 and 6 - h = mhash.new('\x00'*8 + mhash.digest() + salt) + h = mhash.new(bchr(0x00)*8 + mhash.digest() + salt) # Step 7 and 8 - db = '\x00'*(emLen-sLen-mhash.digest_size-2) + '\x01' + salt + db = bchr(0x00)*(emLen-sLen-mhash.digest_size-2) + bchr(0x01) + salt # Step 9 dbMask = mgf(h.digest(), emLen-mhash.digest_size-1) # Step 10 maskedDB = strxor(db,dbMask) # Step 11 - maskedDB = chr(ord(maskedDB[0]) & ~lmask) + maskedDB[1:] + maskedDB = bchr(bord(maskedDB[0]) & ~lmask) + maskedDB[1:] # Step 12 - em = maskedDB + h.digest() + '\xBC' + em = maskedDB + h.digest() + bchr(0xBC) return em def EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen): @@ -304,28 +305,28 @@ def EMSA_PSS_VERIFY(mhash, em, emBits, mgf, sLen): if emLen < mhash.digest_size+sLen+2: return 0 # Step 4 - if em[-1:]!='\xBC': + if ord(em[-1:])!=0xBC: return 0 # Step 5 maskedDB = em[:emLen-mhash.digest_size-1] h = em[emLen-mhash.digest_size-1:-1] # Step 6 - if lmask & ord(em[0]): + if lmask & bord(em[0]): return 0 # Step 7 dbMask = mgf(h, emLen-mhash.digest_size-1) # Step 8 db = strxor(maskedDB, dbMask) # Step 9 - db = chr(ord(db[0]) & ~lmask) + db[1:] + db = bchr(bord(db[0]) & ~lmask) + db[1:] # Step 10 - if not db.startswith('\x00'*(emLen-mhash.digest_size-sLen-2) + '\x01'): + if not db.startswith(bchr(0x00)*(emLen-mhash.digest_size-sLen-2) + bchr(0x01)): return 0 # Step 11 - salt = "" + salt = b("") if sLen: salt = db[-sLen:] # Step 12 and 13 - hp = mhash.new('\x00'*8 + mhash.digest() + salt).digest() + hp = mhash.new(bchr(0x00)*8 + mhash.digest() + salt).digest() # Step 14 if h!=hp: return 0 diff --git a/lib/Crypto/Signature/PKCS1_v1_5.py b/lib/Crypto/Signature/PKCS1_v1_5.py index b6e1cba..5490687 100644 --- a/lib/Crypto/Signature/PKCS1_v1_5.py +++ b/lib/Crypto/Signature/PKCS1_v1_5.py @@ -63,6 +63,7 @@ __all__ = [ 'new' ] import Crypto.Util.number from Crypto.Util.number import ceil_div from Crypto.Util.asn1 import DerSequence, DerNull, DerOctetString +from Crypto.Util.py3compat import * class PKCS115_SigScheme: """This signature scheme can perform PKCS#1 v1.5 RSA signature or verification.""" @@ -110,7 +111,7 @@ class PKCS115_SigScheme: # Step 2a (OS2IP) and 2b (RSASP1) m = self._key.decrypt(em) # Step 2c (I2OSP) - S = '\x00'*(k-len(m)) + m + S = bchr(0x00)*(k-len(m)) + m return S def verify(self, mhash, S): @@ -146,7 +147,7 @@ class PKCS115_SigScheme: # TODO: Fix RSA object; don't do it here. m = self._key.encrypt(S, 0)[0] # Step 2c (I2OSP) - em1 = '\x00'*(k-len(m)) + m + em1 = bchr(0x00)*(k-len(m)) + m # Step 3 try: em2 = EMSA_PKCS1_V1_5_ENCODE(mhash, k) @@ -218,8 +219,8 @@ def EMSA_PKCS1_V1_5_ENCODE(hash, emLen): # at least 8 bytes of padding). if emLen<len(digestInfo)+11: raise ValueError("Selected hash algorith has a too long digest (%d bytes)." % len(digest)) - PS = "\xFF" * (emLen - len(digestInfo) - 3) - return "\x00" + "\x01" + PS + "\x00" + digestInfo + PS = bchr(0xFF) * (emLen - len(digestInfo) - 3) + return b("\x00\x01") + PS + bchr(0x00) + digestInfo def new(key): """Return a signature scheme object `PKCS115_SigScheme` that diff --git a/lib/Crypto/Util/Counter.py b/lib/Crypto/Util/Counter.py index 42dab42..f00099b 100644 --- a/lib/Crypto/Util/Counter.py +++ b/lib/Crypto/Util/Counter.py @@ -22,13 +22,16 @@ # SOFTWARE. # =================================================================== -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * +from Crypto.Util.py3compat import * from Crypto.Util import _counter import struct # Factory function -def new(nbits, prefix="", suffix="", initial_value=1, overflow=0, little_endian=False, allow_wraparound=False, disable_shortcut=False): +def new(nbits, prefix=b(""), suffix=b(""), initial_value=1, overflow=0, little_endian=False, allow_wraparound=False, disable_shortcut=False): # TODO: Document this # Sanity-check the message size @@ -42,20 +45,21 @@ def new(nbits, prefix="", suffix="", initial_value=1, overflow=0, little_endian= raise ValueError("nbits too large") initval = _encode(initial_value, nbytes, little_endian) + if little_endian: - return _counter._newLE(str(prefix), str(suffix), initval, allow_wraparound=allow_wraparound, disable_shortcut=disable_shortcut) + return _counter._newLE(bstr(prefix), bstr(suffix), initval, allow_wraparound=allow_wraparound, disable_shortcut=disable_shortcut) else: - return _counter._newBE(str(prefix), str(suffix), initval, allow_wraparound=allow_wraparound, disable_shortcut=disable_shortcut) + return _counter._newBE(bstr(prefix), bstr(suffix), initval, allow_wraparound=allow_wraparound, disable_shortcut=disable_shortcut) def _encode(n, nbytes, little_endian=False): retval = [] n = long(n) for i in range(nbytes): if little_endian: - retval.append(chr(n & 0xff)) + retval.append(bchr(n & 0xff)) else: - retval.insert(0, chr(n & 0xff)) + retval.insert(0, bchr(n & 0xff)) n >>= 8 - return "".join(retval) + return b("").join(retval) # vim:set ts=4 sw=4 sts=4 expandtab: diff --git a/lib/Crypto/Util/RFC1751.py b/lib/Crypto/Util/RFC1751.py index 85e0e99..9786e6f 100644 --- a/lib/Crypto/Util/RFC1751.py +++ b/lib/Crypto/Util/RFC1751.py @@ -1,4 +1,3 @@ -#!/usr/local/bin/python # rfc1751.py : Converts between 128-bit strings and a human-readable # sequence of words, as defined in RFC1751: "A Convention for # Human-Readable 128-bit Keys", by Daniel L. McDonald. @@ -28,7 +27,8 @@ __revision__ = "$Id$" -import string, binascii +import binascii +from Crypto.Util.py3compat import * 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,18 +36,18 @@ binary={0:'0000', 1:'0001', 2:'0010', 3:'0011', 4:'0100', 5:'0101', def _key2bin(s): "Convert a key into a string of binary digits" - kl=map(lambda x: ord(x), s) + kl=map(lambda x: bord(x), s) kl=map(lambda x: binary[x>>4]+binary[x&15], kl) return ''.join(kl) def _extract(key, start, length): - """Extract a bitstring from a string of binary digits, and return its + """Extract a bitstring(2.x)/bytestring(2.x) from a string of binary digits, and return its numeric value.""" k=key[start:start+length] return reduce(lambda x,y: x*2+ord(y)-48, k, 0) def key_to_english (key): - """key_to_english(key:string) : string + """key_to_english(key:string(2.x)/bytes(3.x)) : string Transform an arbitrary key into a string containing English words. The key length must be a multiple of 8. """ @@ -58,20 +58,20 @@ def key_to_english (key): skbin=_key2bin(subkey) ; p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) # Append parity bits to the subkey - skbin=_key2bin(subkey+chr((p<<6) & 255)) + skbin=_key2bin(subkey+bchr((p<<6) & 255)) for i in range(0, 64, 11): english=english+wordlist[_extract(skbin, i, 11)]+' ' return english[:-1] # Remove the trailing space -def english_to_key (str): - """english_to_key(string):string +def english_to_key (s): + """english_to_key(string):string(2.x)/bytes(2.x) Transform a string into a corresponding key. The string must contain words separated by whitespace; the number of words must be a multiple of 6. """ - L=string.split(string.upper(str)) ; key='' + L=s.upper().split() ; key=b('') for index in range(0, len(L), 6): sublist=L[index:index+6] ; char=9*[0] ; bits=0 for i in sublist: @@ -88,7 +88,7 @@ def english_to_key (str): char[(bits>>3)+1] = char[(bits>>3)+1] | cr else: char[bits>>3] = char[bits>>3] | cr bits=bits+11 - subkey=reduce(lambda x,y:x+chr(y), char, '') + subkey=reduce(lambda x,y:x+bchr(y), char, b('')) # Check the parity of the resulting key skbin=_key2bin(subkey) diff --git a/lib/Crypto/Util/_number_new.py b/lib/Crypto/Util/_number_new.py index 2640392..b040025 100644 --- a/lib/Crypto/Util/_number_new.py +++ b/lib/Crypto/Util/_number_new.py @@ -27,7 +27,9 @@ __revision__ = "$Id$" __all__ = ['ceil_shift', 'ceil_div', 'floor_div', 'exact_log2', 'exact_div'] -from Crypto.Util.python_compat import * +import sys +if sys.version_info[0] == 2 and sys.version_info[1] == 1: + from Crypto.Util.py21compat import * def ceil_shift(n, b): """Return ceil(n / 2**b) without performing any floating-point or division operations. diff --git a/lib/Crypto/Util/asn1.py b/lib/Crypto/Util/asn1.py index f7658b4..e09b3ff 100644 --- a/lib/Crypto/Util/asn1.py +++ b/lib/Crypto/Util/asn1.py @@ -21,8 +21,10 @@ # =================================================================== from Crypto.Util.number import long_to_bytes, bytes_to_long +import sys +from Crypto.Util.py3compat import * -__all__ = [ 'DerObject', 'DerInteger', 'DerOctetString', 'DerNull', 'DerSequence' ] +__all__ = [ 'DerObject', 'DerInteger', 'DerOctetString', 'DerNull', 'DerSequence', 'DerObjectId' ] class DerObject: """Base class for defining a single DER object. @@ -31,35 +33,41 @@ class DerObject: """ # Known TAG types - typeTags = { 'SEQUENCE':'\x30', 'BIT STRING':'\x03', 'INTEGER':'\x02', - 'OCTET STRING':'\x04', 'NULL':'\x05', 'OBJECT IDENTIFIER':'\x06'} + typeTags = { 'SEQUENCE': 0x30, 'BIT STRING': 0x03, 'INTEGER': 0x02, + 'OCTET STRING': 0x04, 'NULL': 0x05, 'OBJECT IDENTIFIER': 0x06 } - def __init__(self, ASN1Type=None, payload=''): + def __init__(self, ASN1Type=None, payload=b('')): """Initialize the DER object according to a specific type. The ASN.1 type is either specified as the ASN.1 string (e.g. 'SEQUENCE'), directly with its numerical tag or with no tag - atl all (None).""" - self.typeTag = self.typeTags.get(ASN1Type, ASN1Type) + at all (None).""" + if isInt(ASN1Type) or ASN1Type is None: + self.typeTag = ASN1Type + else: + if len(ASN1Type)==1: + self.typeTag = ord(ASN1Type) + else: + self.typeTag = self.typeTags.get(ASN1Type) self.payload = payload def isType(self, ASN1Type): return self.typeTags[ASN1Type]==self.typeTag def _lengthOctets(self, payloadLen): - """Return a string that encodes the given payload length (in + """Return a byte string that encodes the given payload length (in bytes) in a format suitable for a DER length tag (L). """ if payloadLen>127: encoding = long_to_bytes(payloadLen) - return chr(len(encoding)+128) + encoding - return chr(payloadLen) + return bchr(len(encoding)+128) + encoding + return bchr(payloadLen) def encode(self): """Return a complete DER element, fully encoded as a TLV.""" - return self.typeTag + self._lengthOctets(len(self.payload)) + self.payload + return bchr(self.typeTag) + self._lengthOctets(len(self.payload)) + self.payload - def _decodeLen(self, idx, str): + def _decodeLen(self, idx, der): """Given a (part of a) DER element, and an index to the first byte of a DER length tag (L), return a tuple with the payload size, and the index of the first byte of the such payload (V). @@ -67,10 +75,10 @@ class DerObject: Raises a ValueError exception if the DER length is invalid. Raises an IndexError exception if the DER element is too short. """ - length = ord(str[idx]) + length = bord(der[idx]) if length<=127: return (length,idx+1) - payloadLength = bytes_to_long(str[idx+1:idx+1+(length & 0x7F)]) + payloadLength = bytes_to_long(der[idx+1:idx+1+(length & 0x7F)]) if payloadLength<=127: raise ValueError("Not a DER length tag.") return (payloadLength, idx+1+(length & 0x7F)) @@ -90,8 +98,8 @@ class DerObject: Raises an IndexError exception if the DER element is too short. """ try: - self.typeTag = derEle[0] - if (ord(self.typeTag) & 0x1F)==0x1F: + self.typeTag = bord(derEle[0]) + if (self.typeTag & 0x1F)==0x1F: raise ValueError("Unsupported DER tag") (length,idx) = self._decodeLen(1, derEle) if noLeftOvers and len(derEle) != (idx+length): @@ -113,8 +121,8 @@ class DerInteger(DerObject): def encode(self): """Return a complete INTEGER DER element, fully encoded as a TLV.""" self.payload = long_to_bytes(self.value) - if ord(self.payload[0])>127: - self.payload = '\x00' + self.payload + if bord(self.payload[0])>127: + self.payload = bchr(0x00) + self.payload return DerObject.encode(self) def decode(self, derEle, noLeftOvers=0): @@ -135,7 +143,7 @@ class DerInteger(DerObject): tlvLength = DerObject.decode(self, derEle, noLeftOvers) if self.typeTag!=self.typeTags['INTEGER']: raise ValueError ("Not a DER INTEGER.") - if ord(self.payload[0])>127: + if bord(self.payload[0])>127: raise ValueError ("Negative INTEGER.") self.value = bytes_to_long(self.payload) return tlvLength @@ -179,13 +187,6 @@ class DerSequence(DerObject): def hasInts(self): """Return the number of items in this sequence that are numbers.""" - def isInt(x): - test = 0 - try: - test += x - except TypeError: - return 0 - return 1 return len(filter(isInt, self._seq)) def hasOnlyInts(self): @@ -199,7 +200,7 @@ class DerSequence(DerObject): Limitation: Raises a ValueError exception if it some elements in the sequence are neither Python integers nor complete DER INTEGERs. """ - self.payload = '' + self.payload = b('') for item in self._seq: try: self.payload += item @@ -275,3 +276,11 @@ class DerObjectId(DerObject): raise ValueError("Not a valid OBJECT IDENTIFIER.") return p +def isInt(x): + test = 0 + try: + test += x + except TypeError: + return 0 + return 1 + diff --git a/lib/Crypto/Util/number.py b/lib/Crypto/Util/number.py index 7be595b..2b5beb6 100644 --- a/lib/Crypto/Util/number.py +++ b/lib/Crypto/Util/number.py @@ -26,15 +26,36 @@ __revision__ = "$Id$" -from Crypto.pct_warnings import GetRandomNumber_DeprecationWarning +from Crypto.pct_warnings import GetRandomNumber_DeprecationWarning, PowmInsecureWarning +from warnings import warn as _warn import math +import sys +from Crypto.Util.py3compat import * bignum = long try: from Crypto.PublicKey import _fastmath except ImportError: + # For production, we are going to let import issues due to gmp/mpir shared + # libraries not loading slide silently and use slowmath. If you'd rather + # see an exception raised if _fastmath exists but cannot be imported, + # uncomment the below + # + # from distutils.sysconfig import get_config_var + # import inspect, os + # _fm_path = os.path.normpath(os.path.dirname(os.path.abspath( + # inspect.getfile(inspect.currentframe()))) + # +"/../../PublicKey/_fastmath"+get_config_var("SO")) + # if os.path.exists(_fm_path): + # raise ImportError("While the _fastmath module exists, importing "+ + # "it failed. This may point to the gmp or mpir shared library "+ + # "not being in the path. _fastmath was found at "+_fm_path) _fastmath = None +# You need libgmp v5 or later to get mpz_powm_sec. Warn if it's not available. +if _fastmath is not None and not _fastmath.HAVE_DECL_MPZ_POWM_SEC: + _warn("Not using mpz_powm_sec. You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning) + # New functions from _number_new import * @@ -62,7 +83,8 @@ def size (N): def getRandomNumber(N, randfunc=None): """Deprecated. Use getRandomInteger or getRandomNBitInteger instead.""" - warnings.warn("Crypto.Util.number.getRandomNumber has confusing semantics and has been deprecated. Use getRandomInteger or getRandomNBitInteger instead.", + warnings.warn("Crypto.Util.number.getRandomNumber has confusing semantics"+ + "and has been deprecated. Use getRandomInteger or getRandomNBitInteger instead.", GetRandomNumber_DeprecationWarning) return getRandomNBitInteger(N, randfunc) @@ -83,7 +105,7 @@ def getRandomInteger(N, randfunc=None): odd_bits = N % 8 if odd_bits != 0: char = ord(randfunc(1)) >> (8-odd_bits) - S = chr(char) + S + S = bchr(char) + S value = bytes_to_long(S) return value @@ -221,7 +243,7 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): The optional false_positive_prob is the statistical probability that true is returned even though it is not (pseudo-prime). It defaults to 1e-6 (less than 1:1000000). - Note that the real probability of a false-positiv is far less. This is + Note that the real probability of a false-positive is far less. This is just the mathematically provable limit. randfunc should take a single int parameter and return that @@ -239,7 +261,8 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): # Use the accelerator if available if _fastmath is not None: - return _fastmath.getStrongPrime(long(N), long(e), false_positive_prob, randfunc) + return _fastmath.getStrongPrime(long(N), long(e), false_positive_prob, + randfunc) if (N < 512) or ((N % 128) != 0): raise ValueError ("bits must be multiple of 128 and > 512") @@ -263,7 +286,6 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): for i in (0, 1): # randomly choose 101-bit y y = getRandomNBitInteger (101, randfunc) - # initialize the field for sieving field = [0] * 5 * len (sieve_base) # sieve the field @@ -300,13 +322,13 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): X = X + (R - (X % increment)) while 1: is_possible_prime = 1 - # first check canidate against sieve_base + # first check candidate against sieve_base for prime in sieve_base: if (X % prime) == 0: is_possible_prime = 0 break # if e is given make sure that e and X-1 are coprime - # this is not necessarily a strong prime criterion but usefull when + # this is not necessarily a strong prime criterion but useful when # creating them for RSA where the p-1 and q-1 should be coprime to # the public exponent e if e and is_possible_prime: @@ -314,8 +336,9 @@ def getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None): if GCD (e, X-1) != 1: is_possible_prime = 0 else: - if GCD (e, (X-1)/2) != 1: + if GCD (e, divmod((X-1),2)[0]) != 1: is_possible_prime = 0 + # do some Rabin-Miller-Tests if is_possible_prime: result = _rabinMillerTest (X, rabin_miller_rounds) @@ -336,7 +359,7 @@ def isPrime(N, false_positive_prob=1e-6, randfunc=None): The optional false_positive_prob is the statistical probability that true is returned even though it is not (pseudo-prime). It defaults to 1e-6 (less than 1:1000000). - Note that the real probability of a false-positiv is far less. This is + Note that the real probability of a false-positive is far less. This is just the mathematically provable limit. If randfunc is omitted, then Random.new().read is used. @@ -370,7 +393,7 @@ def long_to_bytes(n, blocksize=0): blocksize. """ # after much testing, this algorithm was deemed to be the fastest - s = '' + s = b('') n = long(n) pack = struct.pack while n > 0: @@ -378,17 +401,17 @@ def long_to_bytes(n, blocksize=0): n = n >> 32 # strip off leading zeros for i in range(len(s)): - if s[i] != '\000': + if s[i] != b('\000')[0]: break else: # only happens when n == 0 - s = '\000' + s = b('\000') i = 0 s = s[i:] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and len(s) % blocksize: - s = (blocksize - len(s) % blocksize) * '\000' + s + s = (blocksize - len(s) % blocksize) * b('\000') + s return s def bytes_to_long(s): @@ -402,7 +425,7 @@ def bytes_to_long(s): length = len(s) if length % 4: extra = (4 - length % 4) - s = '\000' * extra + s + s = b('\000') * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack('>I', s[i:i+4])[0] @@ -418,7 +441,8 @@ def str2long(s): return bytes_to_long(s) def _import_Random(): - # This is called in a function instead of at the module level in order to avoid problems with recursive imports + # This is called in a function instead of at the module level in order to + # avoid problems with recursive imports global Random, StrongRandom from Crypto import Random from Crypto.Random.random import StrongRandom diff --git a/lib/Crypto/Util/python_compat.py b/lib/Crypto/Util/py21compat.py index 7eb2803..624408b 100644 --- a/lib/Crypto/Util/python_compat.py +++ b/lib/Crypto/Util/py21compat.py @@ -1,6 +1,6 @@ # -*- coding: utf-8 -*- # -# Util/python_compat.py : Compatibility code for old versions of Python +# Util/py21compat.py : Compatibility code for Python 2.1 # # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> # @@ -22,7 +22,7 @@ # SOFTWARE. # =================================================================== -"""Compatibility code for old versions of Python +"""Compatibility code for Python 2.1 Currently, this just defines: - True and False diff --git a/lib/Crypto/Util/py3compat.py b/lib/Crypto/Util/py3compat.py new file mode 100644 index 0000000..76d168b --- /dev/null +++ b/lib/Crypto/Util/py3compat.py @@ -0,0 +1,70 @@ +# -*- coding: utf-8 -*- +# +# Util/py3compat.py : Compatibility code for handling Py3k / Python 2.x +# +# Written in 2010 by Thorsten Behrens +# +# =================================================================== +# The contents of this file are dedicated to the public domain. To +# the extent that dedication to the public domain is not available, +# everyone is granted a worldwide, perpetual, royalty-free, +# non-exclusive license to exercise all rights associated with the +# contents of this file for any purpose whatsoever. +# No rights are reserved. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS +# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +# =================================================================== + +"""Compatibility code for handling string/bytes changes from Python 2.x to Py3k +""" + +__revision__ = "$Id$" + +import sys + +if sys.version_info[0] == 2: + def b(s): + return s + def bchr(s): + return chr(s) + def bstr(s): + return str(s) + def bord(s): + return ord(s) + def tobytes(s): + if isinstance(s,str): + return s + else: + if isinstance(s, unicode): + return s.encode("latin-1") + else: + ''.join(s) +else: + def b(s): + return s.encode("latin-1") # utf-8 would cause some side-effects we don't want + def bchr(s): + return bytes([s]) + def bstr(s): + if isinstance(s,str): + return bytes(s,"latin-1") + else: + return bytes(s) + def bord(s): + return s + def tobytes(s): + if isinstance(s,bytes): + return s + else: + if isinstance(s,str): + return s.encode("latin-1") + else: + return bytes(s) + +# vim:set ts=4 sw=4 sts=4 expandtab: diff --git a/lib/Crypto/Util/wrapper.py b/lib/Crypto/Util/wrapper.py index 479ae26..1090fc7 100644 --- a/lib/Crypto/Util/wrapper.py +++ b/lib/Crypto/Util/wrapper.py @@ -1,6 +1,6 @@ # # wrapper.py: Small class to wrap an object, instantiated from a class -# or generated by a module. +# or generated by a module. # # =================================================================== # The contents of this file are dedicated to the public domain. To @@ -24,23 +24,24 @@ __all__ = [ 'Wrapper' ] class Wrapper: - ''' - Wrapper for an object, instantiated from a class - or from a call to a new() function in a module. - ''' - def __init__(self, wrapped, *args): - """ - wrapped is either a class or a module with a new() function. - """ - if hasattr(wrapped, 'new'): - self._wrapped = wrapped.new(*args) - else: - self._wrapped = wrapped(*args) - def __getattr__(self, name): - try: - return getattr(getattr(self,'_wrapped'),name) - except AttributeError: - if hasattr(self, name): - return getattr(self,name) - raise + ''' + Wrapper for an object, instantiated from a class + or from a call to a new() function in a module. + ''' + def __init__(self, wrapped, *args): + """ + wrapped is either a class or a module with a new() function. + """ + if hasattr(wrapped, 'new'): + self._wrapped = wrapped.new(*args) + else: + self._wrapped = wrapped(*args) + + def __getattr__(self, name): + try: + return getattr(getattr(self,'_wrapped'),name) + except AttributeError: + if hasattr(self, name): + return getattr(self,name) + raise diff --git a/lib/Crypto/pct_warnings.py b/lib/Crypto/pct_warnings.py index 2a5716c..9b4361e 100644 --- a/lib/Crypto/pct_warnings.py +++ b/lib/Crypto/pct_warnings.py @@ -49,6 +49,9 @@ class ClockRewindWarning(CryptoRuntimeWarning): class GetRandomNumber_DeprecationWarning(CryptoDeprecationWarning): """Issued when Crypto.Util.number.getRandomNumber is invoked.""" +class PowmInsecureWarning(CryptoRuntimeWarning): + """Warning for when _fastmath is built without mpz_powm_sec""" + # By default, we want this warning to be shown every time we compensate for # clock rewinding. import warnings as _warnings |
