If you need to encrypt or decrypt data using the Rust programming language, you can do it using the magic_crypt crate using a few lines of code. The example in this Rust tutorial explains how to encrypt and decrypt a string and print it to the screen afterwards.
Example Code: Encrypt A String With Rust
#[macro_use] extern crate magic_crypt;
use magic_crypt::MagicCryptTrait;
fn main() {
let mcrypt = new_magic_crypt!("magickey", 256); //Creates an instance of the magic crypt library/crate.
let encrypted_string = mcrypt.encrypt_str_to_base64("string to encrypt"); //Encrypts the string and saves it to the 'encrypted_string' variable.
println!("Encrypted String: {}", encrypted_string); //Print the encrypted string to see if it worked.
}
The first line inside the ‘main’ function creates an instance of the magic crypt library/crate called ‘mcrypt’. The second line runs the ‘encrypt_str_to_base64’ function to encrypt your string, and then stores it in the ‘encrypted_string’ variable. The third prints the now encrypted string to the console.
Example Code: Decrypt A String With Rust
To decrypt a string using Rust, you can use the ‘encrypt_str_to_base64‘ method in magic_crypt:
#[macro_use] extern crate magic_crypt;
use magic_crypt::MagicCryptTrait;
fn main() {
let mcrypt = new_magic_crypt!("magickey", 256); //Creates an instance of the magic crypt library/crate.
let encrypted_string = mcrypt.encrypt_str_to_base64("string to encrypt"); //Encrypts the string and saves it to the 'encrypted_string' variable.
println!("Encrypted String: {}", encrypted_string); //Print the encrypted string to see if it worked.
let decrypted_string = mcrypt.decrypt_base64_to_string(&encrypted_string).unwrap(); //Decrypts the string so we can read it.
println!("Decrypted String: {}", decrypted_string); //Print the human-readable, decrypted string.
}
The fourth line inside the main function decrypts the string we just encrypted, and stores it in the ‘decrypted_string’ variable. The fifth line prints the contents of that variable to the console.
Dependencies Required For This Tutorial
magic-crypt = “3.1.9”