Crate crypt_guard

source ·
Expand description

§CryptGuard Programming Library

Crates.io MIT licensed Documentation Hashnode Blog GitHub Library

§Introduction

CryptGuard is a comprehensive cryptographic library, offering robust encryption and decryption capabilities. It integrates traditional cryptography with post-quantum algorithms, ensuring resilience against quantum computing threats. Designed for developers, CryptGuard empowers applications to withstand future digital security challenges. Embrace CryptGuard as your trusted ally in safeguarding privacy in the digital realm.

§Key Features and Capabilities

This library supports AES-256 and XChaCha20 encryption algorithms, providing a secure means to protect data. To cater to a variety of security requirements and operational contexts, CryptGuard integrates seamlessly with Kyber512, Kyber768, and Kyber1024 for encryption, ensuring compatibility with post-quantum cryptography standards.

For developers who require digital signing capabilities, CryptGuard incorporates Falcon and Dilithium algorithms, offering robust options for creating and verifying digital signatures. This feature is particularly crucial for applications that necessitate authenticity and integrity of data, ensuring that digital communications remain secure and verifiable.

An additional layer of security is provided through the appending of a HMAC (Hash-Based Message Authentication Code) to encrypted data. This critical feature enables the authentication of encrypted information, ensuring that any tampering with the data can be reliably detected. This HMAC attachment underscores CryptGuard’s commitment to comprehensive data integrity and security, offering developers and end-users peace of mind regarding the authenticity and safety of their data.

§Examples

§Encryption:

The encryption functions encrypt_msg, encrypt_data, and encrypt_file are specifically tailored for different types of data. Using distinct functions ensures that the correct methods and optimizations are applied depending on whether you’re encrypting raw bytes, structured data, or files. Each encryption function requires a new instance of the Kyber object, tailored for the type of encryption (Message, Data, Files), to guarantee that the cryptographic parameters are initialized correctly and securely for each session.

use crypt_guard::{*, error::*};
use std::{
    path::{Path, PathBuf},
    fs,
};

let message = "Hey, how are you doing?";
let passphrase = "Test Passphrase";
 
let (public_key, secret_key) = KyberKeypair!(1024);
 
// Creating new Kyber AES message instance
let mut encryptor = Kyber::<Encryption, Kyber1024, Message, AES>::new(public_key.clone(), None).expect("");
 
// Now are multiple options available:
// Using the Macro
let (encrypt_message, cipher) = Encryption!(public_key.clone(), 1024, message.clone().as_bytes().to_owned(), passphrase.clone(), AES).expect("");
 
// Using the encrypt_ functions:
 
// Message:
let (encrypt_message, cipher) = encryptor.encrypt_msg(message.clone(), passphrase.clone()).expect("");
 
// Data:
// Creating new Kyber AES data instance
let mut encryptor = Kyber::<Encryption, Kyber1024, Data, AES>::new(public_key.clone(), None).expect("");
let (encrypt_message, cipher) = encryptor.encrypt_data(message.clone().as_bytes().to_owned(), passphrase.clone()).expect("");
 
// Last but not least the encryption function for files:
fs::write(PathBuf::from("message.txt"), message.clone().as_bytes()).expect("");
 
// Creating new Kyber AES file instance
let mut encryptor = Kyber::<Encryption, Kyber1024, Files, AES>::new(public_key.clone(), None).expect("");
 
// Encrypt file macro:
let (encrypt_message, cipher) = EncryptFile!(public_key.clone(), 1024, PathBuf::from("message.txt"), passphrase.clone(), AES).expect("");
 
// Encrypt file function:
let (encrypt_message, cipher) = encryptor.encrypt_file(PathBuf::from("message.txt"), passphrase.clone()).expect("");
§Infos about XChaCha20 differences

XChaCha20, unlike AES, requires handling of a nonce (number used once) which must be generated during encryption and subsequently used during decryption. This introduces additional steps in the cryptographic process when using XChaCha20 compared to AES, which does not explicitly require nonce management by the user.

use crypt_guard::{*, error::*, KDF::*};
use std::{
    path::{Path, PathBuf},
    fs,
};

let (public_key, secret_key) = KyberKeypair!(768);

let message = "Hey, how are you doing?";
let passphrase = "Test Passphrase";
 
fs::write(PathBuf::from("message.txt"), message.clone().as_bytes()).expect("");

// You need to save the nonce when not using AES but XChaCha20 instead:
// Creating new Kyber XChaCha20 file encryption instance
let mut encryptor = Kyber::<Encryption, Kyber768, Files, XChaCha20>::new(public_key.clone(), None).expect("");
 
// Encrypt file
let (encrypt_message, cipher) = encryptor.encrypt_file(PathBuf::from("message.txt"), passphrase.clone()).expect("");

// Should be executed after encryption is already done, since doing it before that would trigger an error.
let nonce = encryptor.get_nonce().expect("").to_string(); 
 
// Creating new Kyber XChaCha20 file decryption instance (this time also adding the nonce beside the key)
let mut decryptor = Kyber::<Decryption, Kyber768, Files, XChaCha20>::new(secret_key.clone(), Some(nonce)).expect("");
 
// Decrypt message
let decrypt_message = decryptor.decrypt_file(PathBuf::from("message.txt.enc"), passphrase.clone(), cipher.clone()).expect("");

