1 // Copyright 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 //! BoringSSL-based implementation of random number generation. 16 #[cfg(soong)] 17 use bssl_sys as ffi; 18 use kmr_common::crypto; 19 20 /// [`crypto::Rng`] implementation based on BoringSSL. 21 #[derive(Default)] 22 pub struct BoringRng; 23 24 impl crypto::Rng for BoringRng { add_entropy(&mut self, data: &[u8])25 fn add_entropy(&mut self, data: &[u8]) { 26 #[cfg(soong)] 27 // Safety: `data` is a valid slice. 28 unsafe { 29 ffi::RAND_seed(data.as_ptr() as *const libc::c_void, data.len() as libc::c_int); 30 } 31 #[cfg(not(soong))] 32 // Safety: `data` is a valid slice. 33 unsafe { 34 ffi::RAND_add( 35 data.as_ptr() as *const libc::c_void, 36 data.len() as libc::c_int, 37 data.len() as f64, 38 ); 39 } 40 } fill_bytes(&mut self, dest: &mut [u8])41 fn fill_bytes(&mut self, dest: &mut [u8]) { 42 openssl::rand::rand_bytes(dest).unwrap(); // safe: BoringSSL's RAND_bytes() never fails 43 } 44 } 45