1 | #!/usr/bin/env python |
---|
2 | |
---|
3 | import random, re |
---|
4 | import unittest |
---|
5 | |
---|
6 | from binascii import a2b_hex, b2a_hex |
---|
7 | from pkg_resources import resource_string |
---|
8 | |
---|
9 | from pycryptopp.hash import hmac, sha256 |
---|
10 | TEST_HMAC_RE=re.compile("\nCOUNT=([0-9]+)\nKEY=([0-9a-f]+)\nDATA=([0-9a-f]+)\nHMAC-SHA256=([0-9a-f]+)") |
---|
11 | |
---|
12 | class HMACTest(unittest.TestCase): |
---|
13 | def test_HMAC(self): |
---|
14 | curfile = open('../testvectors/HMACMsg.txt', 'r') |
---|
15 | s = curfile.read() |
---|
16 | print s,"\n" |
---|
17 | return self._test_HMAC(s) |
---|
18 | |
---|
19 | def _test_HMAC(self, vects_str): |
---|
20 | for mo in TEST_HMAC_RE.finditer(vects_str): |
---|
21 | count = int(mo.group(1)) |
---|
22 | # print "hello", count, "\n" |
---|
23 | key = a2b_hex(mo.group(2)) |
---|
24 | data = a2b_hex(mo.group(3)) |
---|
25 | hmacvalue = mo.group(4) |
---|
26 | |
---|
27 | length = len(hmacvalue) |
---|
28 | h = hmac.new(key,data,sha256.SHA256) |
---|
29 | computedhmacvalue = b2a_hex(h.digest()) |
---|
30 | self.failUnlessEqual(computedhmacvalue[:length],hmacvalue,"computedhmac: %s, hmac: %s" % (computedhmacvalue, hmacvalue)) |
---|
31 | |
---|
32 | if __name__ == "__main__": |
---|
33 | unittest.main() |
---|