arx_kw/lib.rs
1#![forbid(unsafe_code)]
2#![warn(clippy::pedantic)]
3#![warn(clippy::nursery)]
4#![allow(clippy::doc_markdown)]
5#![warn(clippy::all)]
6#![warn(missing_docs)]
7#![doc = include_str!("../README.md")]
8
9#[macro_use]
10#[cfg(any(feature = "e", feature = "g", feature = "ex", feature = "gx"))]
11extern crate arrayref;
12extern crate thiserror;
13use thiserror::Error;
14pub use zeroize::{Zeroize, Zeroizing};
15#[cfg(feature = "envelope")]
16mod envelope;
17mod memory;
18#[cfg(any(feature = "e", feature = "g", feature = "ex", feature = "gx"))]
19mod sip;
20#[cfg(feature = "envelope")]
21pub use envelope::{ENVELOPE_HEADER_LENGTH, MAX_CONTEXT_LENGTH};
22pub use memory::{SecretBytes, SecretKey, MAX_INPUT_LENGTH};
23#[cfg(any(feature = "g", feature = "gx"))]
24mod generate;
25#[cfg(any(feature = "e", feature = "g", feature = "ex", feature = "gx"))]
26mod lqb;
27#[cfg(any(feature = "e", feature = "g", feature = "ex", feature = "gx"))]
28mod util;
29
30#[cfg(feature = "e")]
31/// Module containing items related to the ARX-KW-8-2-4-E variant
32pub mod e;
33#[cfg(feature = "ex")]
34/// Module containing items related to the ARX-KW-8-2-4-EX variant
35pub mod ex;
36#[cfg(feature = "g")]
37/// Module containing items related to the ARX-KW-8-2-4-G variant
38pub mod g;
39#[cfg(feature = "gx")]
40/// Module containing items related to the ARX-KW-8-2-4-GX variant
41pub mod gx;
42pub use subtle::{Choice, ConstantTimeEq};
43
44#[derive(Error, Debug)]
45/// An error denoting that a value was of an invalid length. Typically this will be used as a
46/// variant of [`ArxKwError`] rather than on its own.
47pub enum InvalidLengthError {
48 #[error("Invalid length: {0} (expected {1})")]
49 /// Invalid length in a context expecting a fixed length.
50 _Fixed(usize, usize),
51 /// Invalid length in a context which accepts a variable length (e.g. plaintext and ciphertext
52 /// inputs)
53 #[error("Invalid length: {0} (Maximum: {1})")]
54 UpTo(usize, usize),
55}
56#[derive(Error, Debug)]
57/// The error type used by this crate.
58pub enum ArxKwError {
59 #[error("Invalid length: {0}")]
60 /// See [`InvalidLengthError`]
61 InvalidLength(#[from] InvalidLengthError),
62 #[error("{0}")]
63 /// Occurs if a function using either ChaCha8 or XChaCha8 reaches the end of the stream
64 ChaChaError(String),
65 #[error("Authentication failed")]
66 /// Returns if an authentication tag mismatch occurs during decryption
67 BadTags,
68 /// A blob must contain at least its 16-byte authentication tag.
69 #[error("Invalid blob length: {0} (minimum: 16)")]
70 InvalidBlobLength(usize),
71 /// The allocator rejected an output buffer request.
72 #[error("Unable to allocate output buffer")]
73 AllocationFailed,
74 /// Envelope magic, version, variant, or reserved bytes are invalid.
75 #[error("Invalid or unsupported envelope")]
76 InvalidEnvelope,
77 /// Application context exceeds the documented maximum.
78 #[error("Application context is too long")]
79 ContextTooLong,
80 /// HKDF could not produce a key of the requested size.
81 #[error("Context key derivation failed")]
82 KeyDerivationFailed,
83}
84
85/// The 16-byte authentication tag stored alongside encrypted keys.
86///
87/// This is the same for all variants at time of writing (a single, static 128 bits), making
88/// for a 50% storage overhead for a 256-bit key like those used for `ChaCha`
89///
90/// The [`ConstantTimeEq`] trait is implemented (and re-exported from the `subtle` crate by this crate) for constant
91/// time equality checking of `AuthTag`s
92#[derive(Debug, Clone, Copy, Zeroize)]
93pub struct AuthTag(pub [u8; 16]);
94impl std::convert::AsRef<[u8; 16]> for AuthTag {
95 fn as_ref(&self) -> &[u8; 16] {
96 &self.0
97 }
98}
99
100impl ConstantTimeEq for AuthTag {
101 fn ct_eq(&self, other: &Self) -> Choice {
102 self.0.ct_eq(&other.0)
103 }
104}
105/// Asserts equality using [`ConstantTimeEq`]. The second argument must be a reference.
106///
107/// The comparison is constant time for equal-length inputs; assertion failure still branches.
108/// This macro is intended for tests, not authentication decisions.
109#[macro_export]
110macro_rules! assert_ct_eq {
111 ($x:expr, $y:expr) => {{
112 #[allow(unused_imports)]
113 use $crate::ConstantTimeEq as _;
114 assert!(
115 bool::from(($x).ct_eq($y)),
116 "constant-time equality assertion failed"
117 );
118 }};
119}
120
121/// Provides deterministic, authenticated key wrapping.
122///
123/// Keys are fixed-length arrays; E and EX use 48 bytes, G and GX use 32 bytes.
124/// Plaintext and ciphertext are byte slices. E/G reject inputs over 64 bytes.
125/// Blob methods encode the 16-byte tag followed by ciphertext; applications
126/// can instead store the results of [`ArxKW::encrypt`] separately.
127pub trait ArxKW {
128 /// The type of data which is used as a key for the type that `impl`s this trait.
129 /// Note that this is not the same for all variants of ARX-KW. E and EX use 48-byte keys; G and GX use 32-byte keys
130 type Key: Copy + Zeroize + AsRef<[u8]> + AsMut<[u8]>;
131 /// Stable identifier stored in versioned envelopes (1=E, 2=G, 3=EX, 4=GX).
132 const VARIANT_ID: u8;
133 /// Maximum plaintext or ciphertext length accepted before allocation.
134 const MAX_INPUT_LENGTH: usize = MAX_INPUT_LENGTH;
135
136 /// Wraps key material into a versioned envelope bound to an application context.
137 /// Available with the `envelope` feature (enabled by default).
138 ///
139 /// Use a stable, application-specific context such as `b"example.com/storage/v1"`.
140 /// The context is not stored; supply exactly the same bytes during decryption.
141 /// # Errors
142 /// Returns an error for oversized inputs/context, allocation failure, or encryption failure.
143 #[cfg(feature = "envelope")]
144 fn encrypt_envelope(
145 key: &Self::Key,
146 plaintext: &[u8],
147 context: &[u8],
148 ) -> Result<Vec<u8>, ArxKwError> {
149 envelope::encrypt::<Self>(key, plaintext, context)
150 }
151
152 /// Opens a versioned envelope into plaintext that zeroizes when dropped.
153 /// Available with the `envelope` feature (enabled by default).
154 /// # Errors
155 /// Rejects invalid headers, wrong variants, oversized input/context, allocation
156 /// failure, and authentication failure (including a changed context).
157 #[cfg(feature = "envelope")]
158 fn decrypt_envelope(
159 key: &Self::Key,
160 input: &[u8],
161 context: &[u8],
162 ) -> Result<SecretBytes, ArxKwError> {
163 envelope::decrypt::<Self>(key, input, context)
164 }
165
166 /// Decrypts a legacy blob into plaintext that zeroizes when dropped.
167 /// # Errors
168 /// Returns the same errors as [`ArxKW::decrypt_blob`].
169 fn decrypt_secret(key: &Self::Key, blob: &[u8]) -> Result<SecretBytes, ArxKwError> {
170 Self::decrypt_blob(key, blob).map(SecretBytes::new)
171 }
172 /// Encrypts the plaintext using ARX-KW and returns the encrypted ciphertext and an [`AuthTag`]
173 ///
174 /// The authentication tag can be stored/transported alongside it and is needed (along with the
175 /// key used to encrypt the plaintext) in order to decrypt the wrapped key.
176 ///
177 /// # Errors
178 ///
179 /// Returns an error if the plaintext exceeds the variant limit or the
180 /// ChaCha stream is exhausted. Key lengths are checked by the type system.
181 fn encrypt(key: &Self::Key, plaintext: &[u8]) -> Result<(Vec<u8>, AuthTag), ArxKwError>;
182 /// Attempts to decrypt the ciphertext using ARX-KW and returns the decrypted plaintext if
183 /// successful. As ARX-KW is a form of authenticated encryption, the authenticity of the
184 /// decrypted text is verified if the function returns an `Ok` value.
185 ///
186 ///# Errors
187 ///
188 /// Returns an error if the ciphertext exceeds the variant limit, authentication fails,
189 /// or the ChaCha stream is exhausted. Key lengths are checked by the type system.
190 fn decrypt(
191 key: &Self::Key,
192 ciphertext: &[u8],
193 authentication_tag: &AuthTag,
194 ) -> Result<Vec<u8>, ArxKwError>;
195
196 /// Encrypts the plaintext and returns a [`Vec<u8>`] containing both the authentication tag
197 /// and the ciphertext.
198 ///
199 /// While ARX-KW by design eliminates the need for nonce management, it can
200 /// be further used to eliminate the complexity of managing authentication tags as well without
201 /// incurring a large storage overhead. The `encrypt_blob` and `decrypt_blob` methods allow for
202 /// this abstraction; the ciphertext and authentication tag can be treated as one opaque "blob" of bytes
203 /// and so authentication and decryption of that blob can be done with just the key,
204 /// eliminating the need to separately store a nonce or authentication tag. This gives a
205 /// user-friendly interface to deterministic and authenticated encryption.
206 ///
207 /// # Errors
208 ///
209 /// Returns an error if the plaintext exceeds the variant limit or the
210 /// ChaCha stream is exhausted. Key lengths are checked by the type system.
211 ///
212 ///```
213 /// # #[cfg(feature = "gx")]
214 /// # fn main() -> anyhow::Result<()> {
215 /// use arx_kw::{ArxKW,gx::GX,assert_ct_eq,ConstantTimeEq};
216 /// extern crate hex;
217 /// use hex::FromHex;
218 /// # extern crate anyhow;
219 ///
220 /// let key = <[u8; 32]>::from_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f")?; // The key being used to encrypt the plaintext
221 /// let plaintext = <[u8; 32]>::from_hex("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")?; // The key that we are trying to encrypt, as plaintext
222 /// // The expected output: a "blob" consisting of the authentication tag followed by ciphertext. This can be treated as one opaque piece of data when using encrypt_blob and decrypt_blob
223 /// let blob_expected = <[u8; 48]>::from_hex("016325cf6a3c4b2e3b039675e1ccbc652f83f391c97f3606ccd5709c6ee15d66cd7e65a2aeb7dc3066636e8f6b0d39c3")?;
224 /// let blob = GX::encrypt_blob(&key, &plaintext)?; // The output of encrypt_blob, a Vec<u8>
225 /// assert_ct_eq!(blob, &blob_expected);
226 /// # Ok(())
227 /// # }
228 /// # #[cfg(not(feature = "gx"))] fn main() {}
229 ///```
230 fn encrypt_blob(key: &Self::Key, plaintext: &[u8]) -> Result<Vec<u8>, ArxKwError> {
231 let (ciphertext, authentication_tag) = Self::encrypt(key, plaintext)?;
232 let mut blob = memory::allocate(
233 ciphertext
234 .len()
235 .checked_add(16)
236 .ok_or(ArxKwError::AllocationFailed)?,
237 )?;
238 blob.extend_from_slice(authentication_tag.as_ref());
239 blob.extend_from_slice(&ciphertext);
240 Ok(blob)
241 }
242
243 /// Decrypts a blob containing an authentication tag followed by the corresponding ciphertext
244 ///
245 /// If decryption is successful, returns a [`Vec<u8>`] containing the decrypted plaintext.
246 ///
247 /// While ARX-KW by design eliminates the need for nonce management, it can
248 /// be further used to eliminate the complexity of managing authentication tags as well without
249 /// incurring a large storage overhead. The `encrypt_blob` and `decrypt_blob` methods allow for
250 /// this abstraction; the ciphertext and authentication tag can be treated as one opaque "blob" of bytes
251 /// and so authentication and decryption of that blob can be done with just the key,
252 /// eliminating the need to separately store a nonce or authentication tag. This gives a
253 /// user-friendly interface to deterministic and authenticated encryption.
254 ///
255 /// # Errors
256 ///
257 /// Returns an error if the ciphertext exceeds the variant limit, the authentication tag does
258 /// not match the ciphertext that follows it, the blob contains fewer than 16 bytes,
259 /// or if the end of the \[X\]ChaCha stream is reached unexpectedly
260 ///
261 /// ```
262 /// # #[cfg(feature = "e")]
263 /// # fn main() -> anyhow::Result<()> {
264 /// use arx_kw::{ArxKW,e::E,assert_ct_eq,ConstantTimeEq};
265 /// extern crate hex;
266 /// use hex::FromHex;
267 /// # extern crate anyhow;
268 ///
269 /// let key = <[u8; 48]>::from_hex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f")?;
270 /// let blob = <[u8; 48]>::from_hex("c4f21d3b4dbcc566c3a73bbc59790f2fe6457d24abaf7c2ebdb91416a18366d31a66db61a4e45c9f42a119c353bb1eb1")?;
271 /// let plaintext_expected = <[u8;32]>::from_hex("deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef")?;
272 /// let plaintext = E::decrypt_blob(&key, &blob)?;
273 /// assert_ct_eq!(plaintext, &plaintext_expected);
274 /// # Ok(())
275 /// # }
276 /// # #[cfg(not(feature = "e"))] fn main() {}
277 ///```
278 ///
279 fn decrypt_blob(key: &Self::Key, blob: &[u8]) -> Result<Vec<u8>, ArxKwError> {
280 if blob.len() < 16 {
281 return Err(ArxKwError::InvalidBlobLength(blob.len()));
282 }
283 let mut tag = [0; 16];
284 tag.copy_from_slice(&blob[..16]);
285 let authentication_tag = AuthTag(tag);
286 let ciphertext = &blob[16..];
287 Self::decrypt(key, ciphertext, &authentication_tag)
288 }
289}