diff --git a/libs/lua-hash/Makefile b/libs/lua-hash/Makefile new file mode 100644 index 0000000..f71c34f --- /dev/null +++ b/libs/lua-hash/Makefile @@ -0,0 +1,36 @@ +include $(TOPDIR)/rules.mk + +PKG_NAME:=lua-hash +PKG_VERSION:=1 + +PKG_BUILD_DIR := $(BUILD_DIR)/$(PKG_NAME) + +include $(INCLUDE_DIR)/package.mk + +define Package/lua-hash + SECTION:=libs + CATEGORY:=Libraries + TITLE:=Lua hash library + DEPENDS:=+lua +libubox +endef + +define Build/Prepare + mkdir -p $(PKG_BUILD_DIR) + $(CP) ./src/* $(PKG_BUILD_DIR)/ +endef + +define Build/Configure +endef + +define Build/Compile + CFLAGS="$(TARGET_CFLAGS)" \ + CPPFLAGS="$(TARGET_CPPFLAGS)" \ + $(MAKE) -C $(PKG_BUILD_DIR) $(TARGET_CONFIGURE_OPTS) +endef + +define Package/lua-hash/install + $(INSTALL_DIR) $(1)/usr/lib/lua + $(CP) $(PKG_BUILD_DIR)/hash.so $(1)/usr/lib/lua/ +endef + +$(eval $(call BuildPackage,lua-hash)) diff --git a/libs/lua-hash/src/Makefile b/libs/lua-hash/src/Makefile new file mode 100644 index 0000000..cb868c5 --- /dev/null +++ b/libs/lua-hash/src/Makefile @@ -0,0 +1,6 @@ +all: hash.so + +CFLAGS += -Wall + +hash.so: hash.c + $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -shared -fPIC -o $@ $^ $(LDLIBS) -llua -lubox diff --git a/libs/lua-hash/src/hash.c b/libs/lua-hash/src/hash.c new file mode 100644 index 0000000..ce1d3fb --- /dev/null +++ b/libs/lua-hash/src/hash.c @@ -0,0 +1,47 @@ +#include + +#include +#include +#include +#include +#include + +#define MD5_DIGEST_LEN 16 +#define MD5_STRLEN (2*MD5_DIGEST_LEN+1) + +static int md5(lua_State *L) { + size_t len; + const char *input = lua_tolstring(L, 1, &len); + if (input == NULL) { + lua_pushstring(L, "first argument: should be the input string"); + lua_error(L); + __builtin_unreachable(); + } + + unsigned char digest[MD5_DIGEST_LEN]; + char output[MD5_STRLEN]; + + struct md5_ctx ctx; + md5_begin(&ctx); + md5_hash(input, len, &ctx); + md5_end(digest, &ctx); + + // fill the digest bytewise in the output string + int i; + for (i = 0; i < MD5_DIGEST_LEN; i++) { + sprintf(output + 2*i, "%02x", digest[i]); + } + + lua_pushstring(L, output); + return 1; +} + +static const luaL_Reg R[] = { + {"md5", md5}, + {NULL, NULL }, +}; + +LUALIB_API int luaopen_hash(lua_State *L) { + luaL_register(L, "hash", R); + return 1; +} diff --git a/libs/lua-hash/src/test.lua b/libs/lua-hash/src/test.lua new file mode 100644 index 0000000..615a82f --- /dev/null +++ b/libs/lua-hash/src/test.lua @@ -0,0 +1,3 @@ +#!/usr/bin/lua +hash = require "hash" +assert(hash.md5('testing') == 'ae2b1fca515949e5d54fb22b8ed95575')