-
Notifications
You must be signed in to change notification settings - Fork 157
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
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
||
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(()) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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