From f4a3bef33294814193d3433dcddec117e9ac73c7 Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Tue, 25 Aug 2020 17:08:00 +0200 Subject: Beispiel für bcrypt hinzugefügt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bcrypt-test.c | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/bcrypt-test.c b/bcrypt-test.c index b09dee6..2bbdfe7 100644 --- a/bcrypt-test.c +++ b/bcrypt-test.c @@ -1,11 +1,105 @@ #include #include +#include +#include +#include #include "lua-bcrypt/compat/include/pwd.h" +#define USER_DATABASE "./user.db" +#define SECURITY_LEVEL 12 + +static bool +valid_char(int ch) +{ + return isalnum(ch) || ch == '_' || ch == '-' || ch == '.'; +} + +/** + * Create a new user/password + * + * \param[in] username + * \param[in] password + * + * \return true on success (user was created) or false on error + */ +bool +create_user(const char *username, const char *password) +{ + // check for invalid characters in username + for ( const char *ptr = username; *ptr; ++ptr ) { + if ( !valid_char(*ptr) ) { + return false; + } + } + + FILE *db = fopen(USER_DATABASE, "a"); + if ( db == NULL ) { + return false; + } + + char hash[_PASSWORD_LEN + 1] = { 0 }; + + if ( bcrypt_newhash(password, SECURITY_LEVEL, hash, _PASSWORD_LEN) != 0 ) { + return false; + } + + fprintf(db, "%s|%s\n", username, hash); + fclose(db); + + return true; +} + +/** + * Check is a valid username/password exists in the user-database + * + * \param[in] username + * \param[in] password + * + * \return true, if the user was successfully authenticated, otherwise false + */ +bool +check_user(const char *username, const char *password) +{ + FILE *db = fopen(USER_DATABASE, "r"); + if ( db == NULL ) { + return false; + } + + const size_t username_length = strlen(username); + char line[256]; + + bool found = false; + while ( !found && fgets(line, sizeof line, db) ) { + line[strcspn(line, "\r\n")] = '\0'; // remove newline (if exists) + + if ( strncmp(line, username, username_length) != 0 ) { + continue; + } + + if ( line[username_length] != '|' ) { + continue; + } + + if ( bcrypt_checkpass(password, &line[username_length+1]) != 0 ) { + continue; + } + + // User successfully authenticated! + found = true; + } + + fclose(db); + + return found; +} + int main(void) { - puts("Hallo Welt..."); + if ( check_user("Thomas", "Passwort") ) { + puts("Benutzer erfolgreich überprüft!"); + } + return EXIT_SUCCESS; } -- cgit v1.3