* updated lskat (21.12.1 -> 21.12.2), untested
[t2-trunk.git] / misc / luabash / md5 / md5lib.c
blob436b0124e03470dac0729569ff22f60ba326c773
1 /*
2 * "derived from Cryptographic and Hash functions for Lua".
3 * "derived from dietlibc".
5 * --- T2-COPYRIGHT-NOTE-BEGIN ---
6 * This copyright note is auto-generated by ./scripts/Create-CopyPatch.
8 * T2 SDE: misc/luabash/md5/md5.c
9 * Copyright (C) 2006 The T2 SDE Project
10 * Copyright (C) 2006 Rene Rebe <rene@exactcode.de>
11 * Copyright (C) 2005 Roberto Ierusalimschy
13 * More information can be found in the files COPYING and README.
15 * This program is free software; you can redistribute it and/or modify
16 * it under the terms of the GNU General Public License as published by
17 * the Free Software Foundation; version 2 of the License. A copy of the
18 * GNU General Public License can be found in the file COPYING.
19 * --- T2-COPYRIGHT-NOTE-END ---
22 #include <stdlib.h>
23 #include <string.h>
24 #include <time.h>
26 #include <lua.h>
27 #include <lauxlib.h>
29 #include "md5.h"
31 #define LUA_FILEHANDLE "FILE*"
32 #define topfile(L) ((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))
34 static FILE *tofile (lua_State *L) {
35 FILE **f = topfile(L);
36 if (*f == NULL)
37 luaL_error(L, "attempt to use a closed file");
38 return *f;
42 /**
43 * Hash function. Returns a hash for a given string.
44 * @param message: arbitrary binary string.
45 * @return A 128-bit hash string.
47 static int lmd5 (lua_State *L) {
48 char buff[16];
49 size_t l;
51 const char* message = NULL;
52 FILE *f = NULL;
54 if (lua_isstring(L, -1))
55 message = luaL_checklstring(L, 1, &l);
56 else
57 f = tofile(L);
59 MD5_CTX context;
60 uint8_t digest [16];
61 ssize_t len;
62 char* t;
63 int i;
64 int c;
65 char buf [1024*4];
67 MD5Init ( &context );
69 if (f) {
70 while ( (len = fread ( buf, 1, sizeof(buf), f )) > 0 ) {
71 MD5Update ( &context, buf, len );
74 else
75 MD5Update ( &context, message, l);
78 MD5Final ( digest, &context );
80 lua_pushlstring(L, digest, 16L);
81 return 1;
88 ** Assumes the table is on top of the stack.
90 static void set_info (lua_State *L) {
91 lua_pushliteral (L, "_COPYRIGHT");
92 lua_pushliteral (L, "Copyright (C) 2003-2006 PUC-Rio");
93 lua_settable (L, -3);
94 lua_pushliteral (L, "_DESCRIPTION");
95 lua_pushliteral (L, "Basic cryptographic facilities");
96 lua_settable (L, -3);
97 lua_pushliteral (L, "_VERSION");
98 lua_pushliteral (L, "1.0.1");
99 lua_settable (L, -3);
103 static struct luaL_reg md5lib[] = {
104 {"dosum", lmd5},
105 {NULL, NULL}
109 int luaopen_md5_core (lua_State *L) {
110 luaL_openlib(L, "md5", md5lib, 0);
111 set_info (L);
112 return 1;