Skip to main content

Cipher

Struct Cipher 

Source
pub struct Cipher { /* private fields */ }
Expand description

Provides encryption and decryption functions for AES in modes ECB, CTR, and GCM. Instantiated with an AES Key, which is expanded into round keys and stored in the instance.

§Examples

use aesp::{Key, Cipher};
 
// Instantiate random key:
let rk_256 = Key::rand_key_256()?;
 
// Instantiate AESP cipher using the key:
let cipher = Cipher::new(&rk_256);

Implementations§

Source§

impl Cipher

Source

pub fn new(key: &Key) -> Self

Generates round keys from provided key and stores in the returned instance.

Source

pub fn round_keys(&self) -> &[[u8; 16]]

Getter for internal round keys. Returned as a slice of 16-byte arrays.

Source

pub fn encrypt_ecb(&self, plaintext: &[u8]) -> Vec<u8>

Electronic codebook encryption.

Encrypts each 16-byte block entirely independently and chains them together. Pads input to a multiple of 16 bytes using PKCS#7 padding. Vulnerable to pattern emergence in the ciphertext.

§Examples
let plaintext = ("Hello, World!").as_bytes();
let ciphertext = cipher.encrypt_ecb(&plaintext);
Source

pub fn decrypt_ecb(&self, ciphertext: &[u8]) -> Result<Vec<u8>>

Electronic codebook decryption.

Assumes plaintext was PKCS#7 padded before encryption and unpads automatically. Throws error if last block does not match PKCS#7 format or input is not a multiple of 16 bytes.

§Examples
let plaintext = ("Hello, World!").as_bytes();
let ciphertext = cipher.encrypt_ecb(&plaintext);
let decrypted = cipher.decrypt_ecb(&ciphertext)?;
assert_eq!(decrypted, plaintext);
Source

pub fn encrypt_ctr(&self, plaintext: &[u8]) -> Result<Vec<u8>>

Counter mode encryption.

Generates a random 12-byte initialisation vector (IV). For each 16-byte block of plaintext:

  1. 4-byte counter is incremented (starts at zero).
  2. Counter is appended to 12-byte IV to form a 16-byte block.
  3. The IV || Counter block is encrypted using the round keys.
  4. The plaintext block is XOR’d with the encrypted counter block.

Important: the same IV must never be reused with the same key. 96 bits is sufficiently large to assume uniqueness when randomly generated.

Output is formatted as IV (12 bytes) || Ciphertext

§Examples
let plaintext = ("Hello, World!").as_bytes();
let ciphertext = cipher.encrypt_ctr(&plaintext)?;
Source

pub fn decrypt_ctr(&self, ciphertext: &[u8]) -> Result<Vec<u8>>

Counter mode decryption.

Assumes format matches output of encryption: IV (12 bytes) || Ciphertext

§Examples
let plaintext = ("Hello, World!").as_bytes();
let ciphertext = cipher.encrypt_ctr(&plaintext)?;
let decrypted = cipher.decrypt_ctr(&ciphertext)?;
assert_eq!(decrypted, plaintext);
Source

pub fn encrypt_gcm( &self, plaintext: &[u8], aad: Option<&[u8]>, ) -> Result<Vec<u8>>

Galois/counter mode encryption.

Encrypts using counter mode and generates a cryptographic tag to verify the message has not been modified.

Also accepts optional additional authenticated data (AAD), which is included in the computation of the tag but not encrypted.

Output is formatted as IV (12 bytes) || AAD length (4 bytes) || AAD || Ciphertext || Tag (16 bytes)

§Examples
let plaintext = ("Hello, World!").as_bytes();
let aad = ("Some data to be authenticated but not encrypted").as_bytes();

let ciphertext_with_aad = cipher.encrypt_gcm(plaintext, Some(aad))?;
let ciphertext_no_aad = cipher.encrypt_gcm(plaintext, None)?;
Source

pub fn decrypt_gcm( &self, ciphertext: &[u8], ) -> Result<(Vec<u8>, Option<Vec<u8>>)>

Galois/counter mode decryption.

Assumes input follows the same format as encryption: IV (12 bytes) || AAD length (4 bytes) || AAD || Ciphertext || Tag (16 bytes)

Returns:

  • (plaintext, AAD) if tag was authenticated and decryption was successful.
  • AuthFailed error if computed tag did not match input tag.
  • CounterOverflow error if more than 2^32 blocks were provided.
  • InvalidCiphertext error if ciphertext does not match expected format.
§Examples
let plaintext = ("Hello, World!").as_bytes();
let aad = ("Some data to be authenticated but not encrypted").as_bytes();

// Decryption with AAD
let ciphertext = cipher.encrypt_gcm(plaintext, Some(aad))?;
let (decrypted, returned_aad) = cipher.decrypt_gcm(&ciphertext)?;

assert_eq!(decrypted, plaintext);
assert_eq!(returned_aad, Some(aad.to_vec()));

// Decryption without AAD
let ciphertext = cipher.encrypt_gcm(plaintext, None)?;
let (_, returned_aad) = cipher.decrypt_gcm(&ciphertext)?;
assert!(returned_aad.is_none());

Trait Implementations§

Source§

impl Clone for Cipher

Source§

fn clone(&self) -> Cipher

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Cipher

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Cipher

Source§

fn eq(&self, other: &Cipher) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Cipher

Source§

impl StructuralPartialEq for Cipher

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V