§Using Encryption and Decryption macros

Beside the main macros encrypt, decrypt, encrypt_file, decrypt_file, I’ve added the Encryption and Decryption macros. Instead of linking the encryption/ decryption instance, we define the macro by using Encryption!(public_key, keysize [ 1024 | 768 | 512 ] contents_bytes_vec, passphrase_as_str, [ AES | XChaCha20 ]) and get the content and ciphertext returned, or additionally when using XChaCha20, we also get the nonce.

use crypt_guard::{*, error::*};
use std::{
    fs::{self, File}, 
    marker::PhantomData,
    path::{PathBuf, Path},
    io::{Read, Write},
 
};
//use crypt_guard_proc::{*, log_activity, write_log};
use tempfile::{TempDir, Builder};
use crypt_guard::KeyControler::KeyControl;
 
//#[crypt_guard_proc]
#[activate_log("log.txt")]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _ = initialize_logger(); 
    let message = "Hey, how are you doing?";
    let passphrase = "Test Passphrase";
 
    let mut key_control = KeyControl::<KeyControKyber1024>::new();
    let _ = log_activity!("Starting with signing of the message.", "Test");
 
    // Generate key pair
    let (public_key, secret_key) = KyberKeypair!(1024);
 
    // Instantiate Kyber for encryption 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!    
    // Encrypt message
    let (encrypt_message, cipher) = Encryption!(public_key.clone(), 1024, message.as_bytes().to_owned(), passphrase.clone(), AES)?;
 
    key_control.set_ciphertext(cipher.clone()).unwrap();
    key_control.save(KeyTypes::Ciphertext, "./key".into()).unwrap();
 
    // Decrypt message
    let decrypt_message = Decryption!(secret_key, 1024, encrypt_message.clone(), passphrase.clone(), cipher, AES)?;
 
    let decrypted_text = String::from_utf8(decrypt_message).expect("Failed to convert decrypted message to string");
    write_log!();
    println!("{:?}", decrypted_text);
    Ok(())
}  

Re-exports§

Modules§

  • Functions for usage of falcon and dilithium
  • File and Key related functionalitys, enums structs and modules
  • Kyber key functionalitys
  • The cipher_aes module implements the AES (Advanced Encryption Standard) algorithm for secure data encryption and decryption, providing a robust symmetric key cryptography solution.
  • The cipher_xchacha module offers encryption and decryption functionalities using the XChaCha20 algorithm, extending ChaCha for higher nonce sizes and additional security.
  • Cryptographic related functionalitys, enums structs and modules
  • Error types
  • Functions for usage of kyber for key generation
  • Logging related functionalitys

Macros§

  • Macro for encryption of a file, taking a Kyber decryption instance, a PathBuf as well as a passphrase and ciphertext as arguments
  • Macro for decrypting and opening data, a 1024 falcon public key is required
  • Macro for dilithium keypair generation
  • Macro for encryption of a file, taking a Kyber decryption instance, a PathBuf as well as a passphrase and ciphertext as arguments
  • Function activating the log, it takes one arg: &str which represents the location of the logfile Macro for signing and encrypting data, a 1024 falcon secret key is required for signing
  • Macro for falcon keypair generation
  • Macro for kyber keypair generation

Structs§

  • AES: Kyber<ProcessStatus, KeySize, ContentStatus, AlgorithmParam: (used here)>
  • Data: Kyber<ProcessStatus, KeySize, ContentStatus: (used here), AlgorithmParam>
  • Decryption: Kyber<ProcessStatus: (used here), KeySize, ContentStatus, AlgorithmParam>
  • Encryption: Kyber<ProcessStatus: (used here), KeySize, ContentStatus, AlgorithmParam>
  • Files: Kyber<ProcessStatus, KeySize, ContentStatus: (used here), AlgorithmParam>
  • Implementation for Kyber 512 variant.
  • Implementation for Kyber 768 variant.
  • Implementation for Kyber 1024 variant.
  • A structure to manage cryptographic keys and operations for the Kyber algorithm. It encapsulates the public key, secret key, ciphertext, and shared secret.
  • Represents a generic Kyber structure with templated parameters for process status, Kyber size, content status, and algorithm parameter.
  • Kyber512: Kyber<ProcessStatus, KeySize: (used here), ContentStatus, AlgorithmParam>
  • Kyber768: Kyber<ProcessStatus, KeySize: (used here), ContentStatus, AlgorithmParam>
  • Kyber1024: Kyber<ProcessStatus, KeySize: (used here), ContentStatus, AlgorithmParam>
  • Represents the data structure for Kyber algorithm, including key and nonce.
  • Message: Kyber<ProcessStatus, KeySize, ContentStatus: (used here), AlgorithmParam>
  • XChaCha20: Kyber<ProcessStatus, KeySize, ContentStatus, AlgorithmParam: (used here)>

Enums§

Traits§

  • Defines the functionalities for cryptographic operations, providing abstract methods for encryption and decryption that need to be implemented by specific cryptographic algorithms.
  • Trait for Kyber cryptographic functions.
  • Trait for implementing key management functions. This trait provides an interface for key pair generation, encapsulation/decapsulation of secrets, and key manipulation (such as setting and getting key values).
  • Trait to specify Kyber size variants.

Attribute Macros§