pub fn seal<T, K>(
value: &T,
key: Option<K>,
) -> Result<Vec<u8>, SerializationError>Expand description
Encode value to an authenticated, encrypted byte blob sealed with key.
Encryption uses ChaCha20-Poly1305 (IETF) with a freshly generated 12-byte random nonce prepended to the output. Every call produces a different ciphertext even for the same plaintext and key.
If key is None the default key "serialization/deserialization" is
used. String literals (Some("key")) and owned Strings are both accepted.
The resulting blob can only be decoded by open with the same key.
§Errors
Returns SerializationError::Encode if bincode cannot serialise the
value.
Examples found in repository?
examples/seal_open.rs (line 42)
29fn main() {
30 let key = "my-secret-key";
31
32 let original = Payload {
33 user: "alice".into(),
34 score: 9001,
35 tags: vec!["rust".into(), "crypto".into()],
36 };
37
38 println!("Original : {original:?}");
39
40 // ── Seal ──────────────────────────────────────────────────────────────────
41 // String literals and &str both work; K: AsRef<str> handles the conversion.
42 let blob = seal(&original, Some(key)).expect("seal failed");
43 println!("Sealed : {} bytes (nonce ‖ ciphertext ‖ Poly1305 tag)", blob.len());
44
45 // ── Semantic security ─────────────────────────────────────────────────────
46 // A fresh random 12-byte nonce is generated on every seal call, so identical
47 // plaintext + key still produces a different ciphertext each time.
48 let blob2 = seal(&original, Some(key)).expect("seal failed");
49 assert_ne!(blob, blob2, "ciphertexts should differ (different nonces)");
50 println!("Semantic security : two seals of the same value differ ✓");
51
52 // ── Open ──────────────────────────────────────────────────────────────────
53 // Reconstructs Payload from the opaque blob using the same key.
54 let recovered: Payload = open(&blob, Some(key)).expect("open failed");
55 println!("Recovered: {recovered:?}");
56
57 assert_eq!(original, recovered, "round-trip mismatch!");
58 println!("\nRound-trip successful ✓");
59
60 // ── Wrong key rejects ─────────────────────────────────────────────────────
61 let bad: Result<Payload, _> = open(&blob, Some("wrong-key"));
62 assert!(bad.is_err(), "wrong key should fail to open");
63 println!("Wrong-key rejection ✓");
64
65 // ── Default key ───────────────────────────────────────────────────────────
66 // Pass None::<&str> to use the built-in default key.
67 let blob3 = seal(&original, None::<&str>).expect("seal with default key failed");
68 let back3: Payload = open(&blob3, None::<&str>).expect("open with default key failed");
69 assert_eq!(original, back3);
70 println!("Default-key round-trip ✓");
71}