rainier_crypt/lib.rs
1//! # rainier-crypt
2//!
3//! Reversible encryption and message signing — Laravel's `Crypt`, plus the
4//! signing half that Laravel spreads across signed URLs and cookie
5//! integrity.
6//!
7//! ```
8//! use rainier_crypt::{Encryption, Key, KeyRing};
9//!
10//! # fn main() -> rainier_support::Result<()> {
11//! let crypt = Encryption::from_keys(KeyRing::new(Key::generate()));
12//!
13//! let sealed = crypt.encrypt("a card number")?;
14//! assert_eq!(crypt.decrypt(&sealed)?, "a card number");
15//!
16//! // Signed, not sealed: the value stays readable, but not writable.
17//! let signed = crypt.sign("unsubscribe-42")?;
18//! assert!(signed.starts_with("unsubscribe-42."));
19//! assert_eq!(crypt.verify(&signed)?, "unsubscribe-42");
20//! # Ok(()) }
21//! ```
22//!
23//! ## Encrypt or sign?
24//!
25//! | | Hidden | Tamper-evident | Use for |
26//! |---|---|---|---|
27//! | [`encrypt`](Encryption::encrypt) | yes | yes | anything the client must not read |
28//! | [`sign`](Encryption::sign) | no | yes | anything the client may read but not change |
29//!
30//! Reach for signing when the value is not a secret. An unsubscribe link, a
31//! reset token, a "remember this choice" cookie — encrypting those makes them
32//! opaque in your own logs for no gain.
33//!
34//! ## This is not password hashing
35//!
36//! Passwords are hashed, never encrypted, and that lives in `rainier-auth`'s
37//! `Hasher`. If you can get the value back out, it is the wrong tool for a
38//! password — see the [hashing docs](https://github.com/safewords/rainier-framework/blob/main/docs/hashing.md).
39//!
40//! ## Rotation is designed in
41//!
42//! Every payload records which key produced it, and a [`KeyRing`] holds one
43//! current key plus any number of retired ones. Rotating is a deploy:
44//!
45//! ```
46//! # use rainier_crypt::{Encryption, Key, KeyRing};
47//! # fn main() -> rainier_support::Result<()> {
48//! # let retired = Key::generate();
49//! # let sealed = Encryption::from_keys(KeyRing::new(retired.clone())).encrypt("old")?;
50//! let crypt = Encryption::from_keys(
51//! KeyRing::new(Key::generate()).with_previous(retired),
52//! );
53//!
54//! // Written with the old key, still readable; anything new uses the new one.
55//! assert_eq!(crypt.decrypt(&sealed)?, "old");
56//! # Ok(()) }
57//! ```
58//!
59//! Retrofitting that is painful, which is why it is here from the first
60//! release rather than deferred until a key is known to have leaked.
61
62#![deny(missing_docs)]
63#![deny(rustdoc::broken_intra_doc_links)]
64
65pub mod asymmetric;
66pub mod cipher;
67pub mod encrypter;
68pub mod key;
69pub mod signer;
70
71pub use asymmetric::{
72 BoxKeyPair, BoxPublicKey, Ed25519Signer, SealedBox, SigningKeyPair, VerifyingPublicKey,
73};
74pub use cipher::Cipher;
75pub use encrypter::{AeadEncrypter, Encrypter, EncrypterExt};
76pub use key::{Key, KeyRing, KEY_LEN};
77pub use signer::{HmacSigner, Signer, SignerExt};
78
79use std::sync::Arc;
80
81use rainier_support::Result;
82use serde::de::DeserializeOwned;
83use serde::Serialize;
84
85/// The application's encrypter and signer, as one container-storable value.
86///
87/// A newtype over the two ports rather than binding them separately, so
88/// swapping either does not change a call site — the same reason
89/// `rainier-framework`'s `Views` wraps a view engine.
90#[derive(Clone)]
91pub struct Encryption {
92 encrypter: Arc<dyn Encrypter>,
93 signer: Arc<dyn Signer>,
94}
95
96impl Encryption {
97 /// Wrap an encrypter and a signer.
98 pub fn new(encrypter: Arc<dyn Encrypter>, signer: Arc<dyn Signer>) -> Self {
99 Self { encrypter, signer }
100 }
101
102 /// The default pairing — XChaCha20-Poly1305 and HMAC-SHA256 over one ring.
103 pub fn from_keys(keys: KeyRing) -> Self {
104 Self::from_keys_with(keys, Cipher::default())
105 }
106
107 /// The same, with an explicit [`Cipher`].
108 ///
109 /// Reading is unaffected: a payload names its own algorithm, so switching
110 /// this does not strand anything already written.
111 pub fn from_keys_with(keys: KeyRing, cipher: Cipher) -> Self {
112 Self::new(
113 Arc::new(AeadEncrypter::new(keys.clone()).with_cipher(cipher)),
114 Arc::new(HmacSigner::new(keys)),
115 )
116 }
117
118 /// The encrypter.
119 pub fn encrypter(&self) -> &Arc<dyn Encrypter> {
120 &self.encrypter
121 }
122
123 /// The signer.
124 pub fn signer(&self) -> &Arc<dyn Signer> {
125 &self.signer
126 }
127
128 /// Encrypt a string.
129 pub fn encrypt(&self, plain: &str) -> Result<String> {
130 self.encrypter.encrypt(plain)
131 }
132
133 /// Decrypt a string.
134 pub fn decrypt(&self, payload: &str) -> Result<String> {
135 self.encrypter.decrypt(payload)
136 }
137
138 /// Encrypt raw bytes.
139 pub fn encrypt_bytes(&self, plain: &[u8]) -> Result<String> {
140 self.encrypter.encrypt_bytes(plain)
141 }
142
143 /// Decrypt to raw bytes.
144 pub fn decrypt_bytes(&self, payload: &str) -> Result<Vec<u8>> {
145 self.encrypter.decrypt_bytes(payload)
146 }
147
148 /// Encrypt any serialisable value as JSON.
149 pub fn encrypt_json<T: Serialize>(&self, value: &T) -> Result<String> {
150 self.encrypter.encrypt_json(value)
151 }
152
153 /// Decrypt JSON back into a value.
154 pub fn decrypt_json<T: DeserializeOwned>(&self, payload: &str) -> Result<T> {
155 self.encrypter.decrypt_json(payload)
156 }
157
158 /// Sign a value, leaving it readable.
159 pub fn sign(&self, value: &str) -> Result<String> {
160 self.signer.sign(value)
161 }
162
163 /// Recover a signed value, or fail if it was altered.
164 pub fn verify(&self, signed: &str) -> Result<String> {
165 self.signer.verify(signed)
166 }
167
168 /// Whether a signed value is intact.
169 pub fn is_valid(&self, signed: &str) -> bool {
170 self.signer.is_valid(signed)
171 }
172}
173
174impl std::fmt::Debug for Encryption {
175 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176 f.write_str("Encryption(..)")
177 }
178}
179
180#[cfg(test)]
181mod tests {
182 use super::*;
183
184 #[test]
185 fn the_facade_value_does_both_halves() {
186 let crypt = Encryption::from_keys(KeyRing::new(Key::generate()));
187
188 assert_eq!(crypt.decrypt(&crypt.encrypt("sealed").unwrap()).unwrap(), "sealed");
189 assert_eq!(crypt.verify(&crypt.sign("signed").unwrap()).unwrap(), "signed");
190 }
191
192 #[test]
193 fn json_round_trips_through_the_facade_value() {
194 let crypt = Encryption::from_keys(KeyRing::new(Key::generate()));
195 let payload = crypt.encrypt_json(&vec![1u8, 2, 3]).unwrap();
196
197 assert_eq!(crypt.decrypt_json::<Vec<u8>>(&payload).unwrap(), vec![1, 2, 3]);
198 }
199
200 #[test]
201 fn debug_does_not_disclose_anything() {
202 let crypt = Encryption::from_keys(KeyRing::new(Key::from_bytes([3u8; KEY_LEN])));
203 assert_eq!(format!("{crypt:?}"), "Encryption(..)");
204 }
205}