moonproof-contracts 0.2.1

Node-side host orchestration for the moonproof contract pipeline — providers, deploy/call/maintenance lifecycle, fee balancing, submission, indexer-driven sync
Documentation
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Wire-compatible port of
//! `@midnight-ntwrk/midnight-js-level-private-state-provider/src/storage-encryption.ts`.
//!
//! The TS package wraps every export/import payload in a base64-encoded
//! AES-256-GCM ciphertext with a header that pins the version, the
//! KDF salt, and the GCM IV/tag, so a payload encrypted on one runtime
//! decrypts on the other. This module re-implements the TS encoder
//! exactly:
//!
//! ```text
//! base64( [ version u8 = 2 || salt[32] || iv[12] || tag[16] || ct ] )
//! ```
//!
//! * `salt` is per-export random bytes (TS uses CSPRNG, we use the
//!   caller-supplied [`rand::CryptoRng`]).
//! * `iv` is per-encryption random bytes (12 bytes, GCM standard).
//! * `tag` is the 16-byte GCM authentication tag.
//! * `ct` is the AES-256-GCM ciphertext over the UTF-8 plaintext.
//!
//! ## Versioning
//!
//! `V1` (PBKDF2 100k iterations) is recognised on import for
//! interop with old TS exports but never emitted. `V2` (PBKDF2 600k
//! iterations) is the only encoder. Both numbers come from
//! `storage-encryption.ts:31-32` (`PBKDF2_ITERATIONS_V1` /
//! `_V2`) and must not drift — the tag is over the salt+iv+version
//! prefix implicitly, but the iteration count is *not* in the header
//! so a wrong count silently produces a tag-mismatch decryption error,
//! which is the desired oracle-resistant behaviour (see TS `import`
//! comment in `level-private-state-provider.ts:919`).
//!
//! ## Failure modes (matched to TS)
//!
//! | TS error                         | Rust variant                                           |
//! |----------------------------------|--------------------------------------------------------|
//! | `'Invalid encrypted data: too short'` | [`StorageEncryptionError::TooShort`]               |
//! | `'Unsupported encryption version'`    | [`StorageEncryptionError::UnsupportedVersion`]     |
//! | AES-GCM tag mismatch / corruption     | [`StorageEncryptionError::Decrypt`]                |
//! | base64 decode failure                  | [`StorageEncryptionError::InvalidBase64`]          |
//!
//! The TS importer collapses every decryption failure into a single
//! [`level-private-state-provider.ts:920`] `ExportDecryptionError` to
//! avoid an oracle attack — callers of this module should do the same
//! at their boundary (the Rust importer does; see
//! [`crate::providers::in_memory_private_state`]).

use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
use base64::Engine as _;
use hmac::Hmac;
use sha2::Sha256;
use thiserror::Error;

/// AES-256-GCM key length (matches TS `KEY_LENGTH = 32`).
pub const KEY_LENGTH: usize = 32;
/// AES-GCM IV length, in bytes — TS `IV_LENGTH = 12`. Don't use a
/// non-12-byte nonce here: GCM is unsafe with anything else, and the
/// TS encoder is hard-coded to 12.
pub const IV_LENGTH: usize = 12;
/// AES-GCM authentication tag length — TS `AUTH_TAG_LENGTH = 16`.
pub const AUTH_TAG_LENGTH: usize = 16;
/// Salt length used by the KDF (PBKDF2-HMAC-SHA256). Matches TS
/// `SALT_LENGTH = 32`.
pub const SALT_LENGTH: usize = 32;

/// PBKDF2 iteration count for `V1` — TS
/// `PBKDF2_ITERATIONS_V1 = 100_000`. Imported-only; never emitted by
/// this encoder.
pub const PBKDF2_ITERATIONS_V1: u32 = 100_000;
/// PBKDF2 iteration count for `V2` — TS `PBKDF2_ITERATIONS_V2 = 600_000`.
/// Used by every fresh export.
pub const PBKDF2_ITERATIONS_V2: u32 = 600_000;

