diff options
Diffstat (limited to 'src/random.c')
-rw-r--r-- | src/random.c | 82 |
1 files changed, 81 insertions, 1 deletions
diff --git a/src/random.c b/src/random.c index df2d3ff..b409e6a 100644 --- a/src/random.c +++ b/src/random.c @@ -13,6 +13,13 @@ #include "random.h" + +struct Random { + FILE *const file_handle; +}; + + + int urandom_bytes(const size_t n, uint8_t (*const addr)[]) { int rc = -1; @@ -32,7 +39,7 @@ urandom_bytes(const size_t n, uint8_t (*const addr)[]) { goto out; } - const size_t read_count = fread(ret, 1, n, f); + const size_t read_count = fread(ret, 1U, n, f); if (ferror(f)) { logerr("fread(): %s", strerror(errno)); goto out; @@ -59,3 +66,76 @@ out: } return rc; } + +int +random_generate( + const struct Random *const r, + const size_t length, + uint8_t (*const out)[] +) { + int rc = -1; + + const size_t read_count = fread(out, 1U, length, r->file_handle); + if (ferror(r->file_handle)) { + logerr("fread(): %s", strerror(errno)); + goto out; + } + assert(read_count == length); + + rc = 0; +out: + return rc; +} + +int +random_new(const struct Random **const out) { + int rc = -1; + + const struct Random *ret = NULL; + FILE *f = NULL; + + ret = malloc(sizeof(*ret)); + if (ret == NULL) { + logerr("malloc(): %s", strerror(errno)); + goto out; + } + + f = fopen("/dev/urandom", "r"); + if (f == NULL) { + logerr("fopen(): %s", strerror(errno)); + goto out; + } + + memcpy((void *)ret, &(struct Random) { + .file_handle = f, + }, sizeof(*ret)); + *out = ret; + rc = 0; +out: + if (rc) { + random_free(&ret); + } + return rc; +} + +int +random_free(const struct Random **const r) { + if (r == NULL) { + return 0; + } + + if (*r == NULL) { + return 0; + } + + int rc = -1; + if (fclose((*r)->file_handle)) { + logerr("fclose(): %s", strerror(errno)); + goto out; + } + + rc = 0; +out: + freeit((void *)r); + return rc; +} |