lua-bcrypt

Secure password hashing for Lua
Log | Files | Refs | README

main.c (1900B)


      1 /*
      2  * Copyright (c) 2015, Michael Savage <mike@mikejsavage.co.uk>
      3  *
      4  * Permission to use, copy, modify, and/or distribute this software for any
      5  * purpose with or without fee is hereby granted, provided that the above
      6  * copyright notice and this permission notice appear in all copies.
      7  *
      8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
      9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
     11  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
     13  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
     14  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     15 */
     16 
     17 #include <pwd.h>
     18 
     19 #include <lua.h>
     20 #include <lualib.h>
     21 #include <lauxlib.h>
     22 
     23 #if LUA_VERSION_NUM < 502
     24 	#define luaL_newlib( L, l ) ( lua_newtable( L ), luaL_register( L, NULL, l ) )
     25 #endif
     26 
     27 static int luabcrypt_digest( lua_State * const L ) {
     28 	const char * const password = luaL_checkstring( L, 1 );
     29 	const int log_rounds = lua_tointeger( L, 2 );
     30 
     31 	char hash[ _PASSWORD_LEN ];
     32 
     33 	int rv = bcrypt_newhash( password, log_rounds, hash, sizeof( hash ) );
     34 
     35 	if( rv != 0 ) {
     36 		lua_pushliteral( L, "bcrypt_newhash failed" );
     37 
     38 		return lua_error( L );
     39 	}
     40 
     41 	lua_pushstring( L, hash );
     42 
     43 	return 1;
     44 }
     45 
     46 static int luabcrypt_verify( lua_State * const L ) {
     47 	const char * const password = luaL_checkstring( L, 1 );
     48 	const char * const goodhash = luaL_checkstring( L, 2 );
     49 
     50 	const int ok = !bcrypt_checkpass( password, goodhash );
     51 
     52 	lua_pushboolean( L, ok );
     53 
     54 	return 1;
     55 }
     56 
     57 static const struct luaL_Reg luabcrypt_lib[] = {
     58 	{ "digest", luabcrypt_digest },
     59 	{ "verify", luabcrypt_verify },
     60 	{ NULL, NULL },
     61 };
     62 
     63 LUALIB_API int luaopen_bcrypt( lua_State * const L ) {
     64 	luaL_newlib( L, luabcrypt_lib );
     65 
     66 	return 1;
     67 }