Skip to content

Expose "detached" in-place encryption/decryption APIs #21

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

Merged
merged 1 commit into from
Oct 4, 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
1 change: 1 addition & 0 deletions aes-gcm-siv/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ aes = "0.3"
ctr = "0.3"
polyval = "0.2"
subtle = { version = "2", default-features = false }
zeroize = { version = "1.0.0-pre", default-features = false }

[dev-dependencies]
criterion = "0.3.0"
Expand Down
3 changes: 2 additions & 1 deletion aes-gcm-siv/src/ctr32.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@ where
C: BlockCipher<BlockSize = U16, ParBlocks = U8>,
{
/// Instantiate a new CTR instance
pub fn new(cipher: &'c C, mut counter_block: Block128) -> Self {
pub fn new(cipher: &'c C, counter_block: &Block128) -> Self {
let mut counter_block = *counter_block;
counter_block[15] |= 0x80;

Self {
Expand Down
111 changes: 73 additions & 38 deletions aes-gcm-siv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ use aead::{Aead, Error, NewAead, Payload};
use aes::{block_cipher_trait::BlockCipher, Aes128, Aes256};
use alloc::vec::Vec;
use polyval::{universal_hash::UniversalHash, Polyval};
use zeroize::Zeroize;

/// Maximum length of associated data (from RFC 8452 Section 6)
pub const A_MAX: u64 = 1 << 36;
Expand All @@ -77,7 +78,7 @@ pub const P_MAX: u64 = 1 << 36;
pub const C_MAX: u64 = (1 << 36) + 16;

/// AES-GCM-SIV tags
type Tag = GenericArray<u8, U16>;
pub type Tag = GenericArray<u8, U16>;

/// AES-GCM-SIV with a 128-bit key
pub type Aes128GcmSiv = AesGcmSiv<Aes128>;
Expand Down Expand Up @@ -116,15 +117,60 @@ where
nonce: &GenericArray<u8, Self::NonceSize>,
plaintext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>, Error> {
Cipher::<C>::new(&self.key, nonce).encrypt(plaintext.into())
let payload = plaintext.into();
let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
buffer.extend_from_slice(payload.msg);

let tag = self.encrypt_in_place_detached(nonce, payload.aad, &mut buffer)?;
buffer.extend_from_slice(tag.as_slice());
Ok(buffer)
}

fn decrypt<'msg, 'aad>(
&self,
nonce: &GenericArray<u8, Self::NonceSize>,
ciphertext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>, Error> {
Cipher::<C>::new(&self.key, nonce).decrypt(ciphertext.into())
let payload = ciphertext.into();

if payload.msg.len() < Self::TagSize::to_usize() {
return Err(Error);
}

let tag_start = payload.msg.len() - Self::TagSize::to_usize();
let mut buffer = Vec::from(&payload.msg[..tag_start]);
let tag = Tag::from_slice(&payload.msg[tag_start..]);
self.decrypt_in_place_detached(nonce, payload.aad, &mut buffer, tag)?;

Ok(buffer)
}
}

impl<C> AesGcmSiv<C>
where
C: BlockCipher<BlockSize = U16, ParBlocks = U8>,
{
/// Encrypt the data in-place, returning the authentication tag
pub fn encrypt_in_place_detached(
&self,
nonce: &GenericArray<u8, <Self as Aead>::NonceSize>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag, Error> {
Cipher::<C>::new(&self.key, nonce).encrypt_in_place_detached(associated_data, buffer)
}

/// Decrypt the data in-place, returning an error in the event the provided
/// authentication tag does not match the given ciphertext (i.e. ciphertext
/// is modified/unauthentic)
pub fn decrypt_in_place_detached(
&self,
nonce: &GenericArray<u8, <Self as Aead>::NonceSize>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag,
) -> Result<(), Error> {
Cipher::<C>::new(&self.key, nonce).decrypt_in_place_detached(associated_data, buffer, tag)
}
}

Expand All @@ -149,7 +195,6 @@ where
pub(crate) fn new(key: &GenericArray<u8, C::KeySize>, nonce: &GenericArray<u8, U12>) -> Self {
let key_generating_key = C::new(key);

// TODO(tarcieri): zeroize all of these buffers!
let mut mac_key = GenericArray::default();
let mut enc_key = GenericArray::default();
let mut block = GenericArray::default();
Expand Down Expand Up @@ -183,63 +228,43 @@ where
}
}

Self {
let result = Self {
enc_cipher: C::new(&enc_key),
polyval: Polyval::new(&mac_key),
nonce: *nonce,
}
}
};

/// Encrypt the given message, allocating a vector for the resulting ciphertext
pub(crate) fn encrypt(self, payload: Payload<'_, '_>) -> Result<Vec<u8>, Error> {
let tag_size = <Polyval as UniversalHash>::BlockSize::to_usize();
// Zeroize all intermediate buffers
// TODO(tarcieri): use `Zeroizing` when const generics land
mac_key.as_mut_slice().zeroize();
enc_key.as_mut_slice().zeroize();
block.as_mut_slice().zeroize();

let mut buffer = Vec::with_capacity(payload.msg.len() + tag_size);
buffer.extend_from_slice(payload.msg);

let tag = self.encrypt_in_place(&mut buffer, payload.aad)?;
buffer.extend_from_slice(tag.as_slice());
Ok(buffer)
result
}

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

let tag = self.compute_tag(associated_data, buffer);
Ctr32::new(&self.enc_cipher, tag).apply_keystream(buffer);
Ctr32::new(&self.enc_cipher, &tag).apply_keystream(buffer);
Ok(tag)
}

/// Decrypt the given message, allocating a vector for the resulting plaintext
pub(crate) fn decrypt(self, payload: Payload<'_, '_>) -> Result<Vec<u8>, Error> {
let tag_size = <Polyval as UniversalHash>::BlockSize::to_usize();

if payload.msg.len() < tag_size {
return Err(Error);
}

let tag_start = payload.msg.len() - tag_size;
let mut buffer = Vec::from(&payload.msg[..tag_start]);
let tag = GenericArray::from_slice(&payload.msg[tag_start..]);
self.decrypt_in_place(&mut buffer, payload.aad, *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(
pub(crate) fn decrypt_in_place_detached(
mut self,
buffer: &mut [u8],
associated_data: &[u8],
tag: Tag,
buffer: &mut [u8],
tag: &Tag,
) -> Result<(), Error> {
if buffer.len() as u64 > C_MAX || associated_data.len() as u64 > A_MAX {
return Err(Error);
Expand Down Expand Up @@ -290,9 +315,19 @@ where
*byte ^= self.nonce[i];
}

// Clear the highest bit
tag[15] &= 0x7f;

self.enc_cipher.encrypt_block(&mut tag);
tag
}
}

impl<C> Drop for AesGcmSiv<C>
where
C: BlockCipher<BlockSize = U16, ParBlocks = U8>,
{
fn drop(&mut self) {
self.key.as_mut_slice().zeroize();
}
}
26 changes: 14 additions & 12 deletions chacha20poly1305/src/cipher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ use aead::{Error, Payload};
use alloc::vec::Vec;
use chacha20::stream_cipher::{SyncStreamCipher, SyncStreamCipherSeek};
use core::convert::TryInto;
use poly1305::{universal_hash::UniversalHash, Poly1305, Tag};
use poly1305::{universal_hash::UniversalHash, Poly1305};
use zeroize::Zeroizing;

use super::Tag;

/// ChaCha20Poly1305 instantiated with a particular nonce
pub(crate) struct Cipher<C>
where
Expand Down Expand Up @@ -39,16 +41,16 @@ where
let mut buffer = Vec::with_capacity(payload.msg.len() + poly1305::BLOCK_SIZE);
buffer.extend_from_slice(payload.msg);

let tag = self.encrypt_in_place(&mut buffer, payload.aad)?;
buffer.extend_from_slice(tag.into_bytes().as_slice());
let tag = self.encrypt_in_place_detached(payload.aad, &mut buffer)?;
buffer.extend_from_slice(tag.as_slice());
Ok(buffer)
}

/// Encrypt the given message in-place, returning the authentication tag
pub(crate) fn encrypt_in_place(
pub(crate) fn encrypt_in_place_detached(
mut self,
buffer: &mut [u8],
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag, Error> {
if buffer.len() / chacha20::BLOCK_SIZE >= chacha20::MAX_BLOCKS {
return Err(Error);
Expand All @@ -58,7 +60,7 @@ where
self.cipher.apply_keystream(buffer);
self.mac.update_padded(buffer);
self.authenticate_lengths(associated_data, buffer)?;
Ok(self.mac.result())
Ok(self.mac.result().into_bytes())
}

/// Decrypt the given message, allocating a vector for the resulting plaintext
Expand All @@ -69,19 +71,19 @@ where

let tag_start = payload.msg.len() - poly1305::BLOCK_SIZE;
let mut buffer = Vec::from(&payload.msg[..tag_start]);
let tag: [u8; poly1305::BLOCK_SIZE] = payload.msg[tag_start..].try_into().unwrap();
self.decrypt_in_place(&mut buffer, payload.aad, &tag)?;
let tag = Tag::from_slice(&payload.msg[tag_start..]);
self.decrypt_in_place_detached(payload.aad, &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(
pub(crate) fn decrypt_in_place_detached(
mut self,
buffer: &mut [u8],
associated_data: &[u8],
tag: &[u8; poly1305::BLOCK_SIZE],
buffer: &mut [u8],
tag: &Tag,
) -> Result<(), Error> {
if buffer.len() / chacha20::BLOCK_SIZE >= chacha20::MAX_BLOCKS {
return Err(Error);
Expand All @@ -92,7 +94,7 @@ where
self.authenticate_lengths(associated_data, buffer)?;

// This performs a constant-time comparison using the `subtle` crate
if self.mac.verify(GenericArray::from_slice(tag)).is_ok() {
if self.mac.verify(tag).is_ok() {
self.cipher.apply_keystream(buffer);
Ok(())
} else {
Expand Down
33 changes: 33 additions & 0 deletions chacha20poly1305/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ use alloc::vec::Vec;
use chacha20::{stream_cipher::NewStreamCipher, ChaCha20};
use zeroize::Zeroize;

/// Poly1305 tags
pub type Tag = GenericArray<u8, U16>;

/// ChaCha20Poly1305 Authenticated Encryption with Additional Data (AEAD)
#[derive(Clone)]
pub struct ChaCha20Poly1305 {
Expand Down Expand Up @@ -71,6 +74,36 @@ impl Aead for ChaCha20Poly1305 {
}
}

impl ChaCha20Poly1305 {
/// Encrypt the data in-place, returning the authentication tag
pub fn encrypt_in_place_detached(
&self,
nonce: &GenericArray<u8, <Self as Aead>::NonceSize>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag, Error> {
Cipher::new(ChaCha20::new(&self.key, nonce))
.encrypt_in_place_detached(associated_data, buffer)
}

/// Decrypt the data in-place, returning an error in the event the provided
/// authentication tag does not match the given ciphertext (i.e. ciphertext
/// is modified/unauthentic)
pub fn decrypt_in_place_detached(
&self,
nonce: &GenericArray<u8, <Self as Aead>::NonceSize>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag,
) -> Result<(), Error> {
Cipher::new(ChaCha20::new(&self.key, nonce)).decrypt_in_place_detached(
associated_data,
buffer,
tag,
)
}
}

impl Drop for ChaCha20Poly1305 {
fn drop(&mut self) {
self.key.as_mut_slice().zeroize();
Expand Down
32 changes: 31 additions & 1 deletion chacha20poly1305/src/xchacha20poly1305.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! XChaCha20Poly1305 is an extended nonce variant of ChaCha20Poly1305

use crate::cipher::Cipher;
use crate::{cipher::Cipher, Tag};
use aead::generic_array::{
typenum::{U0, U16, U24, U32},
GenericArray,
Expand Down Expand Up @@ -69,6 +69,36 @@ impl Aead for XChaCha20Poly1305 {
}
}

impl XChaCha20Poly1305 {
/// Encrypt the data in-place, returning the authentication tag
pub fn encrypt_in_place_detached(
&self,
nonce: &GenericArray<u8, <Self as Aead>::NonceSize>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag, Error> {
Cipher::new(XChaCha20::new(&self.key, nonce))
.encrypt_in_place_detached(associated_data, buffer)
}

/// Decrypt the data in-place, returning an error in the event the provided
/// authentication tag does not match the given ciphertext (i.e. ciphertext
/// is modified/unauthentic)
pub fn decrypt_in_place_detached(
&self,
nonce: &GenericArray<u8, <Self as Aead>::NonceSize>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag,
) -> Result<(), Error> {
Cipher::new(XChaCha20::new(&self.key, nonce)).decrypt_in_place_detached(
associated_data,
buffer,
tag,
)
}
}

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