[Toybox] Ok, what am I doing wrong here.

Rob Landley rob at landley.net
Tue Feb 4 12:24:17 PST 2025


I tried to chop the uuid code out into a standalone thingy to show 
somebody, and:

#include <stdio.h>
#include <sys/random.h>

// https://tools.ietf.org/html/rfc4122 section 4.4 "Algorithms for
// Creating a UUID from Truly Random or Pseudo-Random Numbers".
int main(void)
{
   char uuid[16], *out = uuid;
   int i;

   // "Set all the ... bits to randomly (or pseudo-randomly) chosen values".
   dprintf(2, "%d\n", getrandom(uuid, 16, 0));

/*
   // "Set the four most significant bits ... of the time_hi_and_version
   // field to the 4-bit version number [4]".
   uuid[6] = (uuid[6] & 0x0F) | 0x40;
   // "Set the two most significant bits (bits 6 and 7) of
   // clock_seq_hi_and_reserved to zero and one, respectively".
   uuid[8] = (uuid[8] & 0x3F) | 0x80;
*/
   // Emit hex with dashes
   for (i = 0; i<16; i++)
     out += sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
   *out = 0;
   puts(uuid);

   return 0;
}

landley at driftwood:~$ ./a.out
16
6d643634-3336-3334-2e
landley at driftwood:~$ ./a.out
16
ffffffa4666666-6666-71
landley at driftwood:~$ ./a.out
16
7e653635-3336-3335-2e
landley at driftwood:~$ ./a.out
16
ffffffaa666666-6666-71
landley at driftwood:~$ ./a.out
16
ffffffbd666666-6666-72
landley at driftwood:~$ ./a.out
16
ffffffcb666666-6666-73
landley at driftwood:~$ ./a.out
16
ffffffc4666666-6666-73
landley at driftwood:~$ ./a.out
16
ffffffe2666666-6666-75
landley at driftwood:~$ dd if=/dev/random bs=16 count=1 2>/dev/null | hd | 
head -n1
00000000  23 1a 69 b3 77 0c ed 26  84 79 f0 c2 7e cd 7c 0d 
|#.i.w..&.y..~.|.|
landley at driftwood:~$ dd if=/dev/random bs=16 count=1 2>/dev/null | hd | 
head -n1
00000000  7f 30 15 46 25 89 fd ab  08 9b d0 ae 95 2a 1e b7 
|.0.F%........*..|
landley at driftwood:~$ dd if=/dev/random bs=16 count=1 2>/dev/null | hd | 
head -n1
00000000  55 24 22 a6 2b e0 bb 5c  9a 40 44 c9 59 0f 6f d2 
|U$".+..\. at D.Y.o.|
landley at driftwood:~$ dd if=/dev/random bs=16 count=1 2>/dev/null | hd | 
head -n1
00000000  e5 35 b5 59 0f 16 b0 43  5a ed ba d3 3d 92 63 fd 
|.5.Y...CZ...=.c.|
landley at driftwood:~$ dd if=/dev/random bs=16 count=1 2>/dev/null | hd | 
head -n1
00000000  3c 10 65 52 db d2 1d 6f  a2 d4 e0 89 ac ed 73 aa 
|<.eR...o......s.|

Why is my getrandom() not random? I tried both getentropy() and 
getrandom(), on both glibc and musl toolchains. The output of 
/dev/random is properly random. It's gotta be something really stupid 
I'm not seeing...

Rob


More information about the Toybox mailing list