1 /*****************************************************************************
2 * rand.c : non-predictible random bytes generator
3 *****************************************************************************
4 * Copyright © 2007 Rémi Denis-Courmont
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20 *****************************************************************************/
30 #include <sys/types.h>
38 * Pseudo-random number generator using a HMAC-MD5 in counter mode.
39 * Probably not very secure (expert patches welcome) but definitely
40 * better than rand() which is defined to be reproducible...
44 static uint8_t okey[BLOCK_SIZE], ikey[BLOCK_SIZE];
46 static void vlc_rand_init (void)
48 #if defined (__OpenBSD__) || defined (__OpenBSD_kernel__)
49 static const char randfile[] = "/dev/random";
51 static const char randfile[] = "/dev/urandom";
53 uint8_t key[BLOCK_SIZE];
55 /* Get non-predictible value as key for HMAC */
56 int fd = open (randfile, O_RDONLY);
60 for (size_t i = 0; i < sizeof (key);)
62 ssize_t val = read (fd, key + i, sizeof (key) - i);
67 /* Precompute outer and inner keys for HMAC */
68 for (size_t i = 0; i < sizeof (key); i++)
70 okey[i] = key[i] ^ 0x5c;
71 ikey[i] = key[i] ^ 0x36;
78 void vlc_rand_bytes (void *buf, size_t len)
80 static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
81 static uint64_t counter = 0;
84 uint64_t stamp = NTPtime64 ();
90 pthread_mutex_lock (&lock);
94 pthread_mutex_unlock (&lock);
97 AddMD5 (&md, ikey, sizeof (ikey));
98 AddMD5 (&md, &stamp, sizeof (stamp));
99 AddMD5 (&md, &val, sizeof (val));
102 if (len < sizeof (md.p_digest))
104 memcpy (buf, md.p_digest, len);
108 memcpy (buf, md.p_digest, sizeof (md.p_digest));
109 len -= sizeof (md.p_digest);
110 buf = ((uint8_t *)buf) + sizeof (md.p_digest);
118 void vlc_rand_bytes (void *buf, size_t len)
125 if (len < sizeof (val))
127 memcpy (buf, &val, len);
131 memcpy (buf, &val, sizeof (val));