1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2022 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.
// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.
use rand_chacha::rand_core::{RngCore, SeedableRng};
/// The SaltGenerator trait always the caller to supply
/// a function to generate a salt value used when hashing
/// data. Providing a unique salt ensures a unique hash for
/// a given data set.
pub trait SaltGenerator {
/// generate a salt vector
fn generate_salt(&self) -> Option<Vec<u8>>;
}
/// Default salt generator
/// This generator uses OpenSSL to generate a
/// salt of the specified length (default 16 bytes)
pub struct DefaultSalt {
salt_len: usize,
}
impl DefaultSalt {
/// Set the length of the generated salt vector
#[allow(dead_code)]
pub fn set_salt_length(&mut self, len: usize) {
self.salt_len = len;
}
}
impl Default for DefaultSalt {
fn default() -> Self {
DefaultSalt { salt_len: 16 }
}
}
impl SaltGenerator for DefaultSalt {
fn generate_salt(&self) -> Option<Vec<u8>> {
let mut salt = vec![0u8; self.salt_len];
let mut rng = rand_chacha::ChaCha20Rng::from_os_rng();
rng.fill_bytes(&mut salt);
Some(salt)
}
}