How to create a ChaCha-based RNG in Rust - rust

I am trying to create a cryptographically secure random number generator in a Rust program based on ChaCha.
Currently I have
let mut rand = ChaChaRng::new_unseeded();
let rand_num = &rand.gen_range(1, 7);
The problem is that this results in the same random numbers being produced, because (I think) 'new_unseeded()' just uses 0 as the seed.
The documentation I found doesn't have any examples
Is there a method I could call instead so that rand will be seeded by the system in an appropriately random way? (Possibly something like the from_entropy() method?)

Looks like in the more recent versions of the rand crate, the ChaCha generator has moved out to a companion crate rand_chacha. Here's usage:
use rand_chacha::ChaChaRng;
use rand_chacha::rand_core::SeedableRng;
use rand::Rng;
fn main() {
let mut rand = ChaChaRng::from_entropy();
let rand_num = &rand.gen_range(1..7);
println!("{}", rand_num);
}

Related

How To Calculate Elliptic Curve Pairing Function Given BLS Public Key and Message

I'm trying to calculate curve pairings for the BLS cryptosystem given a public key and message. I generate the key with the bls_signatures crate and ultimately want to crunch e(pub_key, HashToCurve(message)) using the blstrs crate (since I found a pairing function there).
let priv_key = bls_signatures::PrivateKey::new(&[0_u8; 32]); // not secure, but repeatable
let mut buff = std::io::Cursor::new(vec![]);
let _bytes_written = priv_key
.public_key()
.as_affine()
.write_raw(&mut buff);
let mut pub_key_affine_bytes: Vec<u8> = buff.into_inner();
The first problem is that paired::bls12_381::G1Affine::write_raw() seems to be adding an extraneous zero to the beginning, giving me 97 bytes instead of 96:
assert!(pub_key_affine_bytes.len() == 97_usize); // instead of 96
assert!(pub_key_affine_bytes[0] == 0_u8); // regardless of key used... which seems wrong
I can "fix" it for now via let _ = pub_key_affine_bytes.remove(0); but when I try to convert to a blstrs::G1Affine (in the hopes of using blstrs::pairing() to reach my goal, but maybe there's a better way?), the blstrs library doesn't like it:
let pub_key_affine_bytes: [u8; 96] = pub_key_affine_bytes.try_into().unwrap();
assert!(blstrs::G1Affine::from_uncompressed(&pub_key_affine_bytes) == None); // instead of Some(_)
It's probably obvious by now, but I'm new to both Rust and this type of cryptography, so any guidance is welcome. How would you calculate pairings given a public key and message?
I just realized this simple solution as I was done looking through all the source code and writing up my original answer. It's as easy as changing the enabled features in your Cargo.toml to disable the usage of paired and enable blstrs to be used internally.
[package]
name = "blst_test"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
blstrs = "^0.3"
bls-signatures = {version="0.10.0", default-features= false, features=["blst"] }
With that fixed, the following works just fine
fn main() {
let priv_key = bls_signatures::PrivateKey::new(&[0_u8; 32]); // not secure, but repeatable
let affine = priv_key
.public_key()
.as_affine(); // blstrs::G1Affine, no longer from paired!
println!("{:?}", affine);
}

Is there an equivalent macro for linked list like vec! in Rust

So for easy initialization of a vector there is there vec! macro.
let mut vec_of_zeroes: Vec<usize> = vec![0;10];
I was wondering if there was an easy standard macro for initializing a linked list too?
use std::collections::LinkedList;
let mut list_of_zeroes: LinkedList<usize> = /*macro here?*/;
If not, no worries. Thanks for you time.
No, there is no such macro in the standard library. Indeed, there is no analogous macro for any other data structure, even HashMap / BTreeMap, which are much more frequently used.
However, the crate velcro provides a linked_list! macro that does what you want (and has some other neat features).
Note that std::collections::LinkedList lacks some features that make linked lists attractive - there is no cursor-based API, for instance. In most cases you should probably use Vec or VecDeque instead.
There is no linked list macro, but you could use the .extend() method to achieve something similar:
use std::collections::LinkedList;
fn main() {
let mut a: LinkedList<u32> = LinkedList::new();
a.extend(&[0; 10]);
println!("{:?}", a);
}
Playground
If you want to have a single line initialization, you could use some other iterator methods as suggested by #Stargateur in the comments. This method also allows the variable to be immutable, if you wanted that for some reason.
use std::collections::LinkedList;
fn main() {
let a: LinkedList<u32> = [0; 10].iter().copied().collect();
println!("{:?}", a);
}
Playground

Converting between extprim::u128::u128 and primitive u128 in Rust?

I'm working with an old Rust module that uses the extprim crate to provide a u128 type.
I'm trying to use this with a newer crate that uses Rust's primitive u128 type (available since Rust 1.26).
What's an efficient way to convert back and forth between these two types?
Update:
When your rustc version is greater than 1.26.0 the From trait is implemented and you can use into respectively from easily.
For a lower version than that see below.
As a note: "The most efficient way" is very subjective.
I would use the low64() and high64() methods to generate a rust u128.
extern crate extprim; // 1.6.0
use extprim::u128;
fn main() {
let number = u128::u128::from_parts(6_692_605_942, 14_083_847_773_837_265_618);
println!("{:?}", number);
// going forth
let real_number = u128::from(number.high64()) << 64 | u128::from(number.low64());
println!("{:?}", number);
assert_eq!(number.to_string(), real_number.to_string());
// and back
let old_number = u128::u128::from_parts((real_number >> 64) as u64, (real_number) as u64);
assert_eq!(number, old_number);
}
(playground)
Since you can't compare both directly, I used the to_string() function to convert them to a string and compare those.

Is there a more idiomatic way to initialize an array with random numbers than a for loop?

Is there an idiomatic way of initialising arrays in Rust. I'm creating an array of random numbers and was wondering if there is a more idiomatic way then just doing a for loop. My current code works fine, but seems more like C than proper Rust:
let mut my_array: [u64; 8] = [0; 8];
for i in 0..my_array.len() {
my_array[i] = some_function();
}
Various sized arrays can be directly randomly generated:
use rand; // 0.7.3
fn main() {
let my_array: [u64; 8] = rand::random();
println!("{:?}", my_array);
}
Currently, this only works for arrays of size from 0 to 32 (inclusive). Beyond that, you will want to see related questions:
How can I initialize an array using a function?
What is the proper way to initialize a fixed length array?
The other solution is nice and short, but does not apply to the case where you need to initialize an array of random numbers in a specific range. So, here's an answer that addresses that case.
use rand::{thread_rng, Rng};
fn main() {
let a = [(); 8].map(|_| thread_rng().gen_range(0.0..1.0));
println!("The array of random float numbers between 0.0 and 1.0 is: {:?}", a);
}
I would be happy to know if there's a better (shorter and more efficient) solution than this one.

What is the stable alternative of to_string()

I'm working my way through the rust book. In the Strings chapter a lot of the examples use to_string() which my version of the compiler(rustc 1.0.0-dev) gives the following warning
strings.rs:3:23: 3:34 warning: use of unstable item, #[warn(unstable)] on by default
strings.rs:3 let mut s = "Hello".to_string();
Code:
fn main() {
let mut s = "Hello".to_string();
println!("{}", s);
}
I understand from this question that this is because the API is likely to change, but I would like to know what I should use instead if I want to convert a string slice (str&) to a String
You can work around these things, e.g. format!("Hello"), but I really wouldn’t bother for the moment.

Resources