Skip to content

Commit 25c2b9e

Browse files
committed
aead: add explicit nonce API
Building towards a full solution to #1666, this adds an initial API which supports explicit nonces, implemented as a prefix to the AEAD message. Putting the nonce in any other position than the message prefix doesn't make sense. Nothing else works that way. There are multiple possible permutations like putting the nonce between the ciphertext, or at the end, but nobody does that, and the best thing we can do for users is eliminate unnecessary choices.
1 parent ad1c1ac commit 25c2b9e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

aead/src/lib.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,46 @@ pub trait Aead: AeadCore {
213213
nonce: &Nonce<Self>,
214214
ciphertext: impl Into<Payload<'msg, 'aad>>,
215215
) -> Result<Vec<u8>>;
216+
217+
/// Encrypt an AEAD message, explicitly prepending the nonce as a prefix to
218+
/// the resulting AEAD message.
219+
fn encrypt_with_explicit_nonce<'msg, 'aad>(
220+
&self,
221+
nonce: &Nonce<Self>,
222+
plaintext: impl Into<Payload<'msg, 'aad>>,
223+
) -> Result<Vec<u8>> {
224+
let payload = plaintext.into();
225+
let mut out = Vec::with_capacity(
226+
Self::NonceSize::to_usize() + payload.msg.len() + Self::TagSize::to_usize(),
227+
);
228+
229+
let ciphertext = self.encrypt(nonce, payload)?;
230+
out.extend_from_slice(nonce);
231+
out.extend_from_slice(&ciphertext);
232+
Ok(out)
233+
}
234+
235+
/// Decrypt an AEAD message which has an explicit nonce prepended to the
236+
/// AEAD message.
237+
fn decrypt_with_explicit_nonce<'msg, 'aad>(
238+
&self,
239+
payload: impl Into<Payload<'msg, 'aad>>,
240+
) -> Result<Vec<u8>> {
241+
let payload = payload.into();
242+
243+
if payload.msg.len() < Self::NonceSize::to_usize() {
244+
return Err(Error);
245+
}
246+
247+
let (nonce, ciphertext) = payload.msg.split_at(Self::NonceSize::to_usize());
248+
self.decrypt(
249+
&nonce.try_into().unwrap(),
250+
Payload {
251+
msg: ciphertext,
252+
aad: payload.aad,
253+
},
254+
)
255+
}
216256
}
217257

218258
#[cfg(feature = "alloc")]

0 commit comments

Comments
 (0)