blob: 89ca6ffbbab0ead2692b2bc7b2a79322db7812f6 [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
Guido van Rossuma8add0e2007-05-14 22:03:55 +00006import hmac
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +00007
8def check_hash_module(module, key=None):
9 assert hasattr(module, 'digest_size'), "Must have digest_size"
10 assert (module.digest_size is None or
11 module.digest_size > 0), "digest_size must be None or positive"
12
13 if key is not None:
14 obj1 = module.new(key)
Alexandre Vassalottia351f772008-03-03 02:59:49 +000015 obj2 = module.new(key, b"string")
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000016
Alexandre Vassalottia351f772008-03-03 02:59:49 +000017 h1 = module.new(key, b"string").digest()
18 obj3 = module.new(key) ; obj3.update(b"string") ; h2 = obj3.digest()
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000019 assert h1 == h2, "Hashes must match"
20
21 else:
22 obj1 = module.new()
Alexandre Vassalottia351f772008-03-03 02:59:49 +000023 obj2 = module.new(b"string")
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000024
Alexandre Vassalottia351f772008-03-03 02:59:49 +000025 h1 = module.new(b"string").digest()
26 obj3 = module.new() ; obj3.update(b"string") ; h2 = obj3.digest()
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000027 assert h1 == h2, "Hashes must match"
28
29 assert hasattr(obj1, 'digest_size'), "Objects must have digest_size attr"
30 if module.digest_size is not None:
31 assert obj1.digest_size == module.digest_size, "digest_size must match"
32 assert obj1.digest_size == len(h1), "digest_size must match actual size"
Alexandre Vassalottia351f772008-03-03 02:59:49 +000033 obj1.update(b"string")
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000034 obj_copy = obj1.copy()
35 assert obj1.digest() == obj_copy.digest(), "Copied objects must match"
36 assert obj1.hexdigest() == obj_copy.hexdigest(), \
37 "Copied objects must match"
38 digest, hexdigest = obj1.digest(), obj1.hexdigest()
39 hd2 = ""
40 for byte in digest:
Alexandre Vassalottia351f772008-03-03 02:59:49 +000041 hd2 += "%02x" % byte
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000042 assert hd2 == hexdigest, "hexdigest doesn't appear correct"
43
Guido van Rossumbe19ed72007-02-09 05:37:30 +000044 print('Module', module.__name__, 'seems to comply with PEP 247')
Andrew M. Kuchlinga0b60352001-11-02 21:46:17 +000045
46
47if __name__ == '__main__':
Alexandre Vassalottia351f772008-03-03 02:59:49 +000048 check_hash_module(hmac, key=b'abc')