/// Magic byte for `V1` envelopes.
pub const ENCRYPTION_VERSION_V1: u8 = 1;
/// Magic byte for `V2` envelopes — the only version this module
/// emits.
pub const ENCRYPTION_VERSION_V2: u8 = 2;
/// Header length: `[version u8 || salt[32] || iv[12] || tag[16]]` —
/// matches TS `HEADER_LENGTH = 1 + 32 + 12 + 16 = 61`.
pub const HEADER_LENGTH: usize = 1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH;

/// Errors that surface out of the storage-encryption envelope.
///
/// The library returns these typed variants so call sites can
/// distinguish a structural error (e.g. truncated ciphertext) from a
/// crypto failure. Callers that need TS-compatible behaviour
/// (single generic `ExportDecryptionError` for oracle resistance)
/// should collapse the variants at their boundary.
#[derive(Debug, Error)]
pub enum StorageEncryptionError {
    /// Ciphertext was shorter than [`HEADER_LENGTH`] bytes; cannot
    /// possibly contain a valid envelope.
    #[error("invalid encrypted data: too short ({0} bytes, header is 61 bytes)")]
    TooShort(usize),
    /// The leading version byte is not [`ENCRYPTION_VERSION_V1`] or
    /// [`ENCRYPTION_VERSION_V2`].
    #[error("unsupported encryption version: {0}")]
    UnsupportedVersion(u8),
    /// `base64::decode` failed on the input.
    #[error("invalid base64: {0}")]
    InvalidBase64(#[source] base64::DecodeError),
    /// AES-GCM authentication failed (wrong key, modified ciphertext,
    /// truncated tag, etc.). Mapped to TS's generic
    /// `ExportDecryptionError` at the importer boundary.
    #[error("decryption failed (wrong password or corrupted ciphertext)")]
    Decrypt,
}

/// Salt bound to a [`Cipher`] instance. Re-exposed on import so the
/// caller can record it in the export wrapper alongside the
/// base64-encoded ciphertext (the TS exporter does the same — the
/// salt is *also* embedded in the encrypted blob, but exposing it
/// separately makes round-trip APIs ergonomic and matches the TS
/// `getSalt()` accessor).
pub type Salt = [u8; SALT_LENGTH];

/// One AES-256-GCM cipher bound to a derived key + the salt that
/// produced it.
///
/// Construct with [`Cipher::derive`] (fresh random salt) or
/// [`Cipher::derive_with_salt`] (importer reusing an existing salt).
/// `encrypt` and `decrypt` operate on UTF-8 strings and return /
/// expect base64 envelopes.
#[derive(Clone)]
pub struct Cipher {
    aead: Aes256Gcm,
    salt: Salt,
}

impl Cipher {
    /// Derive an encryption key from `password` and a fresh random
    /// `salt`. Matches TS `StorageEncryption.create(password)` (no
    /// `existingSalt`).
    pub fn derive<R: rand::CryptoRng + rand::RngCore>(rng: &mut R, password: &str) -> Self {
        let mut salt = [0u8; SALT_LENGTH];
        rng.fill_bytes(&mut salt);
        Self::derive_with_salt(password, &salt, PBKDF2_ITERATIONS_V2)
    }

