Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XChaCha20Poly1305 #4

Merged
merged 1 commit into from
Aug 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion chacha20poly1305/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,15 @@ ChaCha20Poly1305 Authenticated Encryption with Additional Data Algorithm (RFC 84
"""
documentation = "chacha20poly1305"
repository = "https://github.com/RustCrypto/AEADs"
keywords = ["crypto", "cipher", "aead"]
keywords = ["crypto", "cipher", "aead", "xchacha20", "xchacha20poly1305"]
categories = ["cryptography", "no-std"]

[dependencies]
aead = { version = "0.1", git = "https://github.com/RustCrypto/traits" }
chacha20 = { version = "0.2.1", features = ["zeroize"] }
poly1305 = "0.2"
zeroize = { version = "0.9", default-features = false }

[features]
default = ["xchacha20poly1305"]
xchacha20poly1305 = ["chacha20/xchacha20"]
122 changes: 122 additions & 0 deletions chacha20poly1305/src/cipher.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
//! Core AEAD cipher implementation for (X)ChaCha20Poly1305.

// TODO(tarcieri): make this reusable for (X)Salsa20Poly1305
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Arguably the best way to do this is making it generic to all stream ciphers: RustCrypto/traits#45


use aead::generic_array::GenericArray;
use aead::Error;
use alloc::vec::Vec;
use chacha20::stream_cipher::{SyncStreamCipher, SyncStreamCipherSeek};
use core::convert::TryInto;
use poly1305::{Poly1305, Tag};
use zeroize::Zeroizing;

/// ChaCha20Poly1305 instantiated with a particular nonce
pub(crate) struct Cipher<C>
where
C: SyncStreamCipher + SyncStreamCipherSeek,
{
cipher: C,
mac: Poly1305,
}

impl<C> Cipher<C>
where
C: SyncStreamCipher + SyncStreamCipherSeek,
{
/// Instantiate the underlying cipher with a particular nonce
pub(crate) fn new(mut cipher: C) -> Self {
// Derive Poly1305 key from the first 32-bytes of the ChaCha20 keystream
let mut mac_key = Zeroizing::new([0u8; poly1305::KEY_SIZE]);
cipher.apply_keystream(&mut *mac_key);
let mac = Poly1305::new(&mac_key);

// Set ChaCha20 counter to 1
cipher.seek(chacha20::BLOCK_SIZE as u64);

Self { cipher, mac }
}

/// Encrypt the given message, allocating a vector for the resulting ciphertext
pub(crate) fn encrypt(
self,
associated_data: &[u8],
plaintext: &[u8],
) -> Result<Vec<u8>, Error> {
let mut buffer = Vec::with_capacity(plaintext.len() + poly1305::BLOCK_SIZE);
buffer.extend_from_slice(plaintext);

let tag = self.encrypt_in_place(associated_data, &mut buffer)?;
buffer.extend_from_slice(tag.code().as_slice());
Ok(buffer)
}

/// Encrypt the given message in-place, returning the authentication tag
pub(crate) fn encrypt_in_place(
mut self,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag, Error> {
if buffer.len() / chacha20::BLOCK_SIZE >= chacha20::MAX_BLOCKS {
return Err(Error);
}

self.mac.input_padded(associated_data);
self.cipher.apply_keystream(buffer);
self.mac.input_padded(buffer);
self.authenticate_lengths(associated_data, buffer)?;
Ok(self.mac.result())
}

/// Decrypt the given message, allocating a vector for the resulting plaintext
pub(crate) fn decrypt(
self,
associated_data: &[u8],
ciphertext: &[u8],
) -> Result<Vec<u8>, Error> {
if ciphertext.len() < poly1305::BLOCK_SIZE {
return Err(Error);
}

let tag_start = ciphertext.len() - poly1305::BLOCK_SIZE;
let mut buffer = Vec::from(&ciphertext[..tag_start]);
let tag: [u8; poly1305::BLOCK_SIZE] = ciphertext[tag_start..].try_into().unwrap();
self.decrypt_in_place(associated_data, &mut buffer, &tag)?;

Ok(buffer)
}

/// Decrypt the given message, first authenticating ciphertext integrity
/// and returning an error if it's been tampered with.
pub(crate) fn decrypt_in_place(
mut self,
associated_data: &[u8],
buffer: &mut [u8],
tag: &[u8; poly1305::BLOCK_SIZE],
) -> Result<(), Error> {
if buffer.len() / chacha20::BLOCK_SIZE >= chacha20::MAX_BLOCKS {
return Err(Error);
}

self.mac.input_padded(associated_data);
self.mac.input_padded(buffer);
self.authenticate_lengths(associated_data, buffer)?;

// This performs a constant-time comparison using the `subtle` crate
if self.mac.result() == Tag::new(*GenericArray::from_slice(tag)) {
self.cipher.apply_keystream(buffer);
Ok(())
} else {
Err(Error)
}
}

/// Authenticate the lengths of the associated data and message
fn authenticate_lengths(&mut self, associated_data: &[u8], buffer: &[u8]) -> Result<(), Error> {
let associated_data_len: u64 = associated_data.len().try_into().map_err(|_| Error)?;
let buffer_len: u64 = buffer.len().try_into().map_err(|_| Error)?;

self.mac.input(&associated_data_len.to_le_bytes());
self.mac.input(&buffer_len.to_le_bytes());
Ok(())
}
}
124 changes: 18 additions & 106 deletions chacha20poly1305/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,25 @@

extern crate alloc;

pub use aead;
mod cipher;
#[cfg(feature = "xchacha20poly1305")]
mod xchacha20poly1305;

use aead::generic_array::typenum::{U0, U12, U16, U32};
use aead::{generic_array::GenericArray, StatelessAead, Error, NewAead};
pub use aead;
#[cfg(feature = "xchacha20poly1305")]
pub use xchacha20poly1305::XChaCha20Poly1305;

use self::cipher::Cipher;
use aead::generic_array::{
typenum::{U0, U12, U16, U32},
GenericArray,
};
use aead::{Error, NewAead, StatelessAead};
use alloc::vec::Vec;
use chacha20::stream_cipher::{NewStreamCipher, SyncStreamCipher, SyncStreamCipherSeek};
use chacha20::ChaCha20;
use core::convert::TryInto;
use poly1305::{Poly1305, Tag};
use zeroize::{Zeroize, Zeroizing};
use chacha20::{stream_cipher::NewStreamCipher, ChaCha20};
use zeroize::Zeroize;

/// ChaCha20Poly1305 AEAD
/// ChaCha20Poly1305 Authenticated Encryption with Additional Data (AEAD)
#[derive(Clone)]
pub struct ChaCha20Poly1305 {
/// Secret key
Expand All @@ -42,7 +49,7 @@ impl StatelessAead for ChaCha20Poly1305 {
nonce: &GenericArray<u8, Self::NonceSize>,
plaintext: &[u8],
) -> Result<Vec<u8>, Error> {
CipherInstance::new(&self.key, nonce).encrypt(associated_data, plaintext)
Cipher::new(ChaCha20::new(&self.key, nonce)).encrypt(associated_data, plaintext)
}

fn decrypt(
Expand All @@ -51,7 +58,7 @@ impl StatelessAead for ChaCha20Poly1305 {
nonce: &GenericArray<u8, Self::NonceSize>,
ciphertext: &[u8],
) -> Result<Vec<u8>, Error> {
CipherInstance::new(&self.key, nonce).decrypt(associated_data, ciphertext)
Cipher::new(ChaCha20::new(&self.key, nonce)).decrypt(associated_data, ciphertext)
}
}

Expand All @@ -60,98 +67,3 @@ impl Drop for ChaCha20Poly1305 {
self.key.as_mut_slice().zeroize();
}
}

/// ChaCha20Poly1305 instantiated with a particular nonce
struct CipherInstance {
chacha20: ChaCha20,
poly1305: Poly1305,
}

impl CipherInstance {
/// Instantiate the underlying cipher with a particular nonce
fn new(key: &GenericArray<u8, U32>, nonce: &GenericArray<u8, U12>) -> Self {
let mut chacha20 = ChaCha20::new(key, nonce);

// Derive Poly1305 key from the first 32-bytes of the ChaCha20 keystream
let mut auth_key = Zeroizing::new([0u8; poly1305::KEY_SIZE]);
chacha20.apply_keystream(&mut *auth_key);

// Set ChaCha20 counter to 1
chacha20.seek(chacha20::BLOCK_SIZE as u64);

let poly1305 = Poly1305::new(&auth_key);
Self { chacha20, poly1305 }
}

/// Encrypt the given message, allocating a vector for the resulting ciphertext
fn encrypt(self, associated_data: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, Error> {
let mut buffer = Vec::with_capacity(plaintext.len() + poly1305::BLOCK_SIZE);
buffer.extend_from_slice(plaintext);

let tag = self.encrypt_in_place(associated_data, &mut buffer)?;
buffer.extend_from_slice(tag.code().as_slice());
Ok(buffer)
}

/// Encrypt the given message in-place, returning the authentication tag
fn encrypt_in_place(mut self, associated_data: &[u8], buffer: &mut [u8]) -> Result<Tag, Error> {
if buffer.len() / chacha20::BLOCK_SIZE >= chacha20::MAX_BLOCKS {
return Err(Error);
}

self.poly1305.input_padded(associated_data);
self.chacha20.apply_keystream(buffer);
self.poly1305.input_padded(buffer);
self.authenticate_lengths(associated_data, buffer)?;
Ok(self.poly1305.result())
}

/// Decrypt the given message, allocating a vector for the resulting plaintext
fn decrypt(self, associated_data: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, Error> {
if ciphertext.len() < poly1305::BLOCK_SIZE {
return Err(Error);
}

let tag_start = ciphertext.len() - poly1305::BLOCK_SIZE;
let mut buffer = Vec::from(&ciphertext[..tag_start]);
let tag: [u8; poly1305::BLOCK_SIZE] = ciphertext[tag_start..].try_into().unwrap();
self.decrypt_in_place(associated_data, &mut buffer, &tag)?;

Ok(buffer)
}

/// Decrypt the given message, first authenticating ciphertext integrity
/// and returning an error if it's been tampered with.
fn decrypt_in_place(
mut self,
associated_data: &[u8],
buffer: &mut [u8],
tag: &[u8; poly1305::BLOCK_SIZE],
) -> Result<(), Error> {
if buffer.len() / chacha20::BLOCK_SIZE >= chacha20::MAX_BLOCKS {
return Err(Error);
}

self.poly1305.input_padded(associated_data);
self.poly1305.input_padded(buffer);
self.authenticate_lengths(associated_data, buffer)?;

// This performs a constant-time comparison using the `subtle` crate
if self.poly1305.result() == Tag::new(*GenericArray::from_slice(tag)) {
self.chacha20.apply_keystream(buffer);
Ok(())
} else {
Err(Error)
}
}

/// Authenticate the lengths of the associated data and message
fn authenticate_lengths(&mut self, associated_data: &[u8], buffer: &[u8]) -> Result<(), Error> {
let associated_data_len: u64 = associated_data.len().try_into().map_err(|_| Error)?;
let buffer_len: u64 = buffer.len().try_into().map_err(|_| Error)?;

self.poly1305.input(&associated_data_len.to_le_bytes());
self.poly1305.input(&buffer_len.to_le_bytes());
Ok(())
}
}
74 changes: 74 additions & 0 deletions chacha20poly1305/src/xchacha20poly1305.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
//! XChaCha20Poly1305 is an extended nonce variant of ChaCha20Poly1305

use crate::cipher::Cipher;
use aead::generic_array::{
typenum::{U0, U16, U24, U32},
GenericArray,
};
use aead::{Error, NewAead, StatelessAead};
use alloc::vec::Vec;
use chacha20::{stream_cipher::NewStreamCipher, XChaCha20};
use zeroize::Zeroize;

/// XChaCha20Poly1305 is a ChaCha20Poly1305 variant with an extended
/// 192-bit (24-byte) nonce.
///
/// The construction is an adaptation of the same techniques used by
/// XSalsa20 as described in the paper "Extending the Salsa20 Nonce",
/// applied to the 96-bit nonce variant of ChaCha20, and derive a
/// separate subkey/nonce for each extended nonce:
///
/// <https://cr.yp.to/snuffle/xsalsa-20081128.pdf>
///
/// No authoritative specification exists for XChaCha20Poly1305, however the
/// construction has "rough consensus and running code" in the form of
/// several interoperable libraries and protocols (e.g. libsodium, WireGuard)
/// and is documented in an (expired) IETF draft:
///
/// <https://tools.ietf.org/html/draft-arciszewski-xchacha-03>
///
/// The `xchacha20poly1305` Cargo feature must be enabled in order to use this
/// (which it is by default).
#[derive(Clone)]
pub struct XChaCha20Poly1305 {
/// Secret key
key: GenericArray<u8, U32>,
}

impl NewAead for XChaCha20Poly1305 {
type KeySize = U32;

fn new(key: GenericArray<u8, U32>) -> Self {
XChaCha20Poly1305 { key }
}
}

impl StatelessAead for XChaCha20Poly1305 {
type NonceSize = U24;
type TagSize = U16;
type CiphertextOverhead = U0;

fn encrypt(
&self,
associated_data: &[u8],
nonce: &GenericArray<u8, Self::NonceSize>,
plaintext: &[u8],
) -> Result<Vec<u8>, Error> {
Cipher::new(XChaCha20::new(&self.key, nonce)).encrypt(associated_data, plaintext)
}

fn decrypt(
&self,
associated_data: &[u8],
nonce: &GenericArray<u8, Self::NonceSize>,
ciphertext: &[u8],
) -> Result<Vec<u8>, Error> {
Cipher::new(XChaCha20::new(&self.key, nonce)).decrypt(associated_data, ciphertext)
}
}

impl Drop for XChaCha20Poly1305 {
fn drop(&mut self) {
self.key.as_mut_slice().zeroize();
}
}
Loading