Move the scheme related primitives to dedicated modules
This commit is contained in:
parent
382492e915
commit
a1bf9e0bcc
5 changed files with 73 additions and 66 deletions
18
src/scheme/blake3.rs
Normal file
18
src/scheme/blake3.rs
Normal file
|
@ -0,0 +1,18 @@
|
|||
pub(crate) fn blake3_derive(context: &str, ikm: &[u8]) -> Vec<u8> {
|
||||
blake3::derive_key(context, ikm).to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn blake3_derive() {
|
||||
assert_eq!(
|
||||
super::blake3_derive("this is a context", b"7b47db8f365e5b602fd956d35985e9e1"),
|
||||
vec![
|
||||
0xc4, 0xf4, 0x6c, 0xf2, 0x03, 0xd9, 0x2d, 0x7b, 0x72, 0xe8, 0xe7, 0x90, 0xa3, 0x62,
|
||||
0x2a, 0xf4, 0x3c, 0x2a, 0xab, 0x27, 0xc6, 0xb1, 0x8b, 0x46, 0x9d, 0x40, 0x61, 0x56,
|
||||
0x19, 0x76, 0x88, 0xc4
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
49
src/scheme/xchacha20poly1305.rs
Normal file
49
src/scheme/xchacha20poly1305.rs
Normal file
|
@ -0,0 +1,49 @@
|
|||
use crate::encryption::EncryptedData;
|
||||
use crate::error::Result;
|
||||
use chacha20poly1305::aead::{Aead, KeyInit, Payload};
|
||||
use chacha20poly1305::{Key, XChaCha20Poly1305, XNonce};
|
||||
|
||||
pub(crate) fn xchacha20poly1305_encrypt(
|
||||
key: &[u8],
|
||||
data: &[u8],
|
||||
aad: &str,
|
||||
) -> Result<EncryptedData> {
|
||||
// Adapt the key
|
||||
let key = Key::from_slice(key);
|
||||
|
||||
// Generate a nonce
|
||||
let mut nonce: [u8; 24] = [0; 24];
|
||||
getrandom::getrandom(&mut nonce)?;
|
||||
let nonce = XNonce::from_slice(&nonce);
|
||||
|
||||
// Prepare the payload
|
||||
let payload = Payload {
|
||||
msg: data,
|
||||
aad: aad.as_bytes(),
|
||||
};
|
||||
|
||||
// Encrypt the payload
|
||||
let cipher = XChaCha20Poly1305::new(key);
|
||||
let ciphertext = cipher.encrypt(nonce, payload)?;
|
||||
|
||||
// Return the result
|
||||
Ok(EncryptedData {
|
||||
nonce: nonce.to_vec(),
|
||||
ciphertext,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn xchacha20poly1305_decrypt(
|
||||
key: &[u8],
|
||||
encrypted_data: &EncryptedData,
|
||||
aad: &str,
|
||||
) -> Result<Vec<u8>> {
|
||||
let key = Key::from_slice(key);
|
||||
let nonce = XNonce::from_slice(&encrypted_data.nonce);
|
||||
let payload = Payload {
|
||||
msg: &encrypted_data.ciphertext,
|
||||
aad: aad.as_bytes(),
|
||||
};
|
||||
let cipher = XChaCha20Poly1305::new(key);
|
||||
Ok(cipher.decrypt(nonce, payload)?)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue