Alex Rivera | Logout

Wrapping a C library for Lua: how do I create nested tables of functions?

Asked 2012-03-02T03:05:07.837
10

The code related to this question is here: https://github.com/jchester/lua-polarssl/tree/master/src

Currently I'm trying to wrap one part of the PolarSSL library (http://polarssl.org) to give me access to SHA-512 HMACs (luacrypto does not provide this).

The API I'm aiming for is of the form:

a_sha512_hash = polarssl.hash.sha512('text')

or more fully

local polarssl = require 'polarssl'
local hash = polarssl.hash

a_sha512_hash = hash.sha512('test')

If you refer to polarssl.c in the link above, you'll see I've written functions that wrap PolarSSL code. Then I'm trying to build the function tables thus:

LUA_API int luaopen_polarssl( lua_State *L ) {
  static const struct luaL_Reg core[] = {
    { NULL, NULL }
  };

  static const struct luaL_Reg hash_functions[] = {
    { "sha512", hash_sha512 },
    { "sha384", hash_sha384 },
    { NULL, NULL }
  };

  static const struct luaL_Reg hmac_functions[] = {
    { "sha512", hmac_sha512 },
    { "sha384", hmac_sha384 },
    { NULL, NULL }
  };

  luaL_register( L, CORE_MOD_NAME, core );
  luaL_register( L, HASH_MOD_NAME, hash_functions );
  luaL_register( L, HMAC_MOD_NAME, hmac_functions );

  return 1;
}

Where CORE_MOD_NAME = 'polarssl', HASH_MOD_NAME = 'polarssl.hash', HMAC_MOD_NAME = 'polarssl.hmac'.

When I run a test script similar to the Lua code at the top of this question, I get this:

lua: test.lua:23: attempt to index global 'polarssl' (a nil value)
stack traceback:
    test.lua:23: in main chunk
    [C]: ?

I've tried looking for examples of how to achieve this module.submodule approach (eg naim vs luasockets), but everyone

Edit
Report

1 Answer

2

Not directly related to the question, but the following statement is not entirely true:

Currently I'm trying to wrap one part of the PolarSSL library (http://polarssl.org) to give me access to SHA-512 HMACs (luacrypto does not provide this).

I do not know which version of LuaCrypto are you referring to, but this LuaCrypto fork does provide SHA-512 HMACs, and also any other digest type supported by OpenSSL automatically. Just pass "sha512" as the digest type:

hmac.digest("sha512", message, key)

The documentation states only a part of the supported digest types, the complete list can be retrieved by calling crypto.list("digests").

table.foreach(crypto.list("digests"), print)

When I think about it, even original LuaCrypto should support SHA-512.

answered 2012-03-02T18:07:15.513

Your Answer