Skip to content

Commit

Permalink
V1.2.16
Browse files Browse the repository at this point in the history
Now contains implementation for AES_GCM_SIV
  • Loading branch information
mm9942 authored Jul 23, 2024
1 parent ec6c8d2 commit c2126be
Show file tree
Hide file tree
Showing 26 changed files with 2,036 additions and 82 deletions.
14 changes: 11 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
workspace = { members = ["crypt_guard_proc"] }
[package]
name = "crypt_guard"
version = "1.2.15"
version = "1.2.16"
edition = "2021"
description = "CryptGuardLib is a comprehensive Rust library designed for strong encryption and decryption, incorporating post-quantum cryptography to safeguard against quantum threats. It's geared towards developers who need to embed advanced cryptographic capabilities in their Rust applications."
license = "MIT"
Expand All @@ -10,8 +10,7 @@ repository = "https://github.com/mm9942/crypt_guard"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
aes = "0.8.3"
env = "0.0.0"
aes = "0.8.4"
hex = "0.4.3"
hmac = "0.12.1"
pqcrypto-falcon = { version = "0.3.0" }
Expand All @@ -25,6 +24,15 @@ chrono = "0.4.37"
lazy_static = "1.4.0"
crypt_guard_proc = { path = "./crypt_guard_proc", version = "0.1.0" }
zeroize = "1.8.1"
digest = "0.10.7"
sudo = "0.6.0"
sysinfo = "0.30.13"
xts-mode = "0.5.1"
block-padding = "0.3.3"
cbc = { version = "0.1.2", features = ["alloc", "std"] }
# ctr = "0.9.2"
generic-array = "1.1.0"
aes-gcm-siv = "0.11.1"

