I have the following Rust code, the eventual goal of which is to generate a deterministic username given a public key:
use openssl::pkey::{PKey, Private};
use rand::{Rng, SeedableRng};
use std::convert::TryInto;
pub struct MyRng([u8; 32]);
impl SeedableRng for MyRng {
type Seed = [u8; 32];
fn from_seed(seed: Self::Seed) -> MyRng {
MyRng(seed)
}
}
fn generate_username(keypair: &PKey<Private>) {
let public_bytes: Vec<u8> = keypair.public_key_to_der().unwrap();
let public_bytes: [u8; 32] = public_bytes.try_into().unwrap();
let seeded_rng: MyRng = SeedableRng::from_seed(public_bytes);
let num = rand::thread_rng().gen_range(0..32);
}
Using rand::thread_rng()
to create a ThreadRng
allows me to create a random number without a seed. If I change the last line to seeded_rng.gen_range(0..32)
then I am told a method is not found, and the traits Rng
and RngCore
are not implemented. However, I am unsure how to go about implementing these traits.
How can I generate random numbers using a seed of [u8; 32]
? Also, are there any areas where my code could be improved idiomatically? (e.g. is it necessary for my to create my own struct?)
Aucun commentaire:
Enregistrer un commentaire