1 | #!/usr/bin/env python |
---|
2 | |
---|
3 | #from pycryptopp import sha256 |
---|
4 | import sha256 |
---|
5 | |
---|
6 | digest_size = None |
---|
7 | |
---|
8 | class HMAC(object): |
---|
9 | """RFC2104 HMAC class |
---|
10 | """ |
---|
11 | |
---|
12 | blocksize = 64 |
---|
13 | def __init__(self, key, msg=None, digestmod = None): |
---|
14 | """Create a new HMAC object |
---|
15 | |
---|
16 | key: key for the keyed hash object. |
---|
17 | msg: Initial input for the hash, if provided. |
---|
18 | digestmod: A module from pycrptopp hash package |
---|
19 | """ |
---|
20 | |
---|
21 | if digestmod is None: |
---|
22 | digestmod = sha256.SHA256 |
---|
23 | |
---|
24 | if callable(digestmod): |
---|
25 | self.digest_cons = digestmod |
---|
26 | else: |
---|
27 | self.digest_cons = lambda d='':digestmod.new(d) |
---|
28 | |
---|
29 | self.outer = self.digest_cons() |
---|
30 | self.inner = self.digest_cons() |
---|
31 | self.digest_size = len(self.digest_cons().digest()) |
---|
32 | |
---|
33 | blocksize = self.blocksize |
---|
34 | if len(key) > blocksize: |
---|
35 | key = self.digest_cons(key).digest() |
---|
36 | |
---|
37 | key = key + chr(0)*(blocksize - len(key)) |
---|
38 | # ikey = key ^ (imask*blocksize) |
---|
39 | # okey = key ^ (omask*blocksize) |
---|
40 | |
---|
41 | ikey = "".join(chr(ord(key[i])^0x5c) for i in xrange(blocksize)) |
---|
42 | okey = "".join(chr(ord(key[i])^0x36) for i in xrange(blocksize)) |
---|
43 | self.outer.update(ikey) |
---|
44 | self.inner.update(okey) |
---|
45 | if msg is not None: |
---|
46 | self.inner.update(msg) |
---|
47 | |
---|
48 | def digest(self): |
---|
49 | """Return the hash value of this hashing object |
---|
50 | """ |
---|
51 | self.outer.update(self.inner.digest()) |
---|
52 | # print "hi,xueyu coming\n" |
---|
53 | return self.outer.digest() |
---|
54 | |
---|
55 | def hexdigest(self): |
---|
56 | """Like digest(), but returns a string of hexadecimal digits instead. |
---|
57 | """ |
---|
58 | self.outer.update(self.inner.digest()) |
---|
59 | return self.outer.hexdigest() |
---|
60 | |
---|
61 | |
---|
62 | def new(key, msg = None, digestmod = None): |
---|
63 | """Create a new hashing object and return it. |
---|
64 | |
---|
65 | key: The starting key for the hash |
---|
66 | msg: if available, will immediately be hashed into the object's starting |
---|
67 | state. |
---|
68 | """ |
---|
69 | return HMAC(key, msg, digestmod) |
---|
70 | |
---|
71 | |
---|
72 | |
---|
73 | |
---|
74 | |
---|
75 | |
---|
76 | |
---|
77 | |
---|
78 | |
---|