lua-bcrypt

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

main.c (1854B)


      1 /*
      2  * Copyright (c) 2021, 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 <lua.h>
     18 #include <lualib.h>
     19 #include <lauxlib.h>
     20 
     21 #include "bcrypt.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 * L ) {
     28 	const char * password = luaL_checkstring( L, 1 );
     29 	int log_rounds = lua_tointeger( L, 2 );
     30 
     31 	char hash[ _PASSWORD_LEN ];
     32 	int rv = bcrypt_newhash( password, log_rounds, hash, sizeof( hash ) );
     33 	if( rv != 0 ) {
     34 		lua_pushliteral( L, "bcrypt_newhash failed" );
     35 		return lua_error( L );
     36 	}
     37 
     38 	lua_pushstring( L, hash );
     39 
     40 	return 1;
     41 }
     42 
     43 static int luabcrypt_verify( lua_State * L ) {
     44 	const char * password = luaL_checkstring( L, 1 );
     45 	const char * goodhash = luaL_checkstring( L, 2 );
     46 
     47 	int ok = bcrypt_checkpass( password, goodhash ) == 0;
     48 	lua_pushboolean( L, ok );
     49 
     50 	return 1;
     51 }
     52 
     53 static const struct luaL_Reg luabcrypt_lib[] = {
     54 	{ "digest", luabcrypt_digest },
     55 	{ "verify", luabcrypt_verify },
     56 
     57 	{ NULL, NULL }
     58 };
     59 
     60 LUALIB_API int luaopen_bcrypt( lua_State * L ) {
     61 	luaL_newlib( L, luabcrypt_lib );
     62 	return 1;
     63 }