2 -- Copyright (C) 2008 Matthew Wild
3 -- Copyright (C) 2008 Waqas Hussain
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.
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.
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.
23 * Lua library for sha1, sha256 and md5 hashes
\r
29 #include "lauxlib.h"
\r
30 #include <openssl/sha.h>
\r
31 #include <openssl/md5.h>
\r
33 const char* hex_tab = "0123456789abcdef";
\r
34 void toHex(const char* in, int length, char* out) {
\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
42 #define MAKE_HASH_FUNCTION(myFunc, func, size) \
\r
43 static int myFunc(lua_State *L) { \
\r
45 const char *s = luaL_checklstring(L, 1, &len); \
\r
46 int hex_out = lua_toboolean(L, 2); \
\r
48 char result[size*2]; \
\r
49 func((const unsigned char*)s, len, (unsigned char*)hash); \
\r
51 toHex(hash, size, result); \
\r
52 lua_pushlstring(L, result, size*2); \
\r
54 lua_pushlstring(L, hash, size);\
\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
63 static const luaL_Reg Reg[] =
\r
66 { "sha256", Lsha256 },
\r
71 LUALIB_API int luaopen_util_hashes(lua_State *L)
\r
73 luaL_register(L, "hashes", Reg);
\r
74 lua_pushliteral(L, "version"); /** version */
\r
75 lua_pushliteral(L, "-3.14");
\r