opcua_crypto/random.rs
1// OPCUA for Rust
2// SPDX-License-Identifier: MPL-2.0
3// Copyright (C) 2017-2024 Adam Lock
4
5//! Module contains functions for creating cryptographically strong random bytes.
6
7use opcua_types::byte_string::ByteString;
8
9use rand;
10
11/// Fills the slice with cryptographically strong pseudo-random bytes
12pub fn bytes(bytes: &mut [u8]) {
13 use rand::RngCore;
14
15 let mut rng = rand::thread_rng();
16 rng.fill_bytes(bytes);
17}
18
19/// Create a byte string with a number of random characters. Can be used to create a nonce or
20/// a similar reason.
21pub fn byte_string(number_of_bytes: usize) -> ByteString {
22 let mut data = vec![0u8; number_of_bytes];
23 bytes(&mut data);
24 ByteString::from(data)
25}