1// Copyright 2018 Brian Smith.
2//
3// Permission to use, copy, modify, and/or distribute this software for any
4// purpose with or without fee is hereby granted, provided that the above
5// copyright notice and this permission notice appear in all copies.
6//
7// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES
8// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
10// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12// OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13// CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
14
15use crate::error;
16
17/// A nonce for a single AEAD opening or sealing operation.
18///
19/// The user must ensure, for a particular key, that each nonce is unique.
20///
21/// `Nonce` intentionally doesn't implement `Clone` to ensure that each one is
22/// consumed at most once.
23pub struct Nonce([u8; NONCE_LEN]);
24
25impl Nonce {
26 /// Constructs a `Nonce` with the given value, assuming that the value is
27 /// unique for the lifetime of the key it is being used with.
28 ///
29 /// Fails if `value` isn't `NONCE_LEN` bytes long.
30 #[inline]
31 pub fn try_assume_unique_for_key(value: &[u8]) -> Result<Self, error::Unspecified> {
32 let value: &[u8; NONCE_LEN] = value.try_into()?;
33 Ok(Self::assume_unique_for_key(*value))
34 }
35
36 /// Constructs a `Nonce` with the given value, assuming that the value is
37 /// unique for the lifetime of the key it is being used with.
38 #[inline]
39 pub fn assume_unique_for_key(value: [u8; NONCE_LEN]) -> Self {
40 Self(value)
41 }
42}
43
44impl AsRef<[u8; NONCE_LEN]> for Nonce {
45 fn as_ref(&self) -> &[u8; NONCE_LEN] {
46 &self.0
47 }
48}
49
50/// All the AEADs we support use 96-bit nonces.
51pub const NONCE_LEN: usize = 96 / 8;
52