Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Centralize dependency on Rng instance #196

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion aead/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ aes-gcm = "^0.9.2"
aes-gcm-siv = "^0.10"
chacha20poly1305 = "^0.9"
generic-array = "^0.14.4"
rand = "^0.7"
tink-core = "^0.2"
tink-mac = "^0.2"
tink-proto = "^0.2"
2 changes: 1 addition & 1 deletion core/src/keyset/manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ impl Manager {

/// Generate a key id that has not been used by any key in the [`Keyset`](tink_proto::Keyset).
fn new_key_id(&self) -> KeyId {
let mut rng = rand::thread_rng();
let mut rng = crate::subtle::random::rng();

loop {
let ret = rng.gen::<u32>();
Expand Down
22 changes: 19 additions & 3 deletions core/src/subtle/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,32 @@

//! Utilities for random data.

use rand::{thread_rng, Rng};
/// Re-export the particular version of the `rand` crate whose types appear in the API.
pub use rand;

use rand::Rng;

/// Trait that encapsulates the required traits that a random number generator instance must
/// implement.
pub trait Generator: rand::RngCore + rand::CryptoRng {}

/// Blanket implementation: any type that is a [`rand::CryptoRng`] is automatically
/// suitable as a Tink [`Generator`].
impl<T> Generator for T where T: rand::RngCore + rand::CryptoRng {}

/// Return a random number generator suitable for cryptographic operation.
pub fn rng() -> Box<dyn Generator> {
Box::new(rand::thread_rng())
}

/// Return a vector of the given `size` filled with random bytes.
pub fn get_random_bytes(size: usize) -> Vec<u8> {
let mut data = vec![0u8; size];
thread_rng().fill(&mut data[..]);
rng().fill(&mut data[..]);
data
}

/// Randomly generate an unsigned 32-bit integer.
pub fn get_random_uint32() -> u32 {
thread_rng().gen()
rng().gen()
}
2 changes: 1 addition & 1 deletion signature/src/ed25519_signer_key_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl tink_core::registry::KeyManager for Ed25519SignerKeyManager {
}

fn new_key(&self, _serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> {
let mut csprng = rand::rngs::OsRng {};
let mut csprng = tink_core::subtle::random::rng();
let keypair = ed25519_dalek::Keypair::generate(&mut csprng);

let public_proto = tink_proto::Ed25519PublicKey {
Expand Down
1 change: 0 additions & 1 deletion streaming/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ categories = ["cryptography"]
aes = { version = "^0.7.4", features = ["ctr"] }
# Need the `std` feature for Error type conversion
aes-gcm = { version = "^0.9.2", features = ["std"] }
rand = "^0.7"
tink-core = "^0.2"
tink-mac = "^0.2"
tink-proto = "^0.2"
2 changes: 1 addition & 1 deletion tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ pub fn get_ecdsa_params(
/// Create an [`Ed25519PrivateKey`](tink_proto::Ed25519PrivateKey) with randomly generated key
/// material.
pub fn new_ed25519_private_key() -> tink_proto::Ed25519PrivateKey {
let mut csprng = rand::thread_rng();
let mut csprng = tink_core::subtle::random::rng();
let keypair = ed25519_dalek::Keypair::generate(&mut csprng);

let public_proto = tink_proto::Ed25519PublicKey {
Expand Down
10 changes: 6 additions & 4 deletions tests/tests/aead/subtle/chacha20poly1305_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
////////////////////////////////////////////////////////////////////////////////

use super::{chacha20poly1305_vectors::*, wycheproof::*};
use rand::{thread_rng, Rng};
use std::collections::HashSet;
use tink_aead::subtle;
use tink_core::{subtle::random::get_random_bytes, Aead};
use tink_core::{
subtle::random::{get_random_bytes, rand::Rng},
Aead,
};
use tink_tests::WycheproofResult;

#[test]
Expand Down Expand Up @@ -172,7 +174,7 @@ fn test_cha_cha20_poly1305_modify_ciphertext() {
.unwrap_or_else(|e| panic!("#{}: encrypt failed: {:?}", i, e));

if !aad.is_empty() {
let alter_aad_idx = thread_rng().gen_range(0, aad.len());
let alter_aad_idx = tink_core::subtle::random::rng().gen_range(0, aad.len());
aad[alter_aad_idx] ^= 0x80;
assert!(
ca.decrypt(&ct, &aad).is_err(),
Expand All @@ -182,7 +184,7 @@ fn test_cha_cha20_poly1305_modify_ciphertext() {
aad[alter_aad_idx] ^= 0x80;
}

let alter_ct_idx = thread_rng().gen_range(0, ct.len());
let alter_ct_idx = tink_core::subtle::random::rng().gen_range(0, ct.len());
ct[alter_ct_idx] ^= 0x80;
assert!(
ca.decrypt(&ct, &aad).is_err(),
Expand Down
10 changes: 6 additions & 4 deletions tests/tests/aead/subtle/xchacha20poly1305_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@
////////////////////////////////////////////////////////////////////////////////

use super::{wycheproof::*, xchacha20poly1305_vectors::*};
use rand::{thread_rng, Rng};
use std::collections::HashSet;
use tink_aead::subtle;
use tink_core::{subtle::random::get_random_bytes, Aead};
use tink_core::{
subtle::random::{get_random_bytes, rand::Rng},
Aead,
};
use tink_tests::WycheproofResult;

#[test]
Expand Down Expand Up @@ -173,7 +175,7 @@ fn test_x_cha_cha20_poly1305_modify_ciphertext() {
.unwrap_or_else(|e| panic!("#{}: encrypt failed: {:?}", i, e));

if !aad.is_empty() {
let alter_aad_idx = thread_rng().gen_range(0, aad.len());
let alter_aad_idx = tink_core::subtle::random::rng().gen_range(0, aad.len());
aad[alter_aad_idx] ^= 0x80;
assert!(
ca.decrypt(&ct, &aad).is_err(),
Expand All @@ -183,7 +185,7 @@ fn test_x_cha_cha20_poly1305_modify_ciphertext() {
aad[alter_aad_idx] ^= 0x80;
}

let alter_ct_idx = thread_rng().gen_range(0, ct.len());
let alter_ct_idx = tink_core::subtle::random::rng().gen_range(0, ct.len());
ct[alter_ct_idx] ^= 0x80;
assert!(
ca.decrypt(&ct, &aad).is_err(),
Expand Down
10 changes: 5 additions & 5 deletions tests/tests/signature/subtle/ed25519_signer_verifier_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use tink_tests::WycheproofResult;
#[test]
fn test_ed25519_deterministic() {
let data = get_random_bytes(20);
let mut csprng = rand::thread_rng();
let mut csprng = tink_core::subtle::random::rng();
let keypair = Keypair::generate(&mut csprng);

// Use the private key and public key directly to create new instances
Expand All @@ -46,7 +46,7 @@ fn test_ed25519_deterministic() {
#[test]
fn test_ed25519_verify_modified_signature() {
let data = get_random_bytes(20);
let mut csprng = rand::thread_rng();
let mut csprng = tink_core::subtle::random::rng();
let keypair = Keypair::generate(&mut csprng);

// Use the private key and public key directly to create new instances
Expand All @@ -73,7 +73,7 @@ fn test_ed25519_verify_modified_signature() {
#[test]
fn test_ed25519_verify_truncated_signature() {
let data = get_random_bytes(20);
let mut csprng = rand::thread_rng();
let mut csprng = tink_core::subtle::random::rng();
let keypair = Keypair::generate(&mut csprng);

// Use the private key and public key directly to create new instances
Expand All @@ -89,7 +89,7 @@ fn test_ed25519_verify_truncated_signature() {
#[test]
fn test_ed25519_verify_modified_message() {
let mut data = get_random_bytes(20);
let mut csprng = rand::thread_rng();
let mut csprng = tink_core::subtle::random::rng();
let keypair = Keypair::generate(&mut csprng);

// Use the private key and public key directly to create new instances
Expand All @@ -114,7 +114,7 @@ fn test_ed25519_verify_modified_message() {
}
#[test]
fn test_ed25519_sign_verify() {
let mut csprng = rand::thread_rng();
let mut csprng = tink_core::subtle::random::rng();
let keypair = Keypair::generate(&mut csprng);
let seed = keypair.secret.as_bytes().to_vec();

Expand Down
3 changes: 2 additions & 1 deletion tests/tests/streaming/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,8 @@ impl std::io::Read for PartialReader {
// when more data is available. This is valid for Rust's `std::io::Read`, but
// would not be valid for an `io::Writer` in Go.
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if rand::thread_rng().gen_range(0, 3) == 0 {
let mut csprng = tink_core::subtle::random::rng();
if csprng.gen_range(0, 3) == 0 {
// Randomly pretend to have been interrupted.
return Err(std::io::Error::new(
std::io::ErrorKind::Interrupted,
Expand Down