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); const char *cryb_rand_version(void);
#define rand_bytes cryb_rand_bytes #define rand_bytes cryb_rand_bytes
int rand_bytes(uint8_t *, size_t); ssize_t rand_bytes(uint8_t *, size_t);
CRYB_END CRYB_END

View file

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

View file

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

View file

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