Random hexadecimal

Python has a very convenient way to get cryptographically secure random hexadecimal by using; secrets.token_hex(n)

Wishing rust had a similar approach. Thereby minimizing code.

In Rust the following seems to work:

use rand::RngCore;

fn main() {
    let mut bytes = [0; n];
    rand::thread_rng().fill_bytes(&mut bytes);
    println!("{}", hex::encode(&bytes));

Are you asking for changes in the Rust language? Proposing an addition or something?

1 Like

Well, in my mind it was a wish for an addition to a similar solution as Pythons. Guess I didn't get that down in the post.

Rust has be reluctant to add RNG in the standard library since external libraries do the job, are pretty trivial to use and there is a high risk to bless an implementation that will be no longer cryptographically secure in a few years.


There are proposals to expose a getrandom-like API in std and make it similar to #[global_allocator]. I think it's the most we can include into std and only because randomness is already used internally by HashMap and std effectively includes its own copy of getrandom.

1 Like

Effectively importing an equivalent of ring::rand::SystemRandom - Rust into std?

A simple function will suffice, see the linked getrandom docs (it's a Rust crate, not the Linux API).

1 Like

Looks like some of you think this proposal is about randomness in itself. Its not.

My thinking is that Python devs found a very practical and efficient way to get random hexidecimal in one line: x = secrets.token_hex(n) That's all it takes. And its inbuilt in Python so installing a package/crate is not necessary.

Rust is in my opinion about writing code that is secure and makes sense. If the language handles this type of mundane coding than it will benefit the community. But I don't mind if this is handled by a crate. It would work the same way.

This forum is the internals forum, about the development and evolution of the language, compiler, and standard library. If you're not asking specifically for std availability, then the correct forum is the users forum.