-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlmd5.c
133 lines (120 loc) · 2.41 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/*
* lmd5.c
* MD5 library for Lua 5.1 based on Rivest's API
* Luiz Henrique de Figueiredo <[email protected]>
* 28 Feb 2013 21:10:02
* This code is hereby placed in the public domain.
*/
#include <string.h>
#include "lua.h"
#include "lauxlib.h"
#include "lmd5.h"
#define MYVERSION MYNAME " library for " LUA_VERSION " / Feb 2013 / "\
"using " AUTHOR
#define MYTYPE MYNAME " context"
static MD5_CTX *Pget(lua_State *L, int i)
{
return luaL_checkudata(L,i,MYTYPE);
}
static MD5_CTX *Pnew(lua_State *L)
{
MD5_CTX *c=lua_newuserdata(L,sizeof(MD5_CTX));
luaL_getmetatable(L,MYTYPE);
lua_setmetatable(L,-2);
return c;
}
static int Lnew(lua_State *L) /** new() */
{
MD5_CTX *c=Pnew(L);
MD5Init(c);
return 1;
}
static int Lclone(lua_State *L) /** clone(c) */
{
MD5_CTX *c=Pget(L,1);
MD5_CTX *d=Pnew(L);
*d=*c;
return 1;
}
static int Lreset(lua_State *L) /** reset(c) */
{
MD5_CTX *c=Pget(L,1);
MD5Init(c);
lua_settop(L,1);
return 1;
}
static int Lupdate(lua_State *L) /** update(c,s,...) */
{
MD5_CTX *c=Pget(L,1);
int i,n=lua_gettop(L);
for (i=2; i<=n; i++)
{
size_t l;
const char *s=luaL_checklstring(L,i,&l);
MD5Update(c,s,l);
}
lua_settop(L,1);
return 1;
}
static int Ldigest(lua_State *L) /** digest(c or s,[raw]) */
{
unsigned char digest[N];
if (lua_isuserdata(L,1))
{
MD5_CTX c=*Pget(L,1);
MD5Final(digest,&c);
}
else
{
size_t l;
const char *s=luaL_checklstring(L,1,&l);
MD5_CTX c;
MD5Init(&c);
MD5Update(&c,s,l);
MD5Final(digest,&c);
}
if (lua_toboolean(L,2))
lua_pushlstring(L,(char*)digest,sizeof(digest));
else
{
char *digit="0123456789abcdef";
char hex[2*N],*h;
int i;
for (h=hex,i=0; i<N; i++)
{
*h++=digit[digest[i] >> 4];
*h++=digit[digest[i] & 0x0F];
}
lua_pushlstring(L,hex,sizeof(hex));
}
return 1;
}
static int Ltostring(lua_State *L) /** __tostring(c) */
{
MD5_CTX *c=Pget(L,1);
lua_pushfstring(L,"%s %p",MYTYPE,(void*)c);
return 1;
}
static const luaL_Reg R[] =
{
{ "__tostring", Ltostring},
{ "clone", Lclone },
{ "digest", Ldigest },
{ "new", Lnew },
{ "reset", Lreset },
{ "update", Lupdate },
{ NULL, NULL }
};
LUALIB_API int luaopen_md5(lua_State *L)
{
luaL_newmetatable(L,MYTYPE);
lua_setglobal(L,MYNAME);
luaL_register(L,MYNAME,R);
lua_pushliteral(L,"version"); /** version */
lua_pushliteral(L,MYVERSION);
lua_settable(L,-3);
lua_pushliteral(L,"__index");
lua_pushvalue(L,-2);
lua_settable(L,-3);
return 1;
}