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 it
8 * under the terms of the GNU Lesser General Public License as published by
9 * the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public License
18 * along with this program; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
20 *****************************************************************************/
26 #include <vlc_common.h>
33 #include <sys/types.h>
42 * Pseudo-random number generator using a HMAC-MD5 in counter mode.
43 * Probably not very secure (expert patches welcome) but definitely
44 * better than rand() which is defined to be reproducible...
48 static uint8_t okey
[BLOCK_SIZE
], ikey
[BLOCK_SIZE
];
50 static void vlc_rand_init (void)
52 uint8_t key
[BLOCK_SIZE
];
54 /* Get non-predictible value as key for HMAC */
55 int fd
= vlc_open ("/dev/urandom", O_RDONLY
);
59 for (size_t i
= 0; i
< sizeof (key
);)
61 ssize_t val
= read (fd
, key
+ i
, sizeof (key
) - i
);
66 /* Precompute outer and inner keys for HMAC */
67 for (size_t i
= 0; i
< sizeof (key
); i
++)
69 okey
[i
] = key
[i
] ^ 0x5c;
70 ikey
[i
] = key
[i
] ^ 0x36;
77 void vlc_rand_bytes (void *buf
, size_t len
)
79 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
80 static uint64_t counter
= 0;
82 uint64_t stamp
= NTPtime64 ();
87 struct md5_s mdi
, mdo
;
92 pthread_mutex_lock (&lock
);
97 AddMD5 (&mdi
, ikey
, sizeof (ikey
));
98 AddMD5 (&mdo
, okey
, sizeof (okey
));
99 pthread_mutex_unlock (&lock
);
101 AddMD5 (&mdi
, &stamp
, sizeof (stamp
));
102 AddMD5 (&mdi
, &val
, sizeof (val
));
104 AddMD5 (&mdo
, mdi
.buf
, 16);
109 memcpy (buf
, mdo
.buf
, len
);
113 memcpy (buf
, mdo
.buf
, 16);
115 buf
= ((uint8_t *)buf
) + 16;