rustfs_crypto/encdec/
decrypt.rs1#[cfg(any(test, feature = "crypto"))]
16pub fn decrypt_data(password: &[u8], data: &[u8]) -> Result<Vec<u8>, crate::Error> {
17 use crate::encdec::id::ID;
18 use crate::error::Error;
19 use aes_gcm::{Aes256Gcm, KeyInit as _};
20 use chacha20poly1305::ChaCha20Poly1305;
21
22 const HEADER_LENGTH: usize = 45;
23 if data.len() < HEADER_LENGTH {
24 return Err(Error::ErrUnexpectedHeader);
25 }
26
27 let (salt, id, nonce_slice) = (&data[..32], ID::try_from(data[32])?, &data[33..45]);
28 let body = &data[HEADER_LENGTH..];
29
30 match id {
31 ID::Argon2idChaCHa20Poly1305 => {
32 let key = id.get_key(password, salt)?;
33 decrypt(ChaCha20Poly1305::new_from_slice(&key)?, nonce_slice, body)
34 }
35 _ => {
36 let key = id.get_key(password, salt)?;
37 decrypt(Aes256Gcm::new_from_slice(&key)?, nonce_slice, body)
38 }
39 }
40}
41
42#[cfg(any(test, feature = "crypto"))]
43#[inline]
44fn decrypt<T: aes_gcm::aead::Aead>(stream: T, nonce: &[u8], data: &[u8]) -> Result<Vec<u8>, crate::Error> {
45 use crate::error::Error;
46 use aes_gcm::AeadCore;
47 use aes_gcm::aead::array::Array;
48 use core::convert::TryFrom;
49
50 let nonce_arr: Array<u8, <T as AeadCore>::NonceSize> =
51 Array::try_from(nonce).map_err(|_| Error::ErrDecryptFailed(aes_gcm::aead::Error))?;
52 stream.decrypt(&nonce_arr, data).map_err(Error::ErrDecryptFailed)
53}
54
55#[cfg(not(any(test, feature = "crypto")))]
56pub fn decrypt_data(_password: &[u8], _data: &[u8]) -> Result<Vec<u8>, crate::Error> {
57 Err(crate::Error::ErrCryptoDisabled)
58}