[dev-dependencies]
tempfile = "3.10.1"
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,19 @@ An additional layer of security is provided through the appending of a HMAC (Has

### Newest Features

**New AES mode:** We have implemented AES_GCM_SIV as a save variant since the AES variant manually implements an ECB block mode encryption, now using AES_GCM_SIV AEAD with the GCM_SIV block mode for encryption, with a randomly generated IV. We also added some functions for device lookup and are now implementing AES with the XTS block mode and system command device handling on Linux and Windows. It's also planned to implement the block modes: CBC and CTR. Use the AES_GCM_SIV implementation through the macro the same way you use XChaCha20.

**Encryption Macro for AES_GCM_SIV:** `let (encrypt_message, cipher, iv) = Encryption!(key.to_owned(), 1024, message.to_vec(), passphrase, AES_GCM_SIV);`

**Decryption Macro for AES_GCM_SIV:** `let decrypted_data = Decryption!(secret_key, [ 1024 | 768 | 512 ], data: Vec<u8>, passphrase: &str, cipher: Vec<u8>, Some(iv): Option<String>, AES_GCM_SIV)`

The macros now automatically zero out the used values to enhance data security during execution. For other execution methods, ensure data safety by manually addressing confidentiality. Developers using this crate are responsible for securely storing, hiding, and zeroing out keys in memory to protect encrypted information. As these values are generated, they fall outside my control for adding security measures. Note that the macros now require data ownership; to ensure safety, avoid cloning and instead use `.to_owned()`.

**Regarding the transfer of ownership, please take a look at the `src` folder in the Git repository. It contains the `tests` module folder and the test file `MacroTests.rs`, which uses the approach mentioned. The same is true for `KyberTests` and parts of the example `encrypt_aes.rs`.**

### Current Release

The present version, **1.2.15**, focuses on detailed cryptographic operations with enhanced data handling through automated macros. These macros simplify execution by wrapping up the necessary steps of definition, leveraging generic types and trait definitions. This version avoids asynchronous code, which will be reintroduced as a feature in future updates. Users preferring async implementation should use version 1.0.3. Note that version 1.0.3 uses the old syntax and has indirect documentation through the README, lacking Cargo's auto-generated documentation due to missing comments. Version 1.2.14 offers user-friendly syntax, reducing the need for extensive struct definitions, and supports Kyber1024, Kyber768, and Kyber512, along with logging capabilities.
The present version, **1.2.16**, focuses on detailed cryptographic operations with enhanced data handling through automated macros. These macros simplify execution by wrapping up the necessary steps of definition, leveraging generic types and trait definitions. This version avoids asynchronous code, which will be reintroduced as a feature in future updates. Users preferring async implementation should use version 1.0.3. Note that version 1.0.3 uses the old syntax and has indirect documentation through the README, lacking Cargo's auto-generated documentation due to missing comments. Version 1.2.14 offers user-friendly syntax, reducing the need for extensive struct definitions, and supports Kyber1024, Kyber768, and Kyber512, along with logging capabilities.

### Simplifying Encryption and Decryption with Macros

Expand Down
2 changes: 1 addition & 1 deletion crypt_guard_proc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "crypt_guard_proc"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
description = "CryptGuardProc is the proc macro crate related to CryptGuardLib, which is a comprehensive Rust library designed for strong encryption and decryption, incorporating post-quantum cryptography to safeguard against quantum threats. It's geared towards developers who need to embed advanced cryptographic capabilities in their Rust applications."
license = "MIT"
Expand Down
4 changes: 2 additions & 2 deletions crypt_guard_proc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub fn activate_log(args: TokenStream, input: TokenStream) -> TokenStream {
}

#[proc_macro]
pub fn ConcatKey(input: TokenStream) -> TokenStream {
pub fn ConcatCipher(input: TokenStream) -> TokenStream {
let inputs = parse_macro_input!(input as Expr);

let output = quote! {
Expand All @@ -36,7 +36,7 @@ pub fn ConcatKey(input: TokenStream) -> TokenStream {
}

#[proc_macro]
pub fn SplitKey(input: TokenStream) -> TokenStream {
pub fn SplitCipher(input: TokenStream) -> TokenStream {
let expr = parse_macro_input!(input as Expr);

let output = quote! {
Expand Down
17 changes: 5 additions & 12 deletions examples/encrypt_aes.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,6 @@
use crypt_guard::KeyControler::KeyControl;
use crypt_guard::{*, error::*};
use std::{
fs::{self, File},
marker::PhantomData,
path::{PathBuf, Path},
io::{Read, Write},

};
use tempfile::{TempDir, Builder};
use crypt_guard::*;
use std::fs::{File};

fn main() -> Result<(), Box<dyn std::error::Error>> {
let message = "Hey, how are you doing?";
Expand All @@ -23,17 +16,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut encryptor = Kyber::<Encryption, Kyber1024, File, AES>::new(public_key.clone(), None)?;

// Encrypt message
let (encrypt_message, cipher) = encryptor.encrypt_msg(message.clone(), passphrase.clone())?;
let (encrypt_message, cipher) = encryptor.encrypt_msg(message, passphrase)?;

key_control.set_ciphertext(cipher.clone()).unwrap();
key_control.save(KeyTypes::Ciphertext, "./key".into()).unwrap();

// Instantiate Kyber for decryption of a message with Kyber1024 and AES
// Fails when not using either of these properties since it would be the wrong type of algorithm, data, keysize or process!
let mut decryptor = Kyber::<Decryption, Kyber1024, File, AES>::new(secret_key, None)?;
let decryptor = Kyber::<Decryption, Kyber1024, File, AES>::new(secret_key, None)?;

// Decrypt message
let decrypt_message = decryptor.decrypt_msg(encrypt_message.clone(), passphrase.clone(), cipher)?;
let decrypt_message = decryptor.decrypt_msg(encrypt_message.clone(), passphrase, cipher)?;

let decrypted_text = String::from_utf8(decrypt_message).expect("Failed to convert decrypted message to string");
println!("{:?}", decrypted_text);
Expand Down
14 changes: 4 additions & 10 deletions examples/encrypt_xchacha.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
use crypt_guard::{*, error::*};
use std::{
fs::{self, File},
marker::PhantomData,
path::{PathBuf, Path},
io::{Read, Write},

};
use std::fs::{self, File};
use tempfile::{TempDir, Builder};


Expand All @@ -30,17 +24,17 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut encryptor = Kyber::<Encryption, Kyber768, File, XChaCha20>::new(public_key.clone(), None)?;

// Encrypt message
let (encrypt_message, cipher) = encryptor.encrypt_file(enc_path.clone(), passphrase.clone())?;
let (encrypt_message, cipher) = encryptor.encrypt_file(enc_path.clone(), passphrase)?;

let nonce = encryptor.get_nonce();

let _ = fs::remove_file(enc_path.clone());

// Instantiate Kyber for decryption of a file with Kyber768 and XChaCha20
// Fails when not using either of these properties since it would be the wrong type of algorithm, data, keysize or process!
let mut decryptor = Kyber::<Decryption, Kyber768, File, XChaCha20>::new(secret_key, Some(nonce?.to_string()))?;
let decryptor = Kyber::<Decryption, Kyber768, File, XChaCha20>::new(secret_key, Some(nonce?.to_string()))?;

// Decrypt message
let decrypt_message = decryptor.decrypt_file(dec_path.clone(), passphrase.clone(), cipher)?;
let decrypt_message = decryptor.decrypt_file(dec_path.clone(), passphrase, cipher)?;
Ok(())
}
1 change: 0 additions & 1 deletion examples/macro_example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ use crypt_guard::{
Encryption,
Decryption,
Kyber1024,
Message,
AES,
Kyber,
Data,
Expand Down
54 changes: 53 additions & 1 deletion src/Core/cipher_aes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ use aes::{
generic_array::GenericArray,
KeyInit
},
Aes256
Aes256,
Aes128,
};
use std::{
path::{PathBuf},
Expand All @@ -26,8 +27,13 @@ use std::{
fs
};

use cbc::{cipher::{KeyIvInit, BlockDecryptMut, BlockEncryptMut}, Encryptor as CbcEncryptor, Decryptor as CbcDecryptor};

use block_padding::Pkcs7;
use rand::Rng;

type Aes128CbcEnc = CbcEncryptor<Aes128>;
type Aes128CbcDec = CbcDecryptor<Aes128>;

/// Provides AES encryption functionality, handling cryptographic information and shared secrets.
impl CipherAES {
Expand Down Expand Up @@ -143,6 +149,52 @@ impl CipherAES {
Ok(encrypted_data)
}

fn generate_cbc_iv(&mut self) -> Result<Vec<u8>, CryptError> {
let mut iv = vec![0u8; 16];
let mut rng = rand::thread_rng();
rng.try_fill(&mut iv[..]);
Ok(iv)
}

/// Encrypts the provided data using AES-256 in CBC mode.
/// This function securely generates an IV for each encryption operation.
pub fn aes_cbc_encrypt(&mut self) -> Result<Vec<u8>, CryptError> {
let data = self.get_data()?;
let key = GenericArray::from_slice(&self.sharedsecret);
let mut iv = vec![0u8; 16]; // AES block size
rand::thread_rng().fill(&mut iv[..]);
let iv_arr = GenericArray::from_slice(&iv);

let cipher = Aes128CbcEnc::new(key, iv_arr);
let mut buffer = data.clone(); // Clone the data to a mutable buffer
let ciphertext = cipher.encrypt_padded_mut::<Pkcs7>(&mut buffer, data.len())
.map_err(|_| CryptError::EncryptionFailed)?;

// Prepend IV to the ciphertext to use it during decryption
let mut result = iv;
result.extend_from_slice(&ciphertext);
Ok(result)
}

/// Decrypts data encrypted using AES-256 in CBC mode.
/// Assumes the IV is prepended to the ciphertext.
pub fn aes_cbc_decrypt(&mut self, ciphertext: &[u8]) -> Result<Vec<u8>, CryptError> {
if ciphertext.len() < 16 {
return Err(CryptError::InvalidDataLength); // Ensure there's enough data for the IV
}

let (iv, encrypted_data) = ciphertext.split_at(16);
let key = GenericArray::from_slice(&self.sharedsecret);
let iv_arr = GenericArray::from_slice(iv);

let mut cipher = Aes128CbcDec::new(key, iv_arr);
let mut buffer = encrypted_data.to_vec();
cipher.decrypt_padded_mut::<Pkcs7>(&mut buffer)
.map_err(|_| CryptError::DecryptionFailed)?;

Ok(buffer)
}

/// Decrypts data using AES-256.
///
/// # Returns
Expand Down
Loading

0 comments on commit c2126be

Please sign in to comment.