2 -- Copyright (C) 2009-2010 Matthew Wild
3 -- Copyright (C) 2009-2010 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
13 * Lua library for sha1, sha256 and md5 hashes
20 #include <openssl/sha.h>
21 #include <openssl/md5.h>
23 const char* hex_tab = "0123456789abcdef";
24 void toHex(const char* in, int length, char* out) {
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];
32 #define MAKE_HASH_FUNCTION(myFunc, func, size) \
33 static int myFunc(lua_State *L) { \
35 const char *s = luaL_checklstring(L, 1, &len); \
36 int hex_out = lua_toboolean(L, 2); \
38 char result[size*2]; \
39 func((const unsigned char*)s, len, (unsigned char*)hash); \
41 toHex(hash, size, result); \
42 lua_pushlstring(L, result, size*2); \
44 lua_pushlstring(L, hash, size);\
49 MAKE_HASH_FUNCTION(Lsha1, SHA1, 20)
50 MAKE_HASH_FUNCTION(Lsha256, SHA256, 32)
51 MAKE_HASH_FUNCTION(Lmd5, MD5, 16)
53 static const luaL_Reg Reg[] =
56 { "sha256", Lsha256 },
61 LUALIB_API int luaopen_util_hashes(lua_State *L)
63 luaL_register(L, "hashes", Reg);
64 lua_pushliteral(L, "version"); /** version */
65 lua_pushliteral(L, "-3.14");