1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
use hacl_star_sys as ffi; use crate::And; pub mod secret { use super::*; pub const KEY_LENGTH: usize = 32; pub const NONCE_LENGTH: usize = 24; pub const MAC_LENGTH: usize = 16; pub type SecretBox<'a> = And<&'a Key, &'a Nonce>; define!{ pub struct Key/key(pub [u8; KEY_LENGTH]); pub struct Nonce/nonce(pub [u8; NONCE_LENGTH]); } impl Key { #[inline] pub fn nonce<'a>(&'a self, n: &'a [u8; NONCE_LENGTH]) -> SecretBox<'a> { And(self, nonce(n)) } } impl<'a> SecretBox<'a> { pub fn seal(self, m: &[u8], c: &mut [u8], mac: &mut [u8; MAC_LENGTH]) { assert!(c.len() > 32); assert_eq!(c.len(), m.len()); let And(Key(key), Nonce(nonce)) = self; unsafe { ffi::nacl::NaCl_crypto_secretbox_detached( c.as_mut_ptr(), mac.as_mut_ptr(), m.as_ptr() as _, (m.len() - 32) as _, nonce.as_ptr() as _, key.as_ptr() as _ ); } } pub fn open(self, m: &mut [u8], c: &[u8], mac: &[u8; MAC_LENGTH]) -> bool { assert!(c.len() > 32); assert_eq!(c.len(), m.len()); let And(Key(key), Nonce(nonce)) = self; unsafe { ffi::nacl::NaCl_crypto_secretbox_open_detached( m.as_mut_ptr(), c.as_ptr() as _, mac.as_ptr() as _, (c.len() - 32) as _, nonce.as_ptr() as _, key.as_ptr() as _ ) == 0 } } } } pub mod sealed { use super::*; pub use crate::curve25519::{ PUBLIC_LENGTH, SECRET_LENGTH, SecretKey, PublicKey, keypair }; pub use super::secret::{ NONCE_LENGTH, MAC_LENGTH, Nonce }; pub type PreSealedBox<'a> = And<&'a SecretKey, &'a PublicKey>; pub type SealedBox<'a> = And<And<&'a SecretKey, &'a PublicKey>, &'a Nonce>; impl SecretKey { #[inline] pub fn and<'a>(&'a self, pk: &'a PublicKey) -> And<&'a SecretKey, &'a PublicKey> { And(self, pk) } } impl<'a> PreSealedBox<'a> { #[inline] pub fn nonce(&self, n: &'a [u8; NONCE_LENGTH]) -> SealedBox<'a> { And(And(self.0, self.1), secret::nonce(n)) } } impl<'a> SealedBox<'a> { pub fn seal(self, m: &[u8], c: &mut [u8], mac: &mut [u8; MAC_LENGTH]) { assert!(c.len() > 32); assert_eq!(m.len(), c.len()); let And(And(SecretKey(sk), PublicKey(pk)), Nonce(nonce)) = self; unsafe { ffi::nacl::NaCl_crypto_box_detached( c.as_mut_ptr(), mac.as_mut_ptr(), m.as_ptr() as _, (m.len() - 32) as _, nonce.as_ptr() as _, pk.as_ptr() as _, sk.as_ptr() as _ ); } } pub fn open(self, m: &mut [u8], c: &[u8], mac: &[u8; MAC_LENGTH]) -> bool { assert!(c.len() > 32); assert_eq!(m.len(), c.len()); let And(And(SecretKey(sk), PublicKey(pk)), Nonce(nonce)) = self; unsafe { ffi::nacl::NaCl_crypto_box_open_detached( m.as_mut_ptr(), c.as_ptr() as _, mac.as_ptr() as _, (c.len() - 32) as _, nonce.as_ptr() as _, pk.as_ptr() as _, sk.as_ptr() as _ ) == 0 } } } }