Make rand_bytes() work more like read(2).

This commit is contained in:
Dag-Erling Smørgrav 2018-04-25 18:23:21 +02:00
parent 5768034d36
commit 4576565fd1
4 changed files with 10 additions and 15 deletions

View file

@ -39,7 +39,7 @@ CRYB_BEGIN
const char *cryb_rand_version(void);
#define rand_bytes cryb_rand_bytes
int rand_bytes(uint8_t *, size_t);
ssize_t rand_bytes(uint8_t *, size_t);
CRYB_END

View file

@ -29,6 +29,8 @@
#include "cryb/impl.h"
#include <sys/types.h>
#include <stdint.h>
#include <string.h>
@ -87,7 +89,7 @@ oath_key_create(const char *label,
/* generate key data if necessary */
if (keydata == NULL) {
if (rand_bytes((uint8_t *)keybuf, keylen) != 1)
if (rand_bytes((uint8_t *)keybuf, keylen) != (ssize_t)keylen)
return (NULL);
keydata = keybuf;
}

View file

@ -41,24 +41,15 @@
* Working placeholder until we come up with a proper API and start adding
* more methods.
*/
int
ssize_t
rand_bytes(uint8_t *buf, size_t len)
{
ssize_t rlen;
int fd, serrno;
int fd;
if ((fd = open("/dev/random", O_RDONLY)) < 0)
return (-1);
if ((rlen = read(fd, buf, len)) < 0) {
serrno = errno;
rlen = read(fd, buf, len);
close(fd);
errno = serrno;
return (-1);
}
close(fd);
if (rlen != (ssize_t)len) {
errno = EIO;
return (-1);
}
return (0);
return (rlen);
}

View file

@ -29,6 +29,8 @@
#include "cryb/impl.h"
#include <sys/types.h>
/* gcc's <cstdint> is broken */
#include <stdint.h>
#include <cstring>