updated pycrypto

This commit is contained in:
shim_
2018-05-10 16:56:32 +02:00
parent fb89f1946b
commit 26579a25f1
92 changed files with 2518 additions and 5288 deletions

View File

@@ -28,14 +28,13 @@ __revision__ = "$Id$"
def get_tests(config={}):
tests = []
from Crypto.SelfTest.Hash import test_HMAC; tests += test_HMAC.get_tests(config=config)
from Crypto.SelfTest.Hash import test_CMAC; tests += test_CMAC.get_tests(config=config)
from Crypto.SelfTest.Hash import test_MD2; tests += test_MD2.get_tests(config=config)
from Crypto.SelfTest.Hash import test_MD4; tests += test_MD4.get_tests(config=config)
from Crypto.SelfTest.Hash import test_MD5; tests += test_MD5.get_tests(config=config)
from Crypto.SelfTest.Hash import test_RIPEMD160; tests += test_RIPEMD160.get_tests(config=config)
from Crypto.SelfTest.Hash import test_SHA1; tests += test_SHA1.get_tests(config=config)
from Crypto.SelfTest.Hash import test_SHA256; tests += test_SHA256.get_tests(config=config)
from Crypto.SelfTest.Hash import test_HMAC; tests += test_HMAC.get_tests(config=config)
from Crypto.SelfTest.Hash import test_MD2; tests += test_MD2.get_tests(config=config)
from Crypto.SelfTest.Hash import test_MD4; tests += test_MD4.get_tests(config=config)
from Crypto.SelfTest.Hash import test_MD5; tests += test_MD5.get_tests(config=config)
from Crypto.SelfTest.Hash import test_RIPEMD; tests += test_RIPEMD.get_tests(config=config)
from Crypto.SelfTest.Hash import test_SHA; tests += test_SHA.get_tests(config=config)
from Crypto.SelfTest.Hash import test_SHA256; tests += test_SHA256.get_tests(config=config)
try:
from Crypto.SelfTest.Hash import test_SHA224; tests += test_SHA224.get_tests(config=config)
from Crypto.SelfTest.Hash import test_SHA384; tests += test_SHA384.get_tests(config=config)

View File

