Merge Tobias's fancy SASL branch->trunk
[prosody.git] / util-src / hashes.c
1 /* Prosody IM
2 -- Copyright (C) 2009-2010 Matthew Wild
3 -- Copyright (C) 2009-2010 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
10
11 /*
12 * hashes.c
13 * Lua library for sha1, sha256 and md5 hashes
14 */
15
16 #include <string.h>
17
18 #include "lua.h"
19 #include "lauxlib.h"
20 #include <openssl/sha.h>
21 #include <openssl/md5.h>
22
23 const char* hex_tab = "0123456789abcdef";
24 void toHex(const char* in, int length, char* out) {
25         int i;
26         for (i = 0; i < length; i++) {
27                 out[i*2] = hex_tab[(in[i] >> 4) & 0xF];
28                 out[i*2+1] = hex_tab[(in[i]) & 0xF];
29         }
30 }
31
32 #define MAKE_HASH_FUNCTION(myFunc, func, size) \
33 static int myFunc(lua_State *L) { \
34         size_t len; \
35         const char *s = luaL_checklstring(L, 1, &len); \
36         int hex_out = lua_toboolean(L, 2); \
37         char hash[size]; \
38         char result[size*2]; \
39         func((const unsigned char*)s, len, (unsigned char*)hash);  \
40         if (hex_out) { \
41                 toHex(hash, size, result); \
42                 lua_pushlstring(L, result, size*2); \
43         } else { \
44                 lua_pushlstring(L, hash, size);\
45         } \
46         return 1; \
47 }
48
49 MAKE_HASH_FUNCTION(Lsha1, SHA1, 20)
50 MAKE_HASH_FUNCTION(Lsha256, SHA256, 32)
51 MAKE_HASH_FUNCTION(Lmd5, MD5, 16)
52
53 static const luaL_Reg Reg[] =
54 {
55         { "sha1",       Lsha1   },
56         { "sha256",     Lsha256 },
57         { "md5",        Lmd5    },
58         { NULL,         NULL    }
59 };
60
61 LUALIB_API int luaopen_util_hashes(lua_State *L)
62 {
63         luaL_register(L, "hashes", Reg);
64         lua_pushliteral(L, "version");                  /** version */
65         lua_pushliteral(L, "-3.14");
66         lua_settable(L,-3);
67         return 1;
68 }