Skip to main content

open

Function open 

Source
pub fn open<T, K>(blob: &[u8], key: Option<K>) -> Result<T, SerializationError>
where T: Decode<()>, K: AsRef<str>,
Expand description

Decode a byte blob produced by seal back into T.

If key is None the default key is used. String literals and owned Strings are both accepted. Returns an error if the key is wrong, the blob is truncated, or the ciphertext has been tampered with — the Poly1305 tag prevents decryption of modified data.

§Errors

Examples found in repository?
examples/serialization_macros.rs (line 195)
164fn demo_serialize_variable_mode() -> Result<(), Box<dyn std::error::Error>> {
165    println!("── #[serialize] / #[deserialize]  variable mode ─────────────────");
166
167    let payload = Payload { id: 42, data: "hello, world".into() };
168
169    // ── Default key ───────────────────────────────────────────────────────────
170    // `#[serialize(payload)]` expands to:
171    //     let blob: Vec<u8> = toolkit_zero::serialization::seal(&payload, None)?;
172    #[serialize(payload)]
173    fn blob() -> Vec<u8> {}
174
175    // `#[deserialize(blob)]` expands to:
176    //     let restored: Payload = toolkit_zero::serialization::open::<Payload, _>(&blob, None)?;
177    #[deserialize(blob)]
178    fn restored() -> Payload {}
179
180    assert_eq!(payload, restored);
181    println!("  default key  : {} bytes → {:?}", blob.len(), restored);
182
183    // ── Custom key ────────────────────────────────────────────────────────────
184    // The `key = <expr>` argument accepts any expression that evaluates to `String`.
185    #[serialize(payload, key = "custom-key".to_string())]
186    fn blob_keyed() -> Vec<u8> {}
187
188    #[deserialize(blob_keyed, key = "custom-key".to_string())]
189    fn restored_keyed() -> Payload {}
190
191    assert_eq!(payload, restored_keyed);
192    println!("  custom key   : {} bytes → {:?}", blob_keyed.len(), restored_keyed);
193
194    // ── Cross-key failure check ───────────────────────────────────────────────
195    let wrong = toolkit_zero::serialization::open::<Payload, String>(&blob_keyed, None);
196    assert!(wrong.is_err(), "decrypting with the wrong key must fail");
197    println!("  wrong key    : open → Err (expected) ✓");
198
199    println!();
200    Ok(())
201}
More examples
Hide additional examples
examples/seal_open.rs (line 54)
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}