tcp-chat/src/client/ClientCredentials.c
2025-11-09 18:39:50 +05:00

45 lines
1.6 KiB
C

#include "client.h"
#include "tlibc/collections/List.h"
void ClientCredentials_destroy(ClientCredentials* cred){
if(!cred)
return;
free(cred->username.data);
free(cred->user_data_key.data);
free(cred->token.data);
}
Result(void) ClientCredentials_tryConstruct(ClientCredentials* cred,
str username, str password)
{
Deferral(8);
memset(cred, 0, sizeof(ClientCredentials));
bool success = false;
Defer(if(!success) ClientCredentials_destroy(cred));
cred->username = str_copy(username);
// concat password and username
List(u8) data_to_hash = List_alloc_size(password.size + username.size + PASSWORD_HASH_SIZE);
Defer(free(data_to_hash.data));
List_push_size(&data_to_hash, password.data, password.size);
List_push_size(&data_to_hash, username.data, username.size);
// lvl 1 hash - is used as AES key for user data
cred->user_data_key = Array_alloc(u8, PASSWORD_HASH_SIZE);
hash_password(List_castTo_Array(data_to_hash), cred->user_data_key.data, PASSWORD_HASH_LVL_ROUNDS);
// concat lvl 1 hash to data_to_hash
List_push_size(&data_to_hash, cred->user_data_key.data, cred->user_data_key.size);
// lvl 2 hash - is used for authentification
cred->token = Array_alloc(u8, PASSWORD_HASH_SIZE);
hash_password(List_castTo_Array(data_to_hash), cred->token.data, PASSWORD_HASH_LVL_ROUNDS);
AESBlockEncryptor_construct(&cred->user_data_aes_enc, cred->user_data_key, AESBlockEncryptor_DEFAULT_CLASS);
AESBlockDecryptor_construct(&cred->user_data_aes_dec, cred->user_data_key, AESBlockDecryptor_DEFAULT_CLASS);
success = true;
Return RESULT_VOID;
}