Skip to content

Commit 4f86dc0

Browse files
committed
add retry limit to rd_rand_entropy
1 parent 4efc182 commit 4f86dc0

File tree

1 file changed

+16
-6
lines changed

1 file changed

+16
-6
lines changed

src/binary/entropy.rs

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,28 @@ fn rd_rand_entropy() -> [u8; 32] {
2929
// Check if the CPU supports `RDRAND`.
3030
if let Some(rd_rand) = RdRand::new() {
3131
for i in 0..4 {
32-
let value = loop {
33-
if let Some(value) = rd_rand.get_u64() {
34-
break value;
35-
}
36-
};
37-
entropy[i * 8..(i + 1) * 8].copy_from_slice(&value.to_ne_bytes());
32+
if let Some(value) = get_random_64(rd_rand) {
33+
entropy[i * 8..(i + 1) * 8].copy_from_slice(&value.to_ne_bytes());
34+
}
3835
}
3936
}
4037

4138
entropy
4239
}
4340

41+
/// Try to fetch a 64 bit random value with a retry count limit of 10.
42+
///
43+
/// This function is a port of the C implementation provided in Intel's Software Developer's Manual, Volume 1, 7.3.17.1.
44+
fn get_random_64(rd_rand: RdRand) -> Option<u64> {
45+
const RETRY_LIMIT: u32 = 10;
46+
for _ in 0..RETRY_LIMIT {
47+
if let Some(value) = rd_rand.get_u64() {
48+
return Some(value);
49+
}
50+
}
51+
None
52+
}
53+
4454
/// Gather entropy by reading the current time with the `RDTSC` instruction if it's available.
4555
///
4656
/// This function doesn't provide particulary good entropy, but it's better than nothing.

0 commit comments

Comments
 (0)