Skip to main content

rustfs_crypto/encdec/
decrypt.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#[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}