Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating secure random numbers in Rust

I can see I have to import like this:

use std::io::IoResult;
use std::num::{Int, ToPrimitive};
use std::rand::{OsRng, Rng};

Then make a new instance of OsRng, and try to generate a new u32 int from it

fn main() {

  let mut rng = OsRng::new();

  let num:u32 = rng.next_u32();
  println!("{}",num);
}

However I get the error type core::result::Result<std::rand::os::imp::OsRng, std::io::IoError> does not implement any method in scope named next_u32

But the rust documentation clearly says there is a function next_u32? http://doc.rust-lang.org/std/rand/struct.OsRng.html

What am I missing?

like image 299
leshow Avatar asked Dec 08 '14 16:12

leshow


2 Answers

Your problem here is that OsRng::new() does not return an OsRng instance, but an IoResult<OsRng>. Because the program can fail to fetch the OS random number generator.

A sample use would be:

use std::rand::{OsRng, Rng};

fn main() {

    let mut rng = match OsRng::new() {
        Ok(g) => g,
        Err(e) => panic!("Failed to obtain OS RNG: {}", e)
    };

    let num:u32 = rng.next_u32();
    println!("{}",num);
}
like image 156
Levans Avatar answered Oct 14 '22 15:10

Levans


A search for generating secure random numbers on Rust returned this SO question, but as a comment on the current answer states, Rust no longer includes random number generation in the standard library. Here's an updated example (as of Jan. 2017):

Cargo.toml

[dependencies]
rand = "0.3.0"

main.rs

extern crate rand;
use rand::{OsRng, Rng};

fn main() {
    let mut rng = OsRng::new().expect("Error opening random number generator");
    println!("Random: {}", rng.next_u32());
}

Useful reference: https://doc.rust-lang.org/rand/rand/index.html#cryptographic-security


Otherwise, using the code from the original answer gives this error:

error[E0432]: unresolved import `std::rand::Rng`
 --> src/main.rs:5:24
  |
5 | use std::rand::{OsRng, Rng};
  |                        ^^^ no `Rng` in `std::rand`

error: module `rand` is private
 --> src/main.rs:5:17
  |
5 | use std::rand::{OsRng, Rng};
  |                 ^^^^^

error: module `rand` is private
 --> src/main.rs:5:24
  |
5 | use std::rand::{OsRng, Rng};
  |                        ^^^

error: aborting due to 3 previous errors
like image 30
nitrogen Avatar answered Oct 14 '22 14:10

nitrogen