• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (C) 2022 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 use anyhow::{ensure, Result};
16 use bssl_ffi as bssl_sys;
17 
18 pub const ENTROPY_LEN: usize = bssl_sys::CTR_DRBG_ENTROPY_LEN as usize;
19 
20 pub type Entropy = [u8; ENTROPY_LEN];
21 
22 pub struct Drbg(*mut bssl_sys::CTR_DRBG_STATE);
23 
24 impl Drbg {
new(entropy: &Entropy) -> Result<Drbg>25     pub fn new(entropy: &Entropy) -> Result<Drbg> {
26         let p = unsafe { bssl_sys::CTR_DRBG_new(entropy.as_ptr(), std::ptr::null(), 0) };
27         ensure!(!p.is_null(), "CTR_DRBG_new failed");
28         Ok(Drbg(p))
29     }
30 
reseed(&mut self, entropy: &Entropy) -> Result<()>31     pub fn reseed(&mut self, entropy: &Entropy) -> Result<()> {
32         ensure!(
33             unsafe { bssl_sys::CTR_DRBG_reseed(self.0, entropy.as_ptr(), std::ptr::null(), 0) }
34                 == 1,
35             "CTR_DRBG_reseed failed"
36         );
37         Ok(())
38     }
39 
generate(&mut self, buf: &mut [u8]) -> Result<()>40     pub fn generate(&mut self, buf: &mut [u8]) -> Result<()> {
41         ensure!(
42             unsafe {
43                 bssl_sys::CTR_DRBG_generate(
44                     self.0,
45                     buf.as_mut_ptr(),
46                     buf.len(),
47                     std::ptr::null(),
48                     0,
49                 )
50             } == 1,
51             "CTR_DRBG_generate failed"
52         );
53         Ok(())
54     }
55 }
56 
57 impl Drop for Drbg {
drop(&mut self)58     fn drop(&mut self) {
59         unsafe {
60             bssl_sys::CTR_DRBG_free(self.0);
61         }
62     }
63 }
64 
65 unsafe impl Send for Drbg {}
66