1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
//! The `ChaCha20` Stream Cipher
mod key;
pub mod state;
pub use key::{Key, KeyRef, GenericKey};
use core::fmt;
use wolf_crypto_sys::{
ChaCha,
wc_Chacha_SetKey, wc_Chacha_SetIV,
wc_Chacha_Process
};
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::addr_of_mut;
use crate::buf::{GenericIv, U12};
use crate::opaque_res::Res;
use crate::{can_cast_u32, const_can_cast_u32, lte, Unspecified};
use state::{State, CanProcess, Init, NeedsIv, Ready, Streaming};
macro_rules! impl_fmt {
($(#[$meta:meta])* $trait:ident for $state:ident) => {
impl fmt::$trait for ChaCha20<$state> {
$(#[$meta])*
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(concat!("ChaCha20<", stringify!($state), "> { ... }"))
}
}
};
($state:ident) => {
impl_fmt! { Debug for $state }
impl_fmt! {
#[inline]
Display for $state
}
};
}
/// The `ChaCha20` Stream Cipher
///
/// # Warning
///
/// `ChaCha20` alone does not ensure that ciphertexts is authentic, unless you have a reason
/// for using this directly, it is generally recommended to use `ChaCha20-Poly1305`.
///
/// # Generic `S`
///
/// This `ChaCha20` implementation is implemented as a state machine, this is to better enforce
/// best practices such as avoiding initialization vector reuse. The generic `S` represents the
/// current state.
///
/// The state machine takes the following form:
///
/// ```text
/// +----------+
/// | Init |
/// +----------+
/// |
/// |
/// v
/// +----------+ `finalize()`
/// +> | Needs IV | <----------------------+
/// | +----------+ |
/// | | |
/// | | |
/// | v |
/// | +--------------------------+ +-----------+
/// | | | | | ---+
/// | | Ready | | Streaming | |
/// | | | ---> | | <--+
/// | +--------------------------+ +-----------+
/// | | ^ |
/// | | | |
/// | v | v
/// | +----------+ | +---------+
/// +- | Encrypt | +- | Decrypt |
/// +----------+ +---------+
/// ```
///
/// # Example
///
/// ```
/// use wolf_crypto::chacha::ChaCha20;
///
/// let (output, mut chacha) = ChaCha20::new(&[7u8; 32])
/// .set_iv(&[3u8; 12])
/// .encrypt_exact(b"hello world")
/// .unwrap();
///
/// let plaintext = chacha.set_iv(&[3u8; 12])
/// .decrypt_exact(&output)
/// .unwrap();
///
/// assert_eq!(b"hello world", &plaintext);
/// ```
#[repr(transparent)]
pub struct ChaCha20<S: State = Init> {
inner: ChaCha,
_state: PhantomData<S>
}
impl ChaCha20<Init> {
/// Create a new `ChaCha20` instance.
///
/// # Arguments
///
/// * `key` - The 128-bit or 256-bit key material.
///
/// # Returns
///
/// A new `ChaCha20` instance in the [`NeedsIv`] state.
pub fn new<K: GenericKey>(key: K) -> ChaCha20<NeedsIv> {
let mut inner = MaybeUninit::<ChaCha>::uninit();
unsafe {
// Infallible, the GenericKey is sealed and only supports 128 or 256-bit keys, which
// are valid sizes. According to the docs this is the only way that this function
// can fail. Debug assert to build further confidence. This has been confirmed post
// reviewing the source code.
//
// See for yourself:
// https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/chacha.c#L154
let _res = wc_Chacha_SetKey(
inner.as_mut_ptr(),
key.slice().as_ptr(),
key.size()
);
debug_assert_eq!(_res, 0);
Self::new_with(inner.assume_init())
}
}
}
impl<S: State> ChaCha20<S> {
#[inline]
#[must_use]
const fn new_with<NS: State>(inner: ChaCha) -> ChaCha20<NS> {
ChaCha20::<NS> {
inner,
_state: PhantomData
}
}
}
impl ChaCha20<NeedsIv> {
/// Set the initialization vector to use for the next [`Ready`] state.
///
/// # Arguments
///
/// * `iv` - The 96-bit initialization vector.
/// * `counter` - The value at which the block counter should start, generally zero.
///
/// # Returns
///
/// The `ChaCha20` instance in the [`Ready`] state.
pub fn set_iv_with_ctr<IV>(mut self, iv: IV, counter: u32) -> ChaCha20<Ready>
where IV: GenericIv<Size = U12>
{
// Infallible, see source:
// /**
// * Set up iv(nonce). Earlier versions used 64 bits instead of 96, this version
// * uses the typical AEAD 96 bit nonce and can do record sizes of 256 GB.
// */
// int wc_Chacha_SetIV(ChaCha* ctx, const byte* inIv, word32 counter)
// {
// word32 temp[CHACHA_IV_WORDS];/* used for alignment of memory */
//
//
// if (ctx == NULL || inIv == NULL)
// return BAD_FUNC_ARG;
//
// XMEMCPY(temp, inIv, CHACHA_IV_BYTES);
//
// ctx->left = 0; /* resets state */
// ctx->X[CHACHA_MATRIX_CNT_IV+0] = counter; /* block counter */
// ctx->X[CHACHA_MATRIX_CNT_IV+1] = LITTLE32(temp[0]); /* fixed variable from nonce */
// ctx->X[CHACHA_MATRIX_CNT_IV+2] = LITTLE32(temp[1]); /* counter from nonce */
// ctx->X[CHACHA_MATRIX_CNT_IV+3] = LITTLE32(temp[2]); /* counter from nonce */
//
// return 0;
// }
//
// https://github.com/wolfSSL/wolfssl/blob/master/wolfcrypt/src/chacha.c#L127
unsafe {
let _res = wc_Chacha_SetIV(
addr_of_mut!(self.inner),
iv.as_slice().as_ptr(),
counter
);
debug_assert_eq!(_res, 0);
}
Self::new_with(self.inner)
}
/// Set the initialization vector to use for the next [`Ready`] state.
///
/// # Arguments
///
/// * `iv` - The 96-bit initialization vector.
///
/// # Returns
///
/// The `ChaCha20` instance in the [`Ready`] state.
#[inline]
pub fn set_iv<IV: GenericIv<Size = U12>>(self, iv: IV) -> ChaCha20<Ready> {
self.set_iv_with_ctr(iv, 0)
}
}
impl_fmt! { NeedsIv }
impl<S: CanProcess> ChaCha20<S> {
#[inline]
#[must_use]
const fn predicate(input_len: usize, output_len: usize) -> bool {
input_len <= output_len && can_cast_u32(input_len)
}
#[inline]
#[must_use]
const fn const_predicate<const I: usize, const O: usize>() -> bool {
I <= O && const_can_cast_u32::<I>()
}
/// Processes the input into the output buffer without checking lengths.
///
/// # Safety
///
/// This function is unsafe because it does not check if the input and output
/// lengths are valid. The caller must ensure that:
/// - The input length is less than or equal to the output length.
/// - The input length can be cast to a `u32` without overflow.
///
/// # Arguments
///
/// * `input` - The input slice to process.
/// * `output` - The output buffer to write the processed data into.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
unsafe fn process_unchecked(&mut self, input: &[u8], output: &mut [u8]) -> Res {
debug_assert!(
Self::predicate(input.len(), output.len()),
"Process unchecked precondition violated (debug assertion). The size of the input must \
be less than or equal to the size of the output. The size of the input must also be \
representable as a `u32` without overflowing."
);
let mut res = Res::new();
res.ensure_0(wc_Chacha_Process(
addr_of_mut!(self.inner),
output.as_mut_ptr(),
input.as_ptr(),
input.len() as u32
));
res
}
/// Processes the input into the output buffer, checking lengths.
///
/// # Arguments
///
/// * `input` - The input slice to process.
/// * `output` - The output buffer to write the processed data into.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
fn process(&mut self, input: &[u8], output: &mut [u8]) -> Res {
if !Self::predicate(input.len(), output.len()) { return Res::ERR }
unsafe { self.process_unchecked(input, output) }
}
/// Processes the input into the output buffer with exact sizes.
///
/// # Arguments
///
/// * `input` - The input array to process.
/// * `output` - The output array to write the processed data into.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
fn process_exact<const C: usize>(
&mut self,
input: &[u8; C],
output: &mut [u8; C]
) -> Res {
if !const_can_cast_u32::<C>() { return Res::ERR; }
unsafe { self.process_unchecked(input, output) }
}
/// Processes the input into the output buffer with compile-time size checking.
///
/// # Type Parameters
///
/// * `I` - The size of the input array.
/// * `O` - The size of the output array.
///
/// # Arguments
///
/// * `input` - The input array to process.
/// * `output` - The output array to write the processed data into.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
fn process_sized<const I: usize, const O: usize>(
&mut self,
input: &[u8; I],
output: &mut [u8; O]
) -> Res {
if !Self::const_predicate::<I, O>() { return Res::ERR }
unsafe { self.process_unchecked(input, output) }
}
/// Processes the input into the output buffer with a fixed-size output.
///
/// # Type Parameters
///
/// * `O` - The size of the output array.
///
/// # Arguments
///
/// * `input` - The input slice to process.
/// * `output` - The output array to write the processed data into.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
fn process_sized_out<const O: usize>(
&mut self,
input: &[u8],
output: &mut [u8; O]
) -> Res {
if !(lte::<O>(input.len()) && can_cast_u32(input.len())) { return Res::ERR }
unsafe { self.process_unchecked(input, output) }
}
}
impl ChaCha20<Ready> {
/// Encrypts the plaintext into the ciphertext buffer.
///
/// # Arguments
///
/// * `plain` - The plaintext to encrypt.
/// * `ciphertext` - The buffer to store the encrypted data.
///
/// # Returns
///
/// A `Result` containing either the `ChaCha20` instance in the `NeedsIv` state
/// on success, or the original instance on failure.
#[inline]
pub fn encrypt_into(
mut self,
plain: &[u8],
ciphertext: &mut [u8]
) -> Result<ChaCha20<NeedsIv>, Self> {
if self.process(plain, ciphertext).is_ok() {
Ok(Self::new_with(self.inner))
} else {
Err(self)
}
}
/// Encrypts the plaintext into the ciphertext buffer with compile-time size checking.
///
/// # Type Parameters
///
/// * `P` - The size of the plaintext array.
/// * `C` - The size of the ciphertext array.
///
/// # Arguments
///
/// * `plain` - The plaintext array to encrypt.
/// * `ciphertext` - The array to store the encrypted data.
///
/// # Returns
///
/// A `Result` containing either the `ChaCha20` instance in the `NeedsIv` state
/// on success, or the original instance on failure.
#[inline]
pub fn encrypt_into_sized<const P: usize, const C: usize>(
mut self,
plain: &[u8; P],
ciphertext: &mut [u8; C]
) -> Result<ChaCha20<NeedsIv>, Self> {
if self.process_sized(plain, ciphertext).is_ok() {
Ok(Self::new_with(self.inner))
} else {
Err(self)
}
}
/// Encrypts the plaintext into a fixed-size ciphertext buffer.
///
/// # Type Parameters
///
/// * `C` - The size of the ciphertext array.
///
/// # Arguments
///
/// * `plain` - The plaintext to encrypt.
/// * `ciphertext` - The array to store the encrypted data.
///
/// # Returns
///
/// A `Result` containing either the `ChaCha20` instance in the `NeedsIv` state
/// on success, or the original instance on failure.
#[inline]
pub fn encrypt_into_sized_out<const C: usize>(
mut self,
plain: &[u8],
ciphertext: &mut [u8; C]
) -> Result<ChaCha20<NeedsIv>, Self> {
if self.process_sized_out(plain, ciphertext).is_ok() {
Ok(Self::new_with(self.inner))
} else {
Err(self)
}
}
/// Encrypts the plaintext into the ciphertext buffer with exact sizes.
///
/// # Type Parameters
///
/// * `C` - The size of both the plaintext and ciphertext arrays.
///
/// # Arguments
///
/// * `plain` - The plaintext array to encrypt.
/// * `ciphertext` - The array to store the encrypted data.
///
/// # Returns
///
/// A `Result` containing either the `ChaCha20` instance in the `NeedsIv` state
/// on success, or the original instance on failure.
#[inline]
pub fn encrypt_into_exact<const C: usize>(
mut self,
plain: &[u8; C],
ciphertext: &mut [u8; C]
) -> Result<ChaCha20<NeedsIv>, Self> {
if self.process_exact(plain, ciphertext).is_ok() {
Ok(Self::new_with(self.inner))
} else {
Err(self)
}
}
alloc! {
/// Encrypts the plaintext and returns the ciphertext as a vector.
///
/// # Arguments
///
/// * `plain` - The plaintext to encrypt.
///
/// # Returns
///
/// A `Result` containing either a tuple of the ciphertext vector and the `ChaCha20`
/// instance in the `NeedsIv` state on success, or the original instance on failure.
pub fn encrypt(
mut self,
plain: &[u8]
) -> Result<(alloc::vec::Vec<u8>, ChaCha20<NeedsIv>), Self> {
let mut output = alloc::vec![0u8; plain.len()];
self.encrypt_into(plain, output.as_mut_slice()).map(move |ni| (output, ni))
}
}
/// Encrypts the plaintext array and returns the ciphertext array.
///
/// # Type Parameters
///
/// * `I` - The size of the plaintext and ciphertext arrays.
///
/// # Arguments
///
/// * `plain` - The plaintext array to encrypt.
///
/// # Returns
///
/// A `Result` containing either a tuple of the ciphertext array and the `ChaCha20`
/// instance in the `NeedsIv` state on success, or the original instance on failure.
#[inline]
pub fn encrypt_exact<const I: usize>(
self,
plain: &[u8; I]
) -> Result<([u8; I], ChaCha20<NeedsIv>), Self> {
let mut output = [0u8; I];
self.encrypt_into_exact(plain, &mut output).map(move |ni| (output, ni))
}
}
impl_fmt! { Ready }
impl<S: CanProcess> ChaCha20<S> {
/// Decrypts the ciphertext into the output buffer.
///
/// # Arguments
///
/// * `cipher` - The ciphertext to decrypt.
/// * `output` - The buffer to store the decrypted data.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
pub fn decrypt_into(&mut self, cipher: &[u8], output: &mut [u8]) -> Res {
self.process(cipher, output)
}
/// Decrypts the ciphertext into the output buffer with compile-time size checking.
///
/// # Type Parameters
///
/// * `I` - The size of the ciphertext array.
/// * `O` - The size of the output array.
///
/// # Arguments
///
/// * `cipher` - The ciphertext array to decrypt.
/// * `output` - The array to store the decrypted data.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
pub fn decrypt_into_sized<const I: usize, const O: usize>(
&mut self,
cipher: &[u8; I],
output: &mut [u8; O]
) -> Res {
self.process_sized(cipher, output)
}
/// Decrypts the ciphertext into the output buffer with exact sizes.
///
/// # Type Parameters
///
/// * `C` - The size of both the ciphertext and output arrays.
///
/// # Arguments
///
/// * `cipher` - The ciphertext array to decrypt.
/// * `output` - The array to store the decrypted data.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
pub fn decrypt_into_exact<const C: usize>(&mut self, cipher: &[u8; C], output: &mut [u8; C]) -> Res {
self.process_exact(cipher, output)
}
alloc! {
/// Decrypts the ciphertext and returns the plaintext as a vector.
///
/// # Arguments
///
/// * `cipher` - The ciphertext to decrypt.
///
/// # Returns
///
/// A `Result` containing either the decrypted plaintext as a vector on success,
/// or an `Unspecified` error on failure.
#[inline]
pub fn decrypt(&mut self, cipher: &[u8]) -> Result<alloc::vec::Vec<u8>, Unspecified> {
let mut output = alloc::vec![0u8; cipher.len()];
self.decrypt_into(cipher, output.as_mut_slice()).unit_err(output)
}
}
/// Decrypts the ciphertext array and returns the plaintext array.
///
/// # Type Parameters
///
/// * `O` - The size of the ciphertext and plaintext arrays.
///
/// # Arguments
///
/// * `cipher` - The ciphertext array to decrypt.
///
/// # Returns
///
/// A `Result` containing either the decrypted plaintext array on success,
/// or an `Unspecified` error on failure.
#[inline]
pub fn decrypt_exact<const O: usize>(&mut self, cipher: &[u8; O]) -> Result<[u8; O], Unspecified> {
let mut output = [0u8; O];
self.decrypt_into_exact(cipher, &mut output).unit_err(output)
}
}
impl ChaCha20<Streaming> {
/// Encrypts the input into the output buffer in streaming mode.
///
/// # Arguments
///
/// * `input` - The input to encrypt.
/// * `output` - The buffer to store the encrypted data.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
pub fn encrypt_into(&mut self, input: &[u8], output: &mut [u8]) -> Res {
self.process(input, output)
}
/// Encrypts the input into the output buffer in streaming mode with compile-time size checking.
///
/// # Type Parameters
///
/// * `I` - The size of the input array.
/// * `O` - The size of the output array.
///
/// # Arguments
///
/// * `input` - The input array to encrypt.
/// * `output` - The array to store the encrypted data.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
pub fn encrypt_into_sized<const I: usize, const O: usize>(
&mut self,
input: &[u8; I],
output: &mut [u8; O]
) -> Res {
self.process_sized(input, output)
}
/// Encrypts the input into the output buffer in streaming mode with exact sizes.
///
/// # Type Parameters
///
/// * `C` - The size of both the input and output arrays.
///
/// # Arguments
///
/// * `input` - The input array to encrypt.
/// * `output` - The array to store the encrypted data.
///
/// # Returns
///
/// A `Res` indicating the success or failure of the operation.
#[inline]
pub fn encrypt_into_exact<const C: usize>(
&mut self,
input: &[u8; C],
output: &mut [u8; C]
) -> Res {
self.process_exact(input, output)
}
/// Finishes the streaming encryption and returns to the `NeedsIv` state.
///
/// # Returns
///
/// A `ChaCha20` instance in the `NeedsIv` state.
#[inline]
pub const fn finish(self) -> ChaCha20<NeedsIv> {
Self::new_with(self.inner)
}
std! {
/// Creates a new `Writer` for streaming encryption with a custom chunk size.
///
/// # Type Parameters
///
/// * `W` - The type of the writer.
/// * `CHUNK` - The chunk size for processing. This is the size of the intermediary buffer
/// stored on the stack in bytes for the `write_all` and `write`
/// implementations.
///
/// # Arguments
///
/// * `writer` - The underlying writer to use.
///
/// # Returns
///
/// A new `Writer` instance.
pub const fn writer<W: io::Write, const CHUNK: usize>(self, writer: W) -> Writer<W, CHUNK> {
Writer::new(self, writer)
}
/// Creates a new `Writer` for streaming encryption with a default chunk size of 128 bytes.
///
/// # Type Parameters
///
/// * `W` - The type of the writer.
///
/// # Arguments
///
/// * `writer` - The underlying writer to use.
///
/// # Returns
///
/// A new `Writer` instance with a chunk size of 128 bytes.
pub const fn default_writer<W: io::Write>(self, writer: W) -> Writer<W, 128> {
Writer::new(self, writer)
}
}
}
impl_fmt! { Streaming }
std! {
use std::io;
use core::ops;
/// A wrapper for any implementor of `std::io::Write`.
///
/// `Writer` implements `std::io::Write` and takes a child which also implements this trait.
/// This type can wrap any writer, and ensure all data passed to said writer is encrypted.
pub struct Writer<W, const CHUNK: usize> {
chacha: ChaCha20<Streaming>,
writer: W
}
impl<W, const CHUNK: usize> Writer<W, CHUNK> {
/// Creates a new `Writer` instance.
///
/// # Arguments
///
/// * `chacha` - The `ChaCha20` instance in streaming mode.
/// * `writer` - The underlying writer.
///
/// # Returns
///
/// A new `Writer` instance.
pub const fn new(chacha: ChaCha20<Streaming>, writer: W) -> Self {
Self {
chacha,
writer
}
}
/// Finishes the streaming encryption and returns to the `NeedsIv` state.
///
/// # Returns
///
/// A `ChaCha20` instance in the `NeedsIv` state.
#[inline]
pub fn finish(self) -> ChaCha20<NeedsIv> {
self.chacha.finish()
}
}
impl<W, const CHUNK: usize> ops::Deref for Writer<W, CHUNK> {
type Target = ChaCha20<Streaming>;
#[inline]
fn deref(&self) -> &Self::Target {
&self.chacha
}
}
impl<W, const CHUNK: usize> ops::DerefMut for Writer<W, CHUNK> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.chacha
}
}
impl<W: io::Write, const CHUNK: usize> io::Write for Writer<W, CHUNK> {
/// Encrypts and writes the given buffer.
///
/// # Arguments
///
/// * `buf` - The buffer to encrypt and write.
///
/// # Returns
///
/// The number of bytes written on success, or an `io::Error` on failure.
///
/// # Note
///
/// The maximum number of bytes this can write in a single invocation is capped by the
/// `CHUNK` size. If this is not desirable, please consider using the `write_all`
/// implementation.
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
let mut out = [0u8; CHUNK];
let to_write = core::cmp::min(CHUNK, buf.len());
if unsafe { self.process_unchecked(&buf[..to_write], &mut out[..to_write]).is_err() } {
return Err(io::Error::other(Unspecified))
}
self.writer.write(&out[..to_write])
}
/// Encrypts and writes the entire buffer.
///
/// # Arguments
///
/// * `buf` - The buffer to encrypt and write.
///
/// # Returns
///
/// `Ok(())` on success, or an `io::Error` on failure.
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
let mut out = [0u8; CHUNK];
let mut pos = 0usize;
let len = buf.len();
while pos + CHUNK <= len {
unsafe {
if self.process_unchecked(&buf[pos..pos + CHUNK], &mut out).is_err() {
return Err(io::Error::other(Unspecified));
}
pos += CHUNK;
self.writer.write_all(&out)?;
}
}
let last = &buf[pos..];
if unsafe { self.process_unchecked(last, &mut out).is_err() } {
return Err(io::Error::other(Unspecified));
}
self.writer.write_all(&out[..last.len()])
}
/// Flushes the underlying writer.
///
/// # Returns
///
/// Propagates the result of invoking flush for the underlying writer
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.writer.flush()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn smoke() {
let (encrypted, chacha) = ChaCha20::new(&[0u8; 16])
.set_iv([3u8; 12])
.encrypt_exact(b"hello world!")
.unwrap();
let plain = chacha
.set_iv([3u8; 12])
.decrypt_exact(&encrypted)
.unwrap();
assert_eq!(plain, *b"hello world!");
}
}