Skip to content

Instantly share code, notes, and snippets.

@Lohann
Last active October 18, 2024 21:16
Show Gist options
  • Save Lohann/153ee52aa60fcee2aa11d68b40a5516e to your computer and use it in GitHub Desktop.
Save Lohann/153ee52aa60fcee2aa11d68b40a5516e to your computer and use it in GitHub Desktop.
// -- Cargo.toml --
// [dependencies]
// rand = { version = "0.8.5" }
// const-hex = { version = "1.13.1" }
use rand::prelude::*;
// Tamanho do secret e do vetor de inicialização.
const BLOCK_SIZE: usize = 16;
#[allow(clippy::manual_memcpy)]
fn encrypt(secret: &[u8; BLOCK_SIZE], iv: &[u8; BLOCK_SIZE], mensagem: &[u8]) -> Vec<u8> {
let mut encrypted = vec![0u8; mensagem.len() + BLOCK_SIZE];
for i in 0..iv.len() {
encrypted[i] = iv[i] ^ secret[i];
}
for i in 0..mensagem.len() {
let secret_index = i % BLOCK_SIZE;
encrypted[i + BLOCK_SIZE] = secret[secret_index] ^ mensagem[i] ^ encrypted[i];
}
encrypted
}
fn decrypt(secret: &[u8; BLOCK_SIZE], encrypted: &[u8]) -> Vec<u8> {
let mut decrypted = vec![0u8; encrypted.len()];
for i in 0..decrypted.len() {
let secret_index = i % BLOCK_SIZE;
decrypted[i] = secret[secret_index] ^ encrypted[i];
if i >= BLOCK_SIZE {
decrypted[i] ^= encrypted[i-BLOCK_SIZE];
}
}
decrypted
}
#[allow(clippy::unwrap_used)]
fn main() {
// Inicializa o gerador de números aleatórios
let mut rng = rand::thread_rng();
// 1. Cria um "secret" de 16 bytes aleatório
let secret = [0u8; BLOCK_SIZE];
rng.fill(&mut secret);
// 2. Cria um "initializaion vector" de 16 bytes
let mut iv = [0u8; BLOCK_SIZE];
rng.fill(&mut iv);
// Mensagem a ser encriptada
let mensagem = b"Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.";
// 3. Encripta a mensagem
let encrypted = encrypt(&secret, &iv, mensagem);
// 4. Decripta a mensagem
let decrypted = decrypt(&secret, &encrypted);
// Transforma os vetores de bytes em strings
let mensagem = String::from_utf8_lossy(mensagem);
let encrypted = const_hex::encode_prefixed(encrypted);
let decrypted = String::from_utf8_lossy(&decrypted[BLOCK_SIZE..]);
println!(" original: {mensagem}");
println!("encryptado: {encrypted}");
println!("decryptado: {decrypted}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment