| 1 | #include <string.h> |
| 2 | #include "kernelrandombytes.h" |
| 3 | #include "crypto_rng.h" |
| 4 | #include "randombytes.h" |
| 5 | |
| 6 | unsigned long long randombytes_calls = 0; |
| 7 | unsigned long long randombytes_bytes = 0; |
| 8 | |
| 9 | static unsigned int init = 0; |
| 10 | |
| 11 | static unsigned char g[crypto_rng_KEYBYTES]; |
| 12 | static unsigned char r[crypto_rng_OUTPUTBYTES]; |
| 13 | unsigned long long pos = crypto_rng_OUTPUTBYTES; |
| 14 | |
| 15 | void randombytes(unsigned char *x,unsigned long long xlen) |
| 16 | { |
| 17 | randombytes_calls += 1; |
| 18 | randombytes_bytes += xlen; |
| 19 | |
| 20 | if (!init) { |
| 21 | kernelrandombytes(g,sizeof g); |
| 22 | init = 1; |
| 23 | } |
| 24 | |
| 25 | #ifdef SIMPLE |
| 26 | |
| 27 | while (xlen > 0) { |
| 28 | if (pos == crypto_rng_OUTPUTBYTES) { |
| 29 | crypto_rng(r,g,g); |
| 30 | pos = 0; |
| 31 | } |
| 32 | *x++ = r[pos]; xlen -= 1; |
| 33 | r[pos++] = 0; |
| 34 | } |
| 35 | |
| 36 | #else /* same output but optimizing copies */ |
| 37 | |
| 38 | while (xlen > 0) { |
| 39 | unsigned long long ready; |
| 40 | |
| 41 | if (pos == crypto_rng_OUTPUTBYTES) { |
| 42 | while (xlen > crypto_rng_OUTPUTBYTES) { |
| 43 | crypto_rng(x,g,g); |
| 44 | x += crypto_rng_OUTPUTBYTES; |
| 45 | xlen -= crypto_rng_OUTPUTBYTES; |
| 46 | } |
| 47 | if (xlen == 0) return; |
| 48 | |
| 49 | crypto_rng(r,g,g); |
| 50 | pos = 0; |
| 51 | } |
| 52 | |
| 53 | ready = crypto_rng_OUTPUTBYTES - pos; |
| 54 | if (xlen <= ready) ready = xlen; |
| 55 | memcpy(x,r + pos,ready); |
| 56 | memset(r + pos,0,ready); |
| 57 | x += ready; |
| 58 | xlen -= ready; |
| 59 | pos += ready; |
| 60 | } |
| 61 | |
| 62 | #endif |
| 63 | |
| 64 | } |