salt.rs (2443B)
1 // Copyright 2022 Adobe. All rights reserved. 2 // This file is licensed to you under the Apache License, 3 // Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) 4 // or the MIT license (http://opensource.org/licenses/MIT), 5 // at your option. 6 7 // Unless required by applicable law or agreed to in writing, 8 // this software is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or 10 // implied. See the LICENSE-MIT and LICENSE-APACHE files for the 11 // specific language governing permissions and limitations under 12 // each license. 13 14 /// The SaltGenerator trait always the caller to supply 15 /// a function to generate a salt value used when hashing 16 /// data. Providing a unique salt ensures a unique hash for 17 /// a given data set. 18 19 pub trait SaltGenerator { 20 /// generate a salt vector 21 fn generate_salt(&self) -> Option<Vec<u8>>; 22 } 23 24 /// NoSalt return a no salt option to a function 25 pub struct NoSalt {} 26 27 impl SaltGenerator for NoSalt { 28 fn generate_salt(&self) -> Option<Vec<u8>> { 29 None 30 } 31 } 32 33 /// const NoSalt instance that can be used when no salting is required 34 pub const NO_SALT: &NoSalt = &NoSalt {}; 35 36 /// Default salt generator 37 /// This generator uses OpenSSL to generate a 38 /// salt of the specified length (default 16 bytes) 39 pub struct DefaultSalt { 40 salt_len: usize, 41 } 42 43 impl DefaultSalt { 44 /// Set the length of the generated salt vector 45 #[allow(dead_code)] 46 pub fn set_salt_length(&mut self, len: usize) { 47 self.salt_len = len; 48 } 49 } 50 51 impl Default for DefaultSalt { 52 fn default() -> Self { 53 DefaultSalt { salt_len: 16 } 54 } 55 } 56 57 impl SaltGenerator for DefaultSalt { 58 fn generate_salt(&self) -> Option<Vec<u8>> { 59 #[cfg(feature = "openssl_sign")] 60 { 61 let mut salt = vec![0u8; self.salt_len]; 62 openssl::rand::rand_bytes(&mut salt).ok()?; 63 64 Some(salt) 65 } 66 #[cfg(all(not(feature = "openssl_sign"), target_arch = "wasm32"))] 67 { 68 let salt = crate::wasm::util::get_random_values(self.salt_len).ok()?; 69 70 Some(salt) 71 } 72 #[cfg(all(not(feature = "openssl_sign"), not(target_arch = "wasm32")))] 73 { 74 use rand::prelude::*; 75 76 let mut salt = vec![0u8; self.salt_len]; 77 let mut rng = rand_chacha::ChaCha20Rng::from_entropy(); 78 rng.fill_bytes(&mut salt); 79 80 Some(salt) 81 } 82 } 83 }