Merge with tip.
[prosody.git] / util / hmac.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local hashes = require "util.hashes"
10 local xor = require "bit".bxor
11
12 local t_insert, t_concat = table.insert, table.concat;
13 local s_char = string.char;
14
15 module "hmac"
16
17 local function arraystr(array)
18         local t = {}
19         for i = 1,#array do
20                 t_insert(t, s_char(array[i]))
21         end
22
23         return t_concat(t)
24 end
25
26 --[[
27 key
28         the key to use in the hash
29 message
30         the message to hash
31 hash
32         the hash function
33 blocksize
34         the blocksize for the hash function in bytes
35 hex
36   return raw hash or hexadecimal string
37 --]]
38 function hmac(key, message, hash, blocksize, hex)
39         local opad = {}
40         local ipad = {}
41         
42         for i = 1,blocksize do
43                 opad[i] = 0x5c
44                 ipad[i] = 0x36
45         end
46
47         if #key > blocksize then
48                 key = hash(key)
49         end
50
51         for i = 1,#key do
52                 ipad[i] = xor(ipad[i],key:sub(i,i):byte())
53                 opad[i] = xor(opad[i],key:sub(i,i):byte())
54         end
55
56         opad = arraystr(opad)
57         ipad = arraystr(ipad)
58
59         if hex then
60                 return hash(opad..hash(ipad..message), true)
61         else
62                 return hash(opad..hash(ipad..message))
63         end
64 end
65
66 function md5(key, message, hex)
67         return hmac(key, message, hashes.md5, 64, hex)
68 end
69
70 function sha1(key, message, hex)
71         return hmac(key, message, hashes.sha1, 64, hex)
72 end
73
74 function sha256(key, message, hex)
75         return hmac(key, message, hashes.sha256, 64, hex)
76 end
77
78 return _M