2021-10-24 11:46:30 -04:00
|
|
|
#include "bcrypt.js.h"
|
2021-01-02 13:10:00 -05:00
|
|
|
|
|
|
|
#include "ow-crypt.h"
|
|
|
|
|
2022-05-16 18:30:14 -04:00
|
|
|
#if defined(_WIN32)
|
|
|
|
#define WIN32_LEAN_AND_MEAN
|
|
|
|
#include <windows.h>
|
|
|
|
extern BOOLEAN NTAPI SystemFunction036(PVOID Buffer, ULONG BufferLength);
|
|
|
|
#else
|
2021-01-02 13:10:00 -05:00
|
|
|
#include <sys/random.h>
|
2022-05-16 18:30:14 -04:00
|
|
|
#endif
|
2021-01-02 13:10:00 -05:00
|
|
|
|
|
|
|
JSValue _crypt_hashpw(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv);
|
|
|
|
JSValue _crypt_gensalt(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv);
|
|
|
|
|
2021-10-24 11:46:30 -04:00
|
|
|
void tf_bcrypt_register(JSContext* context)
|
2021-10-10 17:51:38 -04:00
|
|
|
{
|
2021-01-02 13:10:00 -05:00
|
|
|
JSValue global = JS_GetGlobalObject(context);
|
|
|
|
JSValue bcrypt = JS_NewObject(context);
|
|
|
|
JS_SetPropertyStr(context, global, "bCrypt", bcrypt);
|
|
|
|
JS_SetPropertyStr(context, bcrypt, "hashpw", JS_NewCFunction(context, _crypt_hashpw, "hashpw", 2));
|
|
|
|
JS_SetPropertyStr(context, bcrypt, "gensalt", JS_NewCFunction(context, _crypt_gensalt, "gensalt", 0));
|
|
|
|
JS_FreeValue(context, global);
|
|
|
|
}
|
|
|
|
|
2021-10-10 17:51:38 -04:00
|
|
|
JSValue _crypt_hashpw(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
|
|
|
|
{
|
2021-01-02 13:10:00 -05:00
|
|
|
const char* key = JS_ToCString(context, argv[0]);
|
|
|
|
const char* salt = JS_ToCString(context, argv[1]);
|
|
|
|
char output[7 + 22 + 31 + 1];
|
|
|
|
char* hash = crypt_rn(key, salt, output, sizeof(output));
|
|
|
|
JSValue result = JS_NewString(context, hash);
|
|
|
|
JS_FreeCString(context, key);
|
|
|
|
JS_FreeCString(context, salt);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2021-10-10 17:51:38 -04:00
|
|
|
JSValue _crypt_gensalt(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
|
|
|
|
{
|
2021-01-02 13:10:00 -05:00
|
|
|
int length;
|
|
|
|
JS_ToInt32(context, &length, argv[0]);
|
|
|
|
char buffer[16];
|
2022-05-16 18:30:14 -04:00
|
|
|
#if defined(_WIN32)
|
|
|
|
ssize_t bytes = SystemFunction036(buffer, sizeof(buffer)) ? sizeof(buffer) : 0;
|
|
|
|
#else
|
2021-01-02 13:10:00 -05:00
|
|
|
ssize_t bytes = getrandom(buffer, sizeof(buffer), 0);
|
2022-05-16 18:30:14 -04:00
|
|
|
#endif
|
2021-01-02 13:10:00 -05:00
|
|
|
char output[7 + 22 + 1];
|
|
|
|
char* salt = crypt_gensalt_rn("$2b$", length, buffer, bytes, output, sizeof(output));
|
|
|
|
JSValue result = JS_NewString(context, salt);
|
|
|
|
return result;
|
|
|
|
}
|