1/* 2 See license.txt in the root of this project. 3*/ 4 5# include <ctype.h> 6 7# include <utilmd5.h> 8# include <utiliof.h> 9# include <utilbasexx.h> 10 11# include "luametatex.h" 12 13/* 14# define wrapped_md5(message,len,output) md5_digest(message,len,(unsigned char *) output, 0) 15 16static int md5lib_sum(lua_State *L) 17{ 18 char buf[16]; 19 size_t l; 20 const char *message = luaL_checklstring(L, 1, &l); 21 wrapped_md5(message, l, buf); 22 lua_pushlstring(L, buf, 16L); 23 return 1; 24} 25 26static int md5lib_hex(lua_State *L) 27{ 28 char buf[16]; 29 char hex[32]; 30 iof *inp = iof_filter_string_reader(buf, 16); 31 iof *out = iof_filter_string_writer(hex, 32); 32 size_t l; 33 const char *message = luaL_checklstring(L, 1, &l); 34 wrapped_md5(message, l, buf); 35 base16_encode_lc(inp, out); 36 lua_pushlstring(L, hex, iof_size(out)); 37 iof_free(inp); 38 iof_free(out); 39 return 1; 40} 41 42static int md5lib_HEX(lua_State *L) 43{ 44 char buf[16]; 45 char hex[32]; 46 iof *inp = iof_filter_string_reader(buf, 16); 47 iof *out = iof_filter_string_writer(hex, 32); 48 size_t l; 49 const char *message = luaL_checklstring(L, 1, &l); 50 wrapped_md5(message, l, buf); 51 base16_encode_uc(inp, out); 52 lua_pushlstring(L, hex, iof_size(out)); 53 iof_free(inp); 54 iof_free(out); 55 return 1; 56} 57*/ 58 59# define MD5_RESULT_LENGTH (MD5_STRING_LENGTH-1) 60 61# define md5_body(MD5_LENGTH, CONVERSION, RESULT_LENGTH) do { \ 62 if (lua_type(L, 1) == LUA_TSTRING) { \ 63 uint8_t result[MD5_LENGTH]; \ 64 size_t size = 0; \ 65 const char *data = lua_tolstring(L, 1, &size); \ 66 md5_digest(data, size, (unsigned char *) result, CONVERSION); \ 67 lua_pushlstring(L, (const char *) result, RESULT_LENGTH); \ 68 return 1; \ 69 } \ 70 return 0; \ 71} while (0) 72 73static int md5lib_sum(lua_State *L) { md5_body(MD5_DIGEST_LENGTH, MD5_BYTES, MD5_DIGEST_LENGTH); } 74static int md5lib_hex(lua_State *L) { md5_body(MD5_STRING_LENGTH, MD5_LCHEX, MD5_RESULT_LENGTH); } 75static int md5lib_HEX(lua_State *L) { md5_body(MD5_STRING_LENGTH, MD5_UCHEX, MD5_RESULT_LENGTH); } 76 77static struct luaL_Reg md5lib_function_list[] = { 78 { "sum", md5lib_sum }, 79 { "hex", md5lib_hex }, 80 { "HEX", md5lib_HEX }, 81 { NULL, NULL }, 82}; 83 84int luaopen_md5(lua_State *L) { 85 lua_newtable(L); 86 luaL_setfuncs(L, md5lib_function_list, 0); 87 return 1; 88} 89 |