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 15 use crate::error; 16 use core::convert::TryInto; 17 18 /// A nonce for a single AEAD opening or sealing operation. 19 /// 20 /// The user must ensure, for a particular key, that each nonce is unique. 21 /// 22 /// `Nonce` intentionally doesn't implement `Clone` to ensure that each one is 23 /// consumed at most once. 24 pub struct Nonce([u8; NONCE_LEN]); 25 26 impl Nonce { 27 /// Constructs a `Nonce` with the given value, assuming that the value is 28 /// unique for the lifetime of the key it is being used with. 29 /// 30 /// Fails if `value` isn't `NONCE_LEN` bytes long. 31 #[inline] try_assume_unique_for_key(value: &[u8]) -> Result<Self, error::Unspecified>32 pub fn try_assume_unique_for_key(value: &[u8]) -> Result<Self, error::Unspecified> { 33 let value: &[u8; NONCE_LEN] = value.try_into()?; 34 Ok(Self::assume_unique_for_key(*value)) 35 } 36 37 /// Constructs a `Nonce` with the given value, assuming that the value is 38 /// unique for the lifetime of the key it is being used with. 39 #[inline] assume_unique_for_key(value: [u8; NONCE_LEN]) -> Self40 pub fn assume_unique_for_key(value: [u8; NONCE_LEN]) -> Self { 41 Self(value) 42 } 43 } 44 45 impl AsRef<[u8; NONCE_LEN]> for Nonce { as_ref(&self) -> &[u8; NONCE_LEN]46 fn as_ref(&self) -> &[u8; NONCE_LEN] { 47 &self.0 48 } 49 } 50 51 /// All the AEADs we support use 96-bit nonces. 52 pub const NONCE_LEN: usize = 96 / 8; 53