You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

91 lines
1.9 KiB
C

#include "owner.h"
#include "json/json.h"
#include "json/layout.h"
#include "sha256/sha256.h"
#include "form.h"
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#define OBJ_TYPE struct owner
static struct json_object_field owner_layout[] = {
{
.key = "salt",
.offset = offsetof( struct owner, password_salt ),
.required = true,
.type = &json_field_string
},
{
.key = "hash",
.offset = offsetof( struct owner, password_hash ),
.required = true,
.type = &json_field_string
},
JSON_FIELD_END,
};
#undef OBJ_TYPE
void* allocate( size_t s );
struct owner* owner_new()
{
struct owner* o = allocate(sizeof(struct owner));
json_read_object_layout_from_file( "data/owner.json", owner_layout, o );
return o;
}
void owner_free( struct owner* o )
{
if( !o ) { return; }
free(o->password_salt);
free(o->password_hash);
free(o);
}
void owner_save( struct owner* o )
{
json_write_object_layout_to_file( "data/owner.json", "\t", owner_layout, o );
}
bool owner_check_password( struct owner* o, const char* passwd )
{
char buffer[512];
snprintf( buffer, 512, "%s:%s", o->password_salt, passwd );
printf( "passwd='%s'\n", passwd );
char hash[65] = "";
sha256_easy_hash_hex( buffer, strlen(buffer), hash );
printf( "hash=%s\n", hash );
printf( "expt=%s\n", o->password_hash );
return 0 == strcmp(hash,o->password_hash);
}
void owner_set_password( struct owner* o, const char* passwd )
{
free(o->password_salt);
free(o->password_hash);
char* new_salt = o->password_salt = malloc(65);
memset(new_salt,0,65);
for( int i = 0; i < 64; ++i ) {
new_salt[i] = 'a' + (rand()%26);
}
new_salt[64] = '\0';
char buffer[512];
snprintf( buffer, 512, "%s:%s", new_salt, passwd );
char* new_hash = o->password_hash = malloc(65);
memset(new_hash,0,65);
sha256_easy_hash_hex( buffer, strlen(buffer), new_hash );
o->password_hash = new_hash;
o->password_salt = new_salt;
}