    /// Derive an encryption key from `password` and the supplied
    /// `salt`. Always uses [`PBKDF2_ITERATIONS_V2`] — call
    /// [`Cipher::derive_with_salt_iter`] if you're decrypting a `V1`
    /// envelope.
    #[allow(deprecated)]
    pub fn derive_with_salt(password: &str, salt: &Salt, iterations: u32) -> Self {
        let mut key = [0u8; KEY_LENGTH];
        // pbkdf2 returns Result<(), Error> — failure is impossible
        // for a fixed 32-byte output and any non-empty password
        // (length is checked by upstream callers via
        // validate_export_password). We propagate via expect because
        // the signature constraint is what makes the call infallible.
        pbkdf2::pbkdf2::<Hmac<Sha256>>(password.as_bytes(), salt, iterations, &mut key)
            .expect("PBKDF2 with a 32-byte key length is infallible");
        // Expand AES-256 key schedule + GHASH table once instead of on every
        // encrypt/decrypt call.
        let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key));
        Self { aead, salt: *salt }
    }

    /// Helper for the importer path that reads the version byte off
    /// an envelope before deriving the key. Selects the correct
    /// iteration count based on `version`.
    pub fn derive_for_version(
        password: &str,
        salt: &Salt,
        version: u8,
    ) -> Result<Self, StorageEncryptionError> {
        let iterations = match version {
            ENCRYPTION_VERSION_V1 => PBKDF2_ITERATIONS_V1,
            ENCRYPTION_VERSION_V2 => PBKDF2_ITERATIONS_V2,
            other => return Err(StorageEncryptionError::UnsupportedVersion(other)),
        };
        Ok(Self::derive_with_salt(password, salt, iterations))
    }

    /// Salt accessor — matches TS `getSalt()`.
    #[must_use]
    pub fn salt(&self) -> &Salt {
        &self.salt
    }

    /// Encrypt `plaintext` (UTF-8) and return the base64-encoded
    /// envelope. Matches TS `StorageEncryption.encrypt(data)`.
    #[allow(deprecated)]
    pub fn encrypt<R: rand::CryptoRng + rand::RngCore>(
        &self,
        rng: &mut R,
        plaintext: &str,
    ) -> String {
        let mut iv = [0u8; IV_LENGTH];
        rng.fill_bytes(&mut iv);
        // GCM is safe with random 12-byte IVs up to ~2^32 invocations
        // per key — well above any export workload.
        let ct_with_tag = self
            .aead
            .encrypt(
                Nonce::from_slice(&iv),
                Payload {
                    msg: plaintext.as_bytes(),
                    aad: &[],
                },
            )
            .expect(
                "AES-256-GCM encryption with a 32-byte key, 12-byte nonce, \
                 and well-formed plaintext is infallible",
            );
        // The aes_gcm crate returns ciphertext || tag concatenated.
        // Split into ct and tag for the TS-compatible layout
        // (TS appends auth_tag separately in the header before the
        // ciphertext).
        let (ct, tag) = ct_with_tag.split_at(ct_with_tag.len() - AUTH_TAG_LENGTH);
        let mut envelope = Vec::with_capacity(HEADER_LENGTH + ct.len());
        envelope.push(ENCRYPTION_VERSION_V2);
        envelope.extend_from_slice(&self.salt);
        envelope.extend_from_slice(&iv);
        envelope.extend_from_slice(tag);
        envelope.extend_from_slice(ct);
        BASE64_STANDARD.encode(&envelope)
    }

    /// Decrypt a base64 envelope into the original UTF-8 string.
    /// Matches TS `StorageEncryption.decrypt(encryptedData)`. The
    /// `Cipher` instance MUST have been derived from the same salt
    /// that's in the envelope; if it wasn't, the AES-GCM auth check
    /// fails and we return [`StorageEncryptionError::Decrypt`].
    pub fn decrypt(&self, base64_envelope: &str) -> Result<String, StorageEncryptionError> {
        let parsed = parse_envelope(base64_envelope)?;
        if parsed.salt != self.salt {
            // Salt mismatch is a structural failure (the cipher was
            // derived for a different salt), but treat it as a
            // decrypt error to avoid leaking the salt-comparison
            // result to a timing oracle. The TS code raises
            // `'Salt mismatch'` here, but the `decryptValue` wrapper
            // collapses it to `ExportDecryptionError` upstream. Same
            // here: the caller will collapse all variants.
            return Err(StorageEncryptionError::Decrypt);
        }
        decrypt_with_aead(&self.aead, &parsed)
    }
}

