Remove some debugging from pposix.c
[prosody.git] / util-src / hashes.c
1 /* Prosody IM v0.1
2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
4 -- 
5 -- This program is free software; you can redistribute it and/or
6 -- modify it under the terms of the GNU General Public License
7 -- as published by the Free Software Foundation; either version 2
8 -- of the License, or (at your option) any later version.
9 -- 
10 -- This program is distributed in the hope that it will be useful,
11 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
12 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 -- GNU General Public License for more details.
14 -- 
15 -- You should have received a copy of the GNU General Public License
16 -- along with this program; if not, write to the Free Software
17 -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 */
19
20
21 /*\r
22 * hashes.c\r
23 * Lua library for sha1, sha256 and md5 hashes\r
24 */\r
25 \r
26 #include <string.h>\r
27 \r
28 #include "lua.h"\r
29 #include "lauxlib.h"\r
30 #include <openssl/sha.h>\r
31 #include <openssl/md5.h>\r
32 \r
33 const char* hex_tab = "0123456789abcdef";\r
34 void toHex(const char* in, int length, char* out) {\r
35         int i;\r
36         for (i = 0; i < length; i++) {\r
37                 out[i*2] = hex_tab[(in[i] >> 4) & 0xF];\r
38                 out[i*2+1] = hex_tab[(in[i]) & 0xF];\r
39         }\r
40 }\r
41 \r
42 #define MAKE_HASH_FUNCTION(myFunc, func, size) \\r
43 static int myFunc(lua_State *L) { \\r
44         size_t len; \\r
45         const char *s = luaL_checklstring(L, 1, &len); \\r
46         int hex_out = lua_toboolean(L, 2); \\r
47         char hash[size]; \\r
48         char result[size*2]; \\r
49         func((const unsigned char*)s, len, (unsigned char*)hash);  \\r
50         if (hex_out) { \\r
51                 toHex(hash, size, result); \\r
52                 lua_pushlstring(L, result, size*2); \\r
53         } else { \\r
54                 lua_pushlstring(L, hash, size);\\r
55         } \\r
56         return 1; \\r
57 }\r
58 \r
59 MAKE_HASH_FUNCTION(Lsha1, SHA1, 20)\r
60 MAKE_HASH_FUNCTION(Lsha256, SHA256, 32)\r
61 MAKE_HASH_FUNCTION(Lmd5, MD5, 16)\r
62 \r
63 static const luaL_Reg Reg[] =\r
64 {\r
65         { "sha1",       Lsha1   },\r
66         { "sha256",     Lsha256 },\r
67         { "md5",        Lmd5    },\r
68         { NULL,         NULL    }\r
69 };\r
70 \r
71 LUALIB_API int luaopen_util_hashes(lua_State *L)\r
72 {\r
73         luaL_register(L, "hashes", Reg);\r
74         lua_pushliteral(L, "version");                  /** version */\r
75         lua_pushliteral(L, "-3.14");\r
76         lua_settable(L,-3);\r
77         return 1;\r
78 }\r