From 68bb993d1a8ea82becef89d0bb25f9fa8bbd0735 Mon Sep 17 00:00:00 2001 From: ThoNohT Date: Fri, 29 May 2026 20:01:05 +0200 Subject: [PATCH] Implement hashing of username and password --- Makefile | 4 ++-- src/userctl.c | 55 +++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index 6a466be..7832df3 100644 --- a/Makefile +++ b/Makefile @@ -10,13 +10,13 @@ LDFLAGS=-lm -luuid INCL_FLAGS=-I$(LIBWS)include -I$(LIBSHA) server: src/server.c $(LIBSHA_SRC) output - gcc $(CFLAGS) $(INCL_FLAGS) -o output/server src/server.c $(LIBWS_LIB) $(LDFLAGS) + gcc $(CFLAGS) $(INCL_FLAGS) -o output/server src/server.c $(LIBSHA_SRC) $(LIBWS_LIB) $(LDFLAGS) LDFLAGS2=-lm INCL_FLAGS2=-I$(LIBSHA) userctl: src/userctl.c $(LIBSHA_SRC) output - gcc $(CFLAGS) $(INCL_FLAGS2) -o output/userctl src/userctl.c $(LDFLAGS2) + gcc $(CFLAGS) $(INCL_FLAGS2) -o output/userctl src/userctl.c $(LIBSHA_SRC) $(LDFLAGS2) output: mkdir -p output diff --git a/src/userctl.c b/src/userctl.c index 0a1f67b..196f054 100644 --- a/src/userctl.c +++ b/src/userctl.c @@ -1,7 +1,58 @@ #include +#include +#define NOH_IMPLEMENTATION +#include "noh.h" + +static void show_usage(char *program_name, char *error) { + noh_log(NOH_INFO, "Usage:"); + noh_log(NOH_INFO, "%s username password", program_name); + noh_log(NOH_INFO, " username: The username of the user to register."); + noh_log(NOH_INFO, " password: The password of the user to register."); + noh_log(NOH_INFO, ""); + noh_log(NOH_ERROR, "%s", error); + exit(1); +} + +Noh_String hash_password(Noh_Arena *arena, Noh_String_View username, Noh_String_View password) { + // Build the sha input string. + Noh_String input = {0}; + noh_string_append_sv(&input, username); + noh_string_append_cstr(&input, "<><>"); + noh_string_append_sv(&input, password); + + // Calculate the hash. + SHA256_CTX ctx = {0}; + BYTE hash[32]; + sha256_init(&ctx); + sha256_update(&ctx, (BYTE*)input.elems, input.count); + sha256_final(&ctx, hash); + + // Build the result string. + noh_arena_save(arena); + Noh_String result = {0}; + for (int i = 0; i < 32; i++) { + noh_string_append_cstr(&result, noh_arena_sprintf(arena, "%02x", hash[i])); + } + noh_arena_reset(arena); + + return result; +} + +int main(int argc, char **argv) { + // Parse input parameters. + char *program_name = noh_shift_args(&argc, &argv); + + if (argc < 1) show_usage(program_name, "Username not provided."); + Noh_String_View username = noh_sv_from_cstr(noh_shift_args(&argc, &argv)); + + if (argc < 1) show_usage(program_name, "Password not provided."); + Noh_String_View password = noh_sv_from_cstr(noh_shift_args(&argc, &argv)); + + Noh_Arena arena = noh_arena_init(64 KB); + Noh_String result = hash_password(&arena, username, password); + noh_string_append_null(&result); + printf("%s\n", result.elems); -int main() { - printf("Hello, world!\n"); return 0; }