@@ -29,10 +29,7 @@ __revision__ = "$Id$"
import sys
import unittest
import binascii
import Crypto.Hash
from Crypto.Util.py3compat import *
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
# For compatibility with Python 2.1 and Python 2.2
if sys.hexversion < 0x02030000:
@@ -43,7 +40,6 @@ if sys.hexversion < 0x02030000:
else:
dict = dict
from Crypto.Util.strxor import strxor_c
class HashDigestSizeSelfTest(unittest.TestCase):
@@ -98,27 +94,11 @@ class HashSelfTest(unittest.TestCase):
self.assertEqual(self.expected.decode(), out3) # h = .new(data); h.hexdigest()
self.assertEqual(self.expected, out4) # h = .new(data); h.digest()
# Verify that the .new() method produces a fresh hash object, except
# for MD5 and SHA1, which are hashlib objects. (But test any .new()
# method that does exist.)
if self.hashmod.__name__ not in ('Crypto.Hash.MD5', 'Crypto.Hash.SHA1') or hasattr(h, 'new'):
h2 = h.new()
h2.update(self.input)
out5 = binascii.b2a_hex(h2.digest())
self.assertEqual(self.expected, out5)
# Verify that Crypto.Hash.new(h) produces a fresh hash object
h3 = Crypto.Hash.new(h)
h3.update(self.input)
out6 = binascii.b2a_hex(h3.digest())
self.assertEqual(self.expected, out6)
if hasattr(h, 'name'):
# Verify that Crypto.Hash.new(h.name) produces a fresh hash object
h4 = Crypto.Hash.new(h.name)
h4.update(self.input)
out7 = binascii.b2a_hex(h4.digest())
self.assertEqual(self.expected, out7)
# Verify that new() object method produces a fresh hash object
h2 = h.new()
h2.update(self.input)
out5 = binascii.b2a_hex(h2.digest())
self.assertEqual(self.expected, out5)
class HashTestOID(unittest.TestCase):
def __init__(self, hashmod, oid):
@@ -127,105 +107,65 @@ class HashTestOID(unittest.TestCase):
self.oid = oid
def runTest(self):
from Crypto.Signature import PKCS1_v1_5
h = self.hashmod.new()
self.assertEqual(PKCS1_v1_5._HASH_OIDS[h.name], self.oid)
class HashDocStringTest(unittest.TestCase):
def __init__(self, hashmod):
unittest.TestCase.__init__(self)
self.hashmod = hashmod
def runTest(self):
docstring = self.hashmod.__doc__
self.assert_(hasattr(self.hashmod, '__doc__'))
self.assert_(isinstance(self.hashmod.__doc__, str))
class GenericHashConstructorTest(unittest.TestCase):
def __init__(self, hashmod):
unittest.TestCase.__init__(self)
self.hashmod = hashmod
def runTest(self):
obj1 = self.hashmod.new("foo")
obj2 = self.hashmod.new()
obj3 = Crypto.Hash.new(obj1.name, "foo")
obj4 = Crypto.Hash.new(obj1.name)
obj5 = Crypto.Hash.new(obj1, "foo")
obj6 = Crypto.Hash.new(obj1)
self.assert_(isinstance(self.hashmod, obj1))
self.assert_(isinstance(self.hashmod, obj2))
self.assert_(isinstance(self.hashmod, obj3))
self.assert_(isinstance(self.hashmod, obj4))
self.assert_(isinstance(self.hashmod, obj5))
self.assert_(isinstance(self.hashmod, obj6))
if self.oid==None:
try:
raised = 0
a = h.oid
except AttributeError:
raised = 1
self.assertEqual(raised,1)
else:
self.assertEqual(h.oid, self.oid)
class MACSelfTest(unittest.TestCase):
def __init__(self, module, description, result, input, key, params):
def __init__(self, hashmod, description, expected_dict, input, key, hashmods):
unittest.TestCase.__init__(self)
self.module = module
self.result = result
self.hashmod = hashmod
self.expected_dict = expected_dict
self.input = input
self.key = key
self.params = params
self.hashmods = hashmods
self.description = description
def shortDescription(self):
return self.description
def runTest(self):
key = binascii.a2b_hex(b(self.key))
data = binascii.a2b_hex(b(self.input))
for hashname in self.expected_dict.keys():
hashmod = self.hashmods[hashname]
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 = b("".join(self.result.split()))
# Strip whitespace from the expected string (which should be in lowercase-hex)
expected = b("".join(self.expected_dict[hashname].split()))
h = self.module.new(key, **self.params)
h.update(data)
out1_bin = h.digest()
out1 = binascii.b2a_hex(h.digest())
out2 = h.hexdigest()
h = self.hashmod.new(key, digestmod=hashmod)
h.update(data)
out1 = binascii.b2a_hex(h.digest())
out2 = h.hexdigest()
# Verify that correct MAC does not raise any exception
h.hexverify(out1)
h.verify(out1_bin)
h = self.hashmod.new(key, data, hashmod)
# Verify that incorrect MAC does raise ValueError exception
wrong_mac = strxor_c(out1_bin, 255)
self.assertRaises(ValueError, h.verify, wrong_mac)
self.assertRaises(ValueError, h.hexverify, "4556")
out3 = h.hexdigest()
out4 = binascii.b2a_hex(h.digest())
h = self.module.new(key, data, **self.params)
# Test .copy()
h2 = h.copy()
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
out3 = h.hexdigest()
out4 = binascii.b2a_hex(h.digest())
# Test .copy()
h2 = h.copy()
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: Check that hexdigest() returns str and digest() returns bytes
if sys.version_info[0] > 2:
self.assertTrue(isinstance(h.digest(), type(b(""))))
self.assertTrue(isinstance(h.hexdigest(), type("")))
# PY3K: Check that .hexverify() accepts bytes or str
if sys.version_info[0] > 2:
h.hexverify(h.hexdigest())
h.hexverify(h.hexdigest().encode('ascii'))
# PY3K: hexdigest() should return str, and digest() should return bytes
self.assertEqual(expected, out1)
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)
# PY3K: hexdigest() should return str(), and digest() bytes
self.assertEqual(expected, out1)
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)
def make_hash_tests(module, module_name, test_data, digest_size, oid=None):
tests = []
@@ -238,22 +178,20 @@ def make_hash_tests(module, module_name, test_data, digest_size, oid=None):
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))
if oid is not None:
tests.append(HashTestOID(module, oid))
tests.append(HashDocStringTest(module))
if getattr(module, 'name', None) is not None:
tests.append(GenericHashConstructorTest(module))
tests.append(HashTestOID(module, oid))
return tests
def make_mac_tests(module, module_name, test_data):
def make_mac_tests(module, module_name, test_data, hashmods):
tests = []
for i in range(len(test_data)):
row = test_data[i]
(key, data, results, description, params) = row
(key, data, results, description) = row
name = "%s #%d: %s" % (module_name, i+1, description)
tests.append(MACSelfTest(module, name, results, data, key, params))
tests.append(MACSelfTest(module, name, results, data, key, hashmods))
return tests
# vim:set ts=4 sw=4 sts=4 expandtab:

View File

@@ -29,17 +29,13 @@ __revision__ = "$Id$"
from common import dict # For compatibility with Python 2.1 and 2.2
from Crypto.Util.py3compat import *
from Crypto.Hash import MD5, SHA1, SHA224, SHA256, SHA384, SHA512, HMAC
default_hash = None
# This is a list of (key, data, results, description) tuples.
test_data = [
## Test vectors from RFC 2202 ##
# Test that the default hashmod is MD5
('0b' * 16,
'4869205468657265',
dict(default_hash='9294727a3638bb1c13f48ef8158bfc9d'),
dict(default='9294727a3638bb1c13f48ef8158bfc9d'),
'default-is-MD5'),
# Test case 1 (MD5)
@@ -179,7 +175,9 @@ test_data = [
bfdc63644f0713938a7f51535c3a35e2
'''),
'RFC 4231 #7 (HMAC-SHA256)'),
]
hashlib_test_data = [
# Test case 8 (SHA224)
('4a656665',
'7768617420646f2079612077616e74'
@@ -205,25 +203,17 @@ test_data = [
def get_tests(config={}):
global test_data
from Crypto.Hash import HMAC, MD5, SHA as SHA1, SHA256
from common import make_mac_tests
# A test vector contains multiple results, each one for a
# different hash algorithm.
# Here we expand each test vector into multiple ones,
# and add the relevant parameters that will be passed to new()
exp_test_data = []
for row in test_data:
for modname in row[2].keys():
t = list(row)
t[2] = row[2][modname]
try:
t.append(dict(digestmod=globals()[modname]))
exp_test_data.append(t)
except AttributeError:
import sys
sys.stderr.write("SelfTest: warning: not testing HMAC-%s (not available)\n" % modname)
return make_mac_tests(HMAC, "HMAC", exp_test_data)
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__':
import unittest

View File

@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(MD2, "MD2", test_data,
digest_size=16,
oid="1.2.840.113549.2.2")
oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02")
if __name__ == '__main__':
import unittest

View File

@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(MD4, "MD4", test_data,
digest_size=16,
oid="1.2.840.113549.2.4")
oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04")
if __name__ == '__main__':
import unittest

View File

@@ -54,7 +54,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(MD5, "MD5", test_data,
digest_size=16,
oid="1.2.840.113549.2.5")
oid="\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05")
if __name__ == '__main__':
import unittest

View File

@@ -0,0 +1,73 @@
# -*- coding: utf-8 -*-
#
# SelfTest/Hash/test_RIPEMD.py: Self-test for the RIPEMD-160 hash function
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# 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.
# ===================================================================
#"""Self-test suite for Crypto.Hash.RIPEMD"""
__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
# http://homes.esat.kuleuven.be/~bosselae/ripemd160.html
('9c1185a5c5e9fc54612808977ee8f548b2258d31', '', "'' (empty string)"),
('0bdc9d2d256b3ee9daae347be6f4dc835a467ffe', 'a'),
('8eb208f7e05d987a9b044a8e98c6b087f15a0bfc', 'abc'),
('5d0689ef49d2fae572b881b123a85ffa21595f36', 'message digest'),
('f71c27109c692c1b56bbdceb5b9d2865b3708dbc',
'abcdefghijklmnopqrstuvwxyz',
'a-z'),
('12a053384a9c0c88e405a06c27dcf49ada62eb2b',
'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
'abcdbcd...pnopq'),
('b0e20b6e3116640286ed3a87a5713079b21f5189',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'A-Z, a-z, 0-9'),
('9b752e45573d4b39f4dbd3323cab82bf63326bfb',
'1234567890' * 8,
"'1234567890' * 8"),
('52783243c1697bdbe16d37f97f68f08325dc1528',
'a' * 10**6,
'"a" * 10**6'),
]
def get_tests(config={}):
from Crypto.Hash import RIPEMD
from common import make_hash_tests
return make_hash_tests(RIPEMD, "RIPEMD", test_data,
digest_size=20,
oid="\x06\x05\x2b\x24\x03\02\x01")
if __name__ == '__main__':
import unittest
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:

View File

@@ -0,0 +1,64 @@
# -*- coding: utf-8 -*-
#
# SelfTest/Hash/SHA.py: Self-test for the SHA-1 hash function
#
# Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net>
#
# ===================================================================
# 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.
# ===================================================================
"""Self-test suite for Crypto.Hash.SHA"""
__revision__ = "$Id$"
from Crypto.Util.py3compat import *
# Test vectors from various sources
# This is a list of (expected_result, input[, description]) tuples.
test_data = [
# FIPS PUB 180-2, A.1 - "One-Block Message"
('a9993e364706816aba3e25717850c26c9cd0d89d', 'abc'),
# FIPS PUB 180-2, A.2 - "Multi-Block Message"
('84983e441c3bd26ebaae4aa1f95129e5e54670f1',
'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'),
# FIPS PUB 180-2, A.3 - "Long Message"
# ('34aa973cd4c4daa4f61eeb2bdbad27316534016f',
# 'a' * 10**6,
# '"a" * 10**6'),
# RFC 3174: Section 7.3, "TEST4" (multiple of 512 bits)
('dea356a2cddd90c7a7ecedc5ebb563934f460452',
'01234567' * 80,
'"01234567" * 80'),
]
def get_tests(config={}):
from Crypto.Hash import SHA
from common import make_hash_tests
return make_hash_tests(SHA, "SHA", test_data,
digest_size=20,
oid="\x06\x05\x2B\x0E\x03\x02\x1A")
if __name__ == '__main__':
import unittest
suite = lambda: unittest.TestSuite(get_tests())
unittest.main(defaultTest='suite')
# vim:set ts=4 sw=4 sts=4 expandtab:

View File

@@ -55,7 +55,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA224, "SHA224", test_data,
digest_size=28,
oid='2.16.840.1.101.3.4.2.4')
oid='\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04')
if __name__ == '__main__':
import unittest

View File

@@ -81,7 +81,7 @@ def get_tests(config={}):
from common import make_hash_tests
tests = make_hash_tests(SHA256, "SHA256", test_data,
digest_size=32,
oid="2.16.840.1.101.3.4.2.1")
oid="\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01")
if config.get('slow_tests'):
tests += [LargeSHA256Test()]

View File

@@ -53,7 +53,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA384, "SHA384", test_data,
digest_size=48,
oid='2.16.840.1.101.3.4.2.2')
oid='\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02')
if __name__ == '__main__':
import unittest

View File

@@ -50,7 +50,7 @@ def get_tests(config={}):
from common import make_hash_tests
return make_hash_tests(SHA512, "SHA512", test_data,
digest_size=64,
oid="2.16.840.1.101.3.4.2.3")
oid="\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03")
if __name__ == '__main__':
import unittest