trifid/trifid-api-old/src/crypto.rs

52 lines
1.8 KiB
Rust
Raw Normal View History

2023-11-19 03:51:45 +00:00
// trifid-api-old, an open source reimplementation of the Defined Networking nebula management server.
2023-04-04 13:56:05 +00:00
// Copyright (C) 2023 c0repwn3r
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
2023-05-11 00:32:19 +00:00
use crate::config::TrifidConfig;
2023-04-04 01:53:14 +00:00
use aes_gcm::aead::{Aead, Payload};
2023-05-11 00:32:19 +00:00
use aes_gcm::{Aes256Gcm, KeyInit, Nonce};
2023-04-04 01:53:14 +00:00
use rand::Rng;
2023-05-11 00:32:19 +00:00
use std::error::Error;
2023-04-04 01:53:14 +00:00
use trifid_pki::rand_core::OsRng;
pub fn get_cipher_from_config(config: &TrifidConfig) -> Result<Aes256Gcm, Box<dyn Error>> {
let key_slice = hex::decode(&config.crypto.data_encryption_key)?;
Ok(Aes256Gcm::new_from_slice(&key_slice)?)
}
2023-05-11 00:32:19 +00:00
pub fn encrypt_with_nonce(
plaintext: &[u8],
nonce: [u8; 12],
cipher: &Aes256Gcm,
) -> Result<Vec<u8>, aes_gcm::Error> {
2023-04-04 01:53:14 +00:00
let nonce = Nonce::from_slice(&nonce);
let ciphertext = cipher.encrypt(nonce, plaintext)?;
Ok(ciphertext)
}
2023-05-11 00:32:19 +00:00
pub fn decrypt_with_nonce(
ciphertext: &[u8],
nonce: [u8; 12],
cipher: &Aes256Gcm,
) -> Result<Vec<u8>, aes_gcm::Error> {
2023-04-04 01:53:14 +00:00
let nonce = Nonce::from_slice(&nonce);
let plaintext = cipher.decrypt(nonce, Payload::from(ciphertext))?;
Ok(plaintext)
}
pub fn generate_random_iv() -> [u8; 12] {
OsRng.gen()
2023-05-11 00:32:19 +00:00
}