General & Crypto
This commit is contained in:
parent
0bbcab5727
commit
02f94993c7
27 changed files with 1881 additions and 47 deletions
34
crypto/src/kdf.rs
Normal file
34
crypto/src/kdf.rs
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
use crate::error::CryptoError;
|
||||
use hkdf::Hkdf;
|
||||
use sha2::Sha256;
|
||||
|
||||
pub fn hkdf_expand(
|
||||
ikm: &[u8],
|
||||
salt: &[u8],
|
||||
info: &[u8],
|
||||
okm_len: usize,
|
||||
) -> Result<Vec<u8>, CryptoError> {
|
||||
let hk = Hkdf::<Sha256>::new(Some(salt), ikm);
|
||||
let mut okm = vec![0u8; okm_len];
|
||||
hk.expand(info, &mut okm)
|
||||
.map_err(|_| CryptoError::KdfError)?;
|
||||
Ok(okm)
|
||||
}
|
||||
|
||||
pub fn hkdf_extract(ikm: &[u8], salt: &[u8]) -> [u8; 32] {
|
||||
let (_, hk) = Hkdf::<Sha256>::extract(Some(salt), ikm);
|
||||
let mut okm = [0u8; 32];
|
||||
hk.expand(&[], &mut okm).expect("hkdf expand failed");
|
||||
okm
|
||||
}
|
||||
|
||||
pub fn derive_encryption_key(
|
||||
ikm: &[u8],
|
||||
salt: &[u8],
|
||||
context: &[u8],
|
||||
) -> Result<[u8; 32], CryptoError> {
|
||||
let key = hkdf_expand(ikm, salt, context, 32)?;
|
||||
let mut out = [0u8; 32];
|
||||
out.copy_from_slice(&key);
|
||||
Ok(out)
|
||||
}
|
||||
Loading…
Reference in a new issue