Skip to main content

tss_esapi/context/tpm_commands/
random_number_generator.rs

1// Copyright 2021 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3use crate::{
4    structures::{Digest, SensitiveData},
5    tss2_esys::{Esys_GetRandom, Esys_StirRandom},
6    Context, Error, Result, ReturnCode, WrapperErrorKind as ErrorKind,
7};
8use log::error;
9use std::convert::{TryFrom, TryInto};
10use std::ptr::null_mut;
11
12impl Context {
13    /// Get a number of random bytes from the TPM and return them.
14    ///
15    /// # Errors
16    /// * if converting `num_bytes` to `u16` fails, a `WrongParamSize` will be returned
17    pub fn get_random(&mut self, num_bytes: usize) -> Result<Digest> {
18        let mut random_bytes_ptr = null_mut();
19        ReturnCode::ensure_success(
20            unsafe {
21                Esys_GetRandom(
22                    self.mut_context(),
23                    self.optional_session_1(),
24                    self.optional_session_2(),
25                    self.optional_session_3(),
26                    num_bytes
27                        .try_into()
28                        .map_err(|_| Error::local_error(ErrorKind::WrongParamSize))?,
29                    &mut random_bytes_ptr,
30                )
31            },
32            |ret| {
33                error!("Error in getting random bytes: {:#010X}", ret);
34            },
35        )?;
36        Digest::try_from(Context::ffi_data_to_owned(random_bytes_ptr)?)
37    }
38
39    /// Add additional information into the TPM RNG state
40    pub fn stir_random(&mut self, in_data: SensitiveData) -> Result<()> {
41        ReturnCode::ensure_success(
42            unsafe {
43                Esys_StirRandom(
44                    self.mut_context(),
45                    self.optional_session_1(),
46                    self.optional_session_2(),
47                    self.optional_session_3(),
48                    &in_data.into(),
49                )
50            },
51            |ret| {
52                error!("Error stirring random: {:#010X}", ret);
53            },
54        )
55    }
56}