Skip to content

aead: add explicit nonce API #1818

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

Closed
wants to merge 4 commits into from
Closed
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
63 changes: 63 additions & 0 deletions aead/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,69 @@ pub trait Aead: AeadCore {
nonce: &Nonce<Self>,
ciphertext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>>;

/// Encrypt an AEAD message, explicitly prepending the nonce as a prefix to
/// the resulting AEAD message.
fn encrypt_with_explicit_nonce<'msg, 'aad>(
&self,
nonce: &Nonce<Self>,
plaintext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
let payload = plaintext.into();
let mut out = Vec::with_capacity(
Self::NonceSize::to_usize() + payload.msg.len() + Self::TagSize::to_usize(),
);

let ciphertext = self.encrypt(nonce, payload)?;
out.extend_from_slice(nonce);
out.extend_from_slice(&ciphertext);
Ok(out)
}

/// Encrypt with a random nonce generated by the specified RNG, explicitly
/// prepended to the message.
#[cfg(feature = "rand_core")]
fn encrypt_with_nonce_from_rng<'msg, 'aad, R: CryptoRng + ?Sized>(
&self,
rng: &mut R,
plaintext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
let nonce = Self::generate_nonce_with_rng(rng);
self.encrypt_with_explicit_nonce(&nonce, plaintext)
}

/// Encrypt with a random nonce securely generated by the OS random number
/// generator, explicitly prepended to the message.
#[cfg(feature = "os_rng")]
fn encrypt_with_random_nonce<'msg, 'aad>(
&self,
plaintext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
let nonce = Self::generate_nonce().map_err(|_| Error)?;
self.encrypt_with_explicit_nonce(&nonce, plaintext)
}

/// Decrypt an AEAD message which has an explicit nonce prepended to the
/// AEAD message.
fn decrypt_with_explicit_nonce<'msg, 'aad>(
&self,
payload: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>> {
let payload = payload.into();

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

let (nonce, ciphertext) = payload.msg.split_at(Self::NonceSize::to_usize());
self.decrypt(
&nonce.try_into().expect("msg should at least nonce-length"),
Payload {
msg: ciphertext,
aad: payload.aad,
},
)
}
}

#[cfg(feature = "alloc")]
Expand Down