1 /*****************************************************************************
2 * rand.c : non-predictible random bytes generator
3 *****************************************************************************
4 * Copyright © 2007 Rémi Denis-Courmont
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as published by
8 * the Free Software Foundation; either version 2.1 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
19 *****************************************************************************/
25 #include <vlc_common.h>
32 #include <sys/types.h>
41 * Pseudo-random number generator using a HMAC-MD5 in counter mode.
42 * Probably not very secure (expert patches welcome) but definitely
43 * better than rand() which is defined to be reproducible...
47 static uint8_t okey
[BLOCK_SIZE
], ikey
[BLOCK_SIZE
];
49 static void vlc_rand_init (void)
51 uint8_t key
[BLOCK_SIZE
];
53 /* Get non-predictible value as key for HMAC */
54 int fd
= vlc_open ("/dev/urandom", O_RDONLY
);
58 for (size_t i
= 0; i
< sizeof (key
);)
60 ssize_t val
= read (fd
, key
+ i
, sizeof (key
) - i
);
65 /* Precompute outer and inner keys for HMAC */
66 for (size_t i
= 0; i
< sizeof (key
); i
++)
68 okey
[i
] = key
[i
] ^ 0x5c;
69 ikey
[i
] = key
[i
] ^ 0x36;
76 void vlc_rand_bytes (void *buf
, size_t len
)
78 static pthread_mutex_t lock
= PTHREAD_MUTEX_INITIALIZER
;
79 static uint64_t counter
= 0;
81 uint64_t stamp
= NTPtime64 ();
86 vlc_hash_md5_t mdi
, mdo
;
87 uint8_t mdi_buf
[VLC_HASH_MD5_DIGEST_SIZE
];
88 uint8_t mdo_buf
[VLC_HASH_MD5_DIGEST_SIZE
];
90 vlc_hash_md5_Init (&mdi
);
91 vlc_hash_md5_Init (&mdo
);
93 pthread_mutex_lock (&lock
);
98 vlc_hash_md5_Update (&mdi
, ikey
, sizeof (ikey
));
99 vlc_hash_md5_Update (&mdo
, okey
, sizeof (okey
));
100 pthread_mutex_unlock (&lock
);
102 vlc_hash_md5_Update (&mdi
, &stamp
, sizeof (stamp
));
103 vlc_hash_md5_Update (&mdi
, &val
, sizeof (val
));
104 vlc_hash_md5_Finish (&mdi
, mdi_buf
, sizeof(mdi_buf
));
105 vlc_hash_md5_Update (&mdo
, mdi_buf
, sizeof(mdi_buf
));
106 vlc_hash_md5_Finish (&mdo
, mdo_buf
, sizeof(mdo_buf
));
108 memcpy (buf
, mdo_buf
, (len
< sizeof(mdo_buf
)) ? len
: sizeof(mdo_buf
));
110 if (len
< sizeof(mdo_buf
))
114 buf
= ((uint8_t *)buf
) + 16;