Ticket #42: test_hkdf_new.py

File test_hkdf_new.py, 2.1 KB (added by xueyucoder, at 2011-12-22T15:59:58Z)

add comment about where the test vectors come from

Line 
1#!/usr/bin/env python
2
3import random, re
4import unittest
5import hashlib
6
7from binascii import a2b_hex, b2a_hex
8from pkg_resources import resource_string
9
10from pycryptopp.hash import hkdf, sha256
11TEST_HKDF_RE=re.compile("\nCOUNT=([0-9]+)\nHASH=([0-9A-Z]+)\nIKM=([0-9a-f]+)\nSALT=([0-9a-z ]+)\nINFO=([0-9a-z ]+)\nL=([0-9]+)\nPRK=([0-9a-f]+)\nOKM=([0-9a-f]+)")
12
13
14class HKDFTest(unittest.TestCase):
15    def test_HKDF(self):
16        # The test vector is from RFC 5869 (HMAC-based Extract-and-Expand Key Derivation Function (HKDF))'s
17        # Appendix A. Test Vectors
18        # http://tools.ietf.org/html/rfc5869
19        curfile = open('../testvectors/HKDFMsg.txt', 'r')
20        s = curfile.read()
21        print s, "\n"
22        return self._test_HKDF(s)
23
24    def _test_HKDF(self, vects_str):
25        for mo in TEST_HKDF_RE.finditer(vects_str):
26            count = int(mo.group(1))
27            print "test hdkf: ", count, "\n"
28            hashalg =str(mo.group(2))
29            if hashalg == "SHA256":
30                print "this is sha256\n"
31                hash=sha256.SHA256
32            elif hashalg == "SHA1":
33                print "this is sha1\n"
34                hash=hashlib.sha1
35
36            ikm = a2b_hex(mo.group(3))
37            salttmp = mo.group(4)
38            if salttmp == "none":
39                salt = None
40            elif salttmp == "zero length":
41                salt = ""
42            else:
43                salt = a2b_hex(salttmp)
44           
45            infotmp = mo.group(5)
46            if infotmp == "zero length":
47                info = ""
48            else:
49                info = a2b_hex(infotmp)
50
51            l = int(mo.group(6))
52            prk = a2b_hex(mo.group(7))
53            okm = a2b_hex(mo.group(8))
54
55            hk = hkdf.new(ikm, l, salt, info, hash)
56            computedprk = hk.extract()
57            self.failUnlessEqual(computedprk, prk, "computedprk: %s, prk: %s" % (b2a_hex(computedprk), b2a_hex(prk)))
58
59            computedokm = hk.expand()
60            self.failUnlessEqual(computedokm, okm, "computedokm: %s, okm: %s" % (b2a_hex(computedokm), b2a_hex(okm)))
61
62
63if __name__ == "__main__":
64    unittest.main()
65
66
67