Skip to content

AES加解密 in Rust

use aes

toml
[dependencies]
aes="0.7.5"
hex="0.4.3"
block-modes="0.8.1"
hex-literal="0.3.3"
rust
mod aeshelper;

use aeshelper::AESHelper;
use hex_literal::hex;
use std::str;


fn main() {
    let message = String::from("xxxxxxxxxxxxxxxx");

    let key = hex!("000102030405060708090A0B0C0D0000102030405060708090A0B0C0D0E0FE0F");

    println!("Message: {}", message);

    let plaintext = message.as_bytes();

    let mut aes_helper = AESHelper::new( &key);
    let ciphertext = aes_helper.aes_encrypt(plaintext);
    println!("Ciphertext: {:?}", hex::encode(&ciphertext));

    let decrypted_ciphertext = aes_helper.aes_decrypt(&ciphertext);
    println!("Plaintext: {:?}", str::from_utf8(&decrypted_ciphertext).unwrap());
}
rust
use aes::Aes256;
use block_modes::block_padding::Pkcs7;
use block_modes::{BlockMode, Cbc};

type Aes256Cbc = Cbc<Aes256, Pkcs7>;

pub struct AESHelper {
    iv: Vec<u8>,
    key:  Vec<u8>,
}

impl AESHelper {

    pub fn new(key: &[u8]) -> AESHelper {
        AESHelper {
            key: key.to_vec(),
            iv: (&key[0..16]).to_vec(),
        }
    }

    pub fn aes_encrypt(&mut self, plaintext: &[u8]) -> Vec<u8> {
        let cipher = Aes256Cbc::new_from_slices(&self.key, &self.iv).unwrap();
        let pos = plaintext.len();
        let mut buffer = [0u8; 256];
        buffer[..pos].copy_from_slice(plaintext);
        let ciphertext = cipher.encrypt(&mut buffer, pos).unwrap();
        ciphertext.to_vec()
    }
    
    pub fn aes_decrypt(&mut self, ciphertext: &[u8]) -> Vec<u8> {
        let cipher = Aes256Cbc::new_from_slices(&self.key, &self.iv).unwrap();
        let mut buf = ciphertext.to_vec();
        let decrypted_ciphertext = cipher.decrypt(&mut buf).unwrap();
        decrypted_ciphertext.to_vec()
    }
}

use rust-crypto

toml
[dependencies]
hex = "0.4.3"
hex-literal = "0.3.4"
rust-crypto = "0.2.36"
rust
mod aeshelper;

use aeshelper::AESHelper;
use hex_literal::hex;
use std::str;

fn main() {
    let message = String::from("xxxxxxxxxxxxxxxx");

    let key = hex!("000102030405060708090A0B0C0D0000102030405060708090A0B0C0D0E0FE0F");

    println!("Message: {}", message);

    let plaintext = message.as_bytes();

    let mut aes_helper = AESHelper::new( &key);
    let ciphertext = aes_helper.encrypt_aes_256_cbc(plaintext).unwrap();
    println!("Ciphertext: {:?}", hex::encode(&ciphertext));

    let decrypted_ciphertext = aes_helper.decrypt_aes_256_cbc(&ciphertext).unwrap();
    println!("Plaintext: {:?}", str::from_utf8(&decrypted_ciphertext).unwrap());
}
rust
use crypto::buffer::{ReadBuffer, WriteBuffer};
use crypto::symmetriccipher;

pub struct AESHelper {
    iv: Vec<u8>,
    key: Vec<u8>,
}

impl AESHelper {

    pub fn new(key: &[u8]) -> AESHelper {
        AESHelper {
            key: key.to_vec(),
            iv: (&key[0..16]).to_vec(),
        }
    }

    pub fn encrypt_aes_256_cbc(&mut self, data: &[u8]) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
        //setup
        let mut final_result = Vec::<u8>::new();
        let mut read_buffer = crypto::buffer::RefReadBuffer::new(data);
        let mut buffer = [0; 4096];
        let mut write_buffer = crypto::buffer::RefWriteBuffer::new(&mut buffer);
        let mut encryptor = crypto::aes::cbc_encryptor(crypto::aes::KeySize::KeySize256,&self.key,&self.iv,crypto::blockmodes::PkcsPadding);
        loop {
            let result = encryptor.encrypt(&mut read_buffer, &mut write_buffer, true)?;
            final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().cloned(),);

            match result {
                crypto::buffer::BufferResult::BufferUnderflow => break,
                crypto::buffer::BufferResult::BufferOverflow => {}
            }
        }

        Ok(final_result)
    }
    
    pub fn decrypt_aes_256_cbc(&mut self, encrypted_data: &[u8]) -> Result<Vec<u8>, symmetriccipher::SymmetricCipherError> {
        let mut decryptor = crypto::aes::cbc_decryptor(crypto::aes::KeySize::KeySize256,&self.key,&self.iv,crypto::blockmodes::PkcsPadding);
        let mut final_result = Vec::<u8>::new();
        let mut read_buffer = crypto::buffer::RefReadBuffer::new(encrypted_data);
        let mut buffer = [0; 4096];
        let mut write_buffer = crypto::buffer::RefWriteBuffer::new(&mut buffer);

        loop {
            let result = decryptor.decrypt(&mut read_buffer, &mut write_buffer, true)?;
            final_result.extend(write_buffer.take_read_buffer().take_remaining().iter().cloned(),);
            match result {
                crypto::buffer::BufferResult::BufferUnderflow => break,
                crypto::buffer::BufferResult::BufferOverflow => {}
            }
        }

        Ok(final_result)
    }
}

Released under the MIT License.