blob: 6add21008137dff1f1f5efe88b09aab46a9605fe [file] [log] [blame]
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +00001#
2# Test suite to check compliance with PEP 247, the standard API for
Tim Peters88768482001-11-13 21:51:26 +00003# hashing algorithms.
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +00004#
5
Brett Cannon7eec2172007-05-30 22:24:28 +00006import warnings
7warnings.filterwarnings("ignore", "the md5 module is deprecated.*",
8 DeprecationWarning)
Brett Cannonc2aa09a2007-05-31 19:20:00 +00009warnings.filterwarnings("ignore", "the sha module is deprecated.*",
10 DeprecationWarning)
Brett Cannon7eec2172007-05-30 22:24:28 +000011
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000012import md5, sha, hmac
13
14def check_hash_module(module, key=None):
15 assert hasattr(module, 'digest_size'), "Must have digest_size"
16 assert (module.digest_size is None or
17 module.digest_size > 0), "digest_size must be None or positive"
18
19 if key is not None:
20 obj1 = module.new(key)
21 obj2 = module.new(key, "string")
22
23 h1 = module.new(key, "string").digest()
24 obj3 = module.new(key) ; obj3.update("string") ; h2 = obj3.digest()
25 assert h1 == h2, "Hashes must match"
26
27 else:
28 obj1 = module.new()
29 obj2 = module.new("string")
30
31 h1 = module.new("string").digest()
32 obj3 = module.new() ; obj3.update("string") ; h2 = obj3.digest()
33 assert h1 == h2, "Hashes must match"
34
35 assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr"
36 if module.digest_size is not None:
37 assert obj1.digest_size == module.digest_size, "digest_size must match"
38 assert obj1.digest_size == len(h1), "digest_size must match actual size"
39 obj1.update("string")
40 obj_copy = obj1.copy()
41 assert obj1.digest() == obj_copy.digest(), "Copied objects must match"
42 assert obj1.hexdigest() == obj_copy.hexdigest(), \
43 "Copied objects must match"
44 digest, hexdigest = obj1.digest(), obj1.hexdigest()
45 hd2 = ""
46 for byte in digest:
47 hd2 += "%02x" % ord(byte)
48 assert hd2 == hexdigest, "hexdigest doesn't appear correct"
49
50 print 'Module', module.__name__, 'seems to comply with PEP 247'
51
52
53if __name__ == '__main__':
54 check_hash_module(md5)
55 check_hash_module(sha)
56 check_hash_module(hmac, key='abc')