Skip to navigation
Simple example to encrypt and decrypt with Rust cryptostream
24.04.21
1.Cargo.toml [dependencies] cryptostream = "0.1.0" base64 = "0.13.0" openssl = { version = "0.10" } 1. Source file: use base64::{encode,decode}; use cryptostream::{read, write}; use openssl::symm::{Cipher, Crypter, Mode}; use std::io::Read; use std::io::Write; pub fn test() { let t = "hello world".to_string(); let ct = encrypt(t); let s = decrypt(ct); println!("{:?}", s.to_string()); } pub fn encrypt(t: String) -> String { let src: &[u8] = &t.into_bytes(); let key: Vec<_> = decode("kjtbxCPw3XPFThb3mKmzfg==").unwrap(); let iv: Vec<_> = decode("dB0Ej+7zWZWTS5JUCldWMg==").unwrap(); let cipher = Cipher::aes_128_cbc(); let mut encrypted = Vec::new(); let mut bytes_written = 0; { let mut encryptor = write::Encryptor::new(&mut encrypted, cipher, &key,&iv).unwrap(); while bytes_written < src.len() { let write_bytes = encryptor.write(&src[bytes_written..]).unwrap(); bytes_written += write_bytes; } } let ct = encode(encrypted); return ct; } pub fn decrypt(ct: String) -> String { let src: Vec
= decode(ct).unwrap(); let key: Vec<_> = decode("kjtbxCPw3XPFThb3mKmzfg==").unwrap(); let iv: Vec<_> = decode("dB0Ej+7zWZWTS5JUCldWMg==").unwrap(); let mut decrypted = Vec::new(); { let mut decryptor = write::Decryptor::new(&mut decrypted, Cipher::aes_128_cbc(), &key,&iv).unwrap(); let mut bytes_decrypted = 0; while bytes_decrypted != src.len() { let write_count = decryptor.write(&src[bytes_decrypted..]).unwrap(); bytes_decrypted += write_count; } } let t = String::from_utf8_lossy(&decrypted); return t.into_owned(); // memory is allocated for a new stri }
https://docs.rs/cryptostream/0.3.1/cryptostream/
Reply
Anonymous
Information Epoch 1732552050
Save trees.
Home
Notebook
Contact us