-1

I'm trying to use ring::rand::Secure/SystemRandom to generate some secure random bytes:

let mut randoms: [u8; 10] = [0; 10];
let sr = ring::rand::SystemRandom::new();
sr.fill(&randoms); // Error: fill method not found in `SystemRandom`

Now i'm not sure why SystemRandom doesn't implement 'fill' - there's a fair bit of indirection in the ring library but I believe it should:

Firstly, SystemRandom implements sealed::SecureRandom:

impl sealed::SecureRandom for SystemRandom {
    #[inline(always)]
    fn fill_impl(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
        fill_impl(dest)
    }
}

Next, sealed::SecureRandom implements SecureRandom (i'm unsure why the need for generics here?):

impl<T> SecureRandom for T
where
    T: sealed::SecureRandom,
{
    #[inline(always)]
    fn fill(&self, dest: &mut [u8]) -> Result<(), error::Unspecified> {
        self.fill_impl(dest)
    }
}

And thus SystemRandom implements SecureRandom via the internal sealed::SecureRandom.

However it doesn't seem to compile, am i missing something important here?

Thanks

  • edit -

Turns out i had use ring::rand::SystemRandom but needed to also have use ring::rand::SecureRandom to make that function visible.

Now my problem is:

sr.fill(&randoms);
|        ^^^^^^^^ types differ in mutability
Chris
  • 39,719
  • 45
  • 189
  • 235
  • 1
    "I'm unsure why the need for generics here?" `sealed::SecureRandom` is a trait, not a type. The generics are needed for a [blanket implementation](https://stackoverflow.com/questions/39150216/implementing-a-trait-for-multiple-types-at-once) of `SecureRandom`. Essentially, it's saying: every type `T` that implements `sealed::SecureRandom` shall also implement `SecureRandom`, and here's how. – Thomas Feb 14 '21 at 16:26

1 Answers1

4

fill expects a mutable reference to randoms. So just change

sr.fill(&randoms);

to

sr.fill(&mut randoms);
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46