Created
October 29, 2024 10:43
-
-
Save vinicius73/7e1e91a142d1256efa850d6e9713eb78 to your computer and use it in GitHub Desktop.
encrypt_str and decrypt_str
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use base64::{engine::general_purpose, Engine as _}; | |
use crypto::aes::{cbc_decryptor, cbc_encryptor, KeySize}; | |
use crypto::blockmodes::PkcsPadding; | |
use crypto::buffer::{BufferResult, ReadBuffer, RefReadBuffer, RefWriteBuffer, WriteBuffer}; | |
use crate::errors::AppError; // use your own error type | |
pub fn encrypt_str<T: AsRef<str>>( | |
data_to_encrypt: T, | |
key: &[u8], | |
iv: &[u8], | |
) -> Result<String, AppError> { | |
let mut encryptor = cbc_encryptor(KeySize::KeySize256, key, iv, PkcsPadding); | |
let mut final_result = Vec::<u8>::new(); | |
let mut read_buffer = RefReadBuffer::new(data_to_encrypt.as_ref().as_bytes()); | |
let mut buffer = Vec::from(data_to_encrypt.as_ref().as_bytes()); | |
let mut write_buffer = RefWriteBuffer::new(&mut buffer); | |
loop { | |
let result = encryptor.encrypt(&mut read_buffer, &mut write_buffer, true)?; | |
final_result.extend( | |
write_buffer | |
.take_read_buffer() | |
.take_remaining() | |
.iter() | |
.copied(), | |
); | |
match result { | |
BufferResult::BufferUnderflow => break, | |
BufferResult::BufferOverflow => {} | |
} | |
} | |
Ok(general_purpose::STANDARD.encode(&final_result)) | |
} | |
pub fn decrypt_str<T: AsRef<str>>( | |
encrypted_data: T, | |
key: &[u8], | |
iv: &[u8], | |
) -> Result<String, AppError> { | |
let encrypted_data = general_purpose::STANDARD.decode(encrypted_data.as_ref())?; | |
let mut decrypt = cbc_decryptor(KeySize::KeySize256, key, iv, PkcsPadding); | |
let mut final_result = Vec::<u8>::new(); | |
let mut read_buffer = RefReadBuffer::new(encrypted_data.as_slice()); | |
let mut buffer = encrypted_data.clone(); | |
let mut write_buffer = RefWriteBuffer::new(&mut buffer); | |
loop { | |
let result = decrypt.decrypt(&mut read_buffer, &mut write_buffer, true)?; | |
final_result.extend( | |
write_buffer | |
.take_read_buffer() | |
.take_remaining() | |
.iter() | |
.copied(), | |
); | |
match result { | |
BufferResult::BufferUnderflow => break, | |
BufferResult::BufferOverflow => {} | |
} | |
} | |
let res = String::from_utf8(final_result)?; | |
Ok(res) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment