diff options
author | Dwayne Bent <dbb.0@liqd.org> | 2009-07-01 20:24:47 -0400 |
---|---|---|
committer | Dwayne Bent <dbb.0@liqd.org> | 2009-07-01 20:24:47 -0400 |
commit | 0ba13417109702dfe58ab29e497825366d3a6464 (patch) | |
tree | 7754e61f4bdf7094963ae9df8b7707fe430a8814 /util/hmac.lua | |
parent | dab398fd1ee4c93b63dd0390401b62b5017f4c3f (diff) | |
download | prosody-0ba13417109702dfe58ab29e497825366d3a6464.tar.gz prosody-0ba13417109702dfe58ab29e497825366d3a6464.zip |
Added HMAC utility module
Produces HMAC codes using all the supported hashes (md5, sha1, sha256)
Diffstat (limited to 'util/hmac.lua')
-rw-r--r-- | util/hmac.lua | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/util/hmac.lua b/util/hmac.lua new file mode 100644 index 00000000..b3098380 --- /dev/null +++ b/util/hmac.lua @@ -0,0 +1,67 @@ +local hashes = require "util.hashes" +local xor = require "bit".bxor + +module "hmac" + +local function arraystr(array) + t = {} + for i = 1,table.getn(array) do + table.insert(t, string.char(array[i])) + end + + return table.concat(t) +end + +--[[ +key + the key to use in the hash +message + the message to hash +hash + the hash function +blocksize + the blocksize for the hash function in bytes +hex + return raw hash or hexadecimal string +--]] +function hmac(key, message, hash, blocksize, hex) + local opad = {} + local ipad = {} + + for i = 1,blocksize do + opad[i] = 0x5c + ipad[i] = 0x36 + end + + if #key > blocksize then + key = hash(key) + end + + for i = 1,#key do + ipad[i] = xor(ipad[i],key:sub(i,i):byte()) + opad[i] = xor(opad[i],key:sub(i,i):byte()) + end + + opad = arraystr(opad) + ipad = arraystr(ipad) + + if hex then + return hash(opad..hash(ipad..message), true) + else + return hash(opad..hash(ipad..message)) + end +end + +function md5(key, message, hex) + return hmac(key, message, hashes.md5, 64, hex) +end + +function sha1(key, message, hex) + return hmac(key, message, hashes.sha1, 64, hex) +end + +function sha256(key, message, hex) + return hmac(key, message, hashes.sha256, 64, hex) +end + +return _M |