forked from watercoldyi/lua-md5
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lmd5.c
104 lines (96 loc) · 1.76 KB
/
lmd5.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include "lualib.h"
#include "lua.h"
#include "lauxlib.h"
#include "md5.h"
static int
linput(lua_State *L){
MD5_CTX *ctx = lua_touserdata(L,1);
int type = lua_type(L,2);
if(type == LUA_TSTRING){
size_t n = 0;
const char *s = lua_tolstring(L,2,&n);
MD5Update(ctx,(unsigned char*)s,n);
}
else if(type == LUA_TLIGHTUSERDATA){
luaL_checktype(L,3,LUA_TNUMBER);
void *s = lua_touserdata(L,2);
unsigned int n = lua_tointeger(L,3);
MD5Update(ctx,s,n);
}
return 0;
}
static int
lfinal(lua_State *L){
MD5_CTX *ctx = lua_touserdata(L,1);
MD5Final(ctx);
char md5[32];
MD5Hex(ctx,md5);
lua_pushlstring(L,md5,32);
return 1;
}
static int
lcreate(lua_State *L){
static luaL_Reg mf[]={
{"input",linput},
{"final",lfinal},
{NULL,NULL}
};
MD5_CTX *ctx = lua_newuserdata(L,sizeof(*ctx));
MD5Init(ctx);
if(luaL_newmetatable(L,"lmd5")){
luaL_newlib(L,mf);
lua_setfield(L,-2,"__index");
}
lua_setmetatable(L,-2);
return 1;
}
static int
lsumhex(lua_State *L){
size_t n = 0;
const char *s = lua_tolstring(L,1,&n);
if(n == 0){
lua_pushnil(L);
return 1;
}
MD5_CTX ctx;
MD5Init(&ctx);
MD5Update(&ctx,(unsigned char *)s,n);
MD5Final(&ctx);
char hex[32];
MD5Hex(&ctx,hex);
lua_pushlstring(L,hex,32);
return 1;
}
static int
lfile(lua_State *L){
const char *path = lua_tostring(L,1);
FILE *f = fopen(path,"rb");
if(f == NULL){
lua_pushnil(L);
return 1;
}
char buf[4096];
MD5_CTX ctx;
MD5Init(&ctx);
int n = 0;
while(n = fread(buf,1,4096,f)){
MD5Update(&ctx,(unsigned char*)buf,n);
}
fclose(f);
MD5Final(&ctx);
char hex[32];
MD5Hex(&ctx,hex);
lua_pushlstring(L,hex,32);
return 1;
}
int
luaopen_lmd5(lua_State *L){
static luaL_Reg f[]={
{"sumhex",lsumhex},
{"create",lcreate},
{"file",lfile},
{NULL,NULL}
};
luaL_newlib(L,f);
return 1;
}