Skip to main content

Sm4CtrCipher

Struct Sm4CtrCipher 

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

Streaming SM4-CTR cipher.

Construct with Sm4CtrCipher::new, feed input/output buffer pairs through update, drop or finalize when done. Single struct serves both encrypt and decrypt (CTR is symmetric).

State machine:

  • counter: next 128-bit BE counter to evaluate.
  • leftover: the most recently evaluated keystream block.
  • leftover_pos: in 0..=16. Bytes [leftover_pos..16] of leftover are unconsumed keystream from a previous partial call; on next update they’re consumed first before the counter advances.

Internal invariant: when leftover_pos == 16, no carried-over keystream; the next byte requires a fresh encrypt_block of counter. Initial state is leftover_pos = 16 (no leftover).

Implementations§

Source§

impl Sm4CtrCipher

Source

pub fn new(key: &[u8; 16], counter: &[u8; 16]) -> Self

Construct from a 16-byte key and a 16-byte initial counter. Counter is treated as a 128-bit BE integer; per-block keystream is SM4_E(key, counter + i) for i = 0..N-1.

Source

pub fn update(&mut self, input: &[u8], output: &mut [u8])

Consume input and write input.len() bytes of output. The output buffer must be at least as long as the input; only the leading input.len() bytes are written.

§Panics

Panics if output.len() < input.len().

Source

pub fn finalize(self)

Finalize and drop the cipher. CTR has no padding to flush and no authenticity bits to emit, so this is a stateless drop. Provided for symmetry with super::cbc_streaming and so the call site reads intuitively.

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> 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> Same for T

Source§

type Output = T

Should always be Self
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.