/// Components of a parsed envelope, before the AES-GCM auth check.
#[derive(Debug, Clone)]
pub struct EnvelopeParts {
    pub version: u8,
    pub salt: Salt,
    pub iv: [u8; IV_LENGTH],
    pub tag: [u8; AUTH_TAG_LENGTH],
    pub ciphertext: Vec<u8>,
}

/// Parse a base64 envelope into its raw header components — does
/// not run the AES-GCM auth check. The importer reads the version
/// byte first, then derives the key with the matching iteration
/// count, then calls [`decrypt_with_key`]. Direct callers should
/// prefer [`Cipher::decrypt`].
pub fn parse_envelope(base64_envelope: &str) -> Result<EnvelopeParts, StorageEncryptionError> {
    let bytes = BASE64_STANDARD
        .decode(base64_envelope.trim())
        .map_err(StorageEncryptionError::InvalidBase64)?;
    if bytes.len() < HEADER_LENGTH {
        return Err(StorageEncryptionError::TooShort(bytes.len()));
    }
    let version = bytes[0];
    if version != ENCRYPTION_VERSION_V1 && version != ENCRYPTION_VERSION_V2 {
        return Err(StorageEncryptionError::UnsupportedVersion(version));
    }
    let mut salt = [0u8; SALT_LENGTH];
    salt.copy_from_slice(&bytes[1..=SALT_LENGTH]);
    let mut iv = [0u8; IV_LENGTH];
    iv.copy_from_slice(&bytes[1 + SALT_LENGTH..1 + SALT_LENGTH + IV_LENGTH]);
    let mut tag = [0u8; AUTH_TAG_LENGTH];
    tag.copy_from_slice(
        &bytes[1 + SALT_LENGTH + IV_LENGTH..1 + SALT_LENGTH + IV_LENGTH + AUTH_TAG_LENGTH],
    );
    let ciphertext = bytes[HEADER_LENGTH..].to_vec();
    Ok(EnvelopeParts {
        version,
        salt,
        iv,
        tag,
        ciphertext,
    })
}

/// Run AES-256-GCM decryption against the parsed envelope. Used by
/// the importer to decrypt with a key derived for the envelope's
/// version.
#[allow(deprecated)]
pub fn decrypt_with_key(
    key: &[u8; KEY_LENGTH],
    parts: &EnvelopeParts,
) -> Result<String, StorageEncryptionError> {
    let aead = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key));
    decrypt_with_aead(&aead, parts)
}

#[allow(deprecated)]
fn decrypt_with_aead(
    aead: &Aes256Gcm,
    parts: &EnvelopeParts,
) -> Result<String, StorageEncryptionError> {
    // The aes_gcm crate's decrypt API expects ciphertext || tag, so
    // re-concatenate.
    let mut combined = Vec::with_capacity(parts.ciphertext.len() + AUTH_TAG_LENGTH);
    combined.extend_from_slice(&parts.ciphertext);
    combined.extend_from_slice(&parts.tag);
    let plaintext = aead
        .decrypt(
            Nonce::from_slice(&parts.iv),
            Payload {
                msg: &combined,
                aad: &[],
            },
        )
        .map_err(|_| StorageEncryptionError::Decrypt)?;
    String::from_utf8(plaintext).map_err(|_| StorageEncryptionError::Decrypt)
}

/// `true` if `data` looks like a [`Cipher::encrypt`] envelope (passes
/// length + magic-byte checks). Matches TS `StorageEncryption.isEncrypted`.
#[must_use]
pub fn is_encrypted(data: &str) -> bool {
    let Ok(bytes) = BASE64_STANDARD.decode(data.trim()) else {
        return false;
    };
    bytes.len() >= HEADER_LENGTH
        && (bytes[0] == ENCRYPTION_VERSION_V1 || bytes[0] == ENCRYPTION_VERSION_V2)
}

/// Read the version byte from a base64 envelope. Matches TS
/// `StorageEncryption.getVersion`.
pub fn get_version(data: &str) -> Result<u8, StorageEncryptionError> {
    let bytes = BASE64_STANDARD
        .decode(data.trim())
        .map_err(StorageEncryptionError::InvalidBase64)?;
    if bytes.is_empty() {
        return Err(StorageEncryptionError::TooShort(0));
    }
    Ok(bytes[0])
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::StdRng;
    use rand::SeedableRng;

    fn rng(seed: u64) -> StdRng {
        StdRng::seed_from_u64(seed)
    }

    #[test]
    fn header_length_matches_ts_constant() {
        // TS: VERSION_PREFIX_LENGTH(1) + SALT_LENGTH(32) + IV_LENGTH(12) + AUTH_TAG_LENGTH(16) = 61.
        assert_eq!(HEADER_LENGTH, 61);
    }

    #[test]
    fn pbkdf2_iteration_constants_match_ts() {
        assert_eq!(PBKDF2_ITERATIONS_V1, 100_000);
        assert_eq!(PBKDF2_ITERATIONS_V2, 600_000);
    }

    #[test]
    fn round_trip_encrypt_then_decrypt_with_same_cipher() {
        let mut r = rng(0x42);
        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
        let plain = "this is the plaintext that should round-trip cleanly";
        let envelope = cipher.encrypt(&mut r, plain);
        assert!(is_encrypted(&envelope));
        let recovered = cipher.decrypt(&envelope).expect("round-trip decrypt");
        assert_eq!(recovered, plain);
    }

    #[test]
    fn round_trip_via_importer_path_using_envelope_salt() {
        // Importer flow: parse the envelope, derive the key with the
        // header's salt + version, decrypt.
        let mut r = rng(0x99);
        let pw = "TheQuickBrownFox-12345!";
        let cipher = Cipher::derive(&mut r, pw);
        let plain = "import-path round-trip";
        let envelope = cipher.encrypt(&mut r, plain);

        let parts = parse_envelope(&envelope).unwrap();
        let importer = Cipher::derive_for_version(pw, &parts.salt, parts.version).unwrap();
        let recovered = importer.decrypt(&envelope).unwrap();
        assert_eq!(recovered, plain);
    }

    #[test]
    fn wrong_password_rejects_with_decrypt_error() {
        let mut r = rng(1);
        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
        let envelope = cipher.encrypt(&mut r, "some payload");
        // Same salt — different password.
        let parts = parse_envelope(&envelope).unwrap();
        let wrong = Cipher::derive_for_version(
            "DifferentPassword!12345",
            &parts.salt,
            ENCRYPTION_VERSION_V2,
        )
        .unwrap();
        let err = wrong.decrypt(&envelope).unwrap_err();
        assert!(matches!(err, StorageEncryptionError::Decrypt));
    }

    #[test]
    fn truncated_envelope_rejects_with_too_short() {
        // Envelope shorter than HEADER_LENGTH bytes.
        let truncated = BASE64_STANDARD.encode([0u8; HEADER_LENGTH - 1]);
        let err = parse_envelope(&truncated).unwrap_err();
        assert!(matches!(err, StorageEncryptionError::TooShort(_)));
    }

    #[test]
    fn unsupported_version_rejects() {
        let mut bytes = vec![0xFFu8]; // version 255
        bytes.extend(vec![0u8; HEADER_LENGTH - 1]);
        let envelope = BASE64_STANDARD.encode(bytes);
        let err = parse_envelope(&envelope).unwrap_err();
        assert!(matches!(
            err,
            StorageEncryptionError::UnsupportedVersion(0xFF)
        ));
    }

    #[test]
    fn corrupted_ciphertext_rejects_with_decrypt_error() {
        let mut r = rng(2);
        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
        let envelope = cipher.encrypt(&mut r, "payload");

        // Decode, flip the last ciphertext byte, re-encode.
        let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
        let last = decoded.len() - 1;
        decoded[last] ^= 0xff;
        let tampered = BASE64_STANDARD.encode(&decoded);

        let err = cipher.decrypt(&tampered).unwrap_err();
        assert!(matches!(err, StorageEncryptionError::Decrypt));
    }

    #[test]
    fn corrupted_tag_rejects_with_decrypt_error() {
        let mut r = rng(3);
        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
        let envelope = cipher.encrypt(&mut r, "payload");

        // Flip a byte inside the auth tag region (bytes [1+32+12 ..
        // 1+32+12+16]).
        let mut decoded = BASE64_STANDARD.decode(&envelope).unwrap();
        let tag_start = 1 + SALT_LENGTH + IV_LENGTH;
        decoded[tag_start] ^= 0xff;
        let tampered = BASE64_STANDARD.encode(&decoded);

        let err = cipher.decrypt(&tampered).unwrap_err();
        assert!(matches!(err, StorageEncryptionError::Decrypt));
    }

    #[test]
    fn invalid_base64_rejects() {
        let err = parse_envelope("@@@not-base64@@@").unwrap_err();
        assert!(matches!(err, StorageEncryptionError::InvalidBase64(_)));
    }

    #[test]
    fn is_encrypted_recognises_well_formed_envelope() {
        let mut r = rng(4);
        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
        let envelope = cipher.encrypt(&mut r, "x");
        assert!(is_encrypted(&envelope));
    }

    #[test]
    fn is_encrypted_rejects_random_string() {
        // 64 valid base64 chars but doesn't pass the magic-byte check.
        let bogus = BASE64_STANDARD.encode([0x99u8; HEADER_LENGTH + 4]);
        assert!(!is_encrypted(&bogus));
    }

    #[test]
    fn get_version_returns_emitted_version() {
        let mut r = rng(5);
        let cipher = Cipher::derive(&mut r, "TheQuickBrownFox-12345!");
        let envelope = cipher.encrypt(&mut r, "x");
        assert_eq!(get_version(&envelope).unwrap(), ENCRYPTION_VERSION_V2);
    }

    #[test]
    fn distinct_salts_distinct_envelopes_for_same_plaintext() {
        // Two derive() calls on the same password with different
        // RNGs should produce different salts and therefore different
        // envelopes (proves we're not deterministic across exports).
        let mut r1 = rng(10);
        let mut r2 = rng(11);
        let c1 = Cipher::derive(&mut r1, "TheQuickBrownFox-12345!");
        let c2 = Cipher::derive(&mut r2, "TheQuickBrownFox-12345!");
        assert_ne!(c1.salt, c2.salt);
        let e1 = c1.encrypt(&mut r1, "same plain");
        let e2 = c2.encrypt(&mut r2, "same plain");
        assert_ne!(e1, e2);
    }

    #[test]
    fn pbkdf2_v2_known_answer_against_rfc6070_style_vector() {
        // PBKDF2-HMAC-SHA256, password = "password", salt = "salt",
        // iterations = 1, dkLen = 32. RFC 6070 doesn't cover SHA-256
        // directly, but `cryptography.io` publishes the equivalent
        // vector and `pbkdf2` crate documents it. Hard-coding a known
        // answer here means a future cargo update that breaks the
        // pbkdf2 dep surfaces immediately.
        let mut out = [0u8; 32];
        pbkdf2::pbkdf2::<Hmac<Sha256>>(b"password", b"salt", 1, &mut out).unwrap();
        let expected =
            hex::decode("120fb6cffcf8b32c43e7225256c4f837a86548c92ccc35480805987cb70be17b")
                .unwrap();
        assert_eq!(out.as_slice(), expected.as_slice());
    }
}