keynest 0.4.1

Simple, offline, cross-platform secrets manager written in Rust
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! Keynest - Simple, offline, cross-platform secrets manager
//!
//! Keynest provides secure local secret storage using Argon2id for key derivation
//! and XChaCha20-Poly1305 for authenticated encryption.
//!
//! # Security
//!
//! For detailed cryptographic architecture, see [CRYPTO.md](https://github.com/capydev42/keynest/blob/main/CRYPTO.md).
//! For security policy and vulnerability reporting, see [SECURITY.md](https://github.com/capydev42/keynest/blob/main/SECURITY.md).
//!
//! # Quick Start
//!
//! ```ignore
//! use keynest::{Keynest, Storage};
//! use zeroize::Zeroizing;
//!
//! // Create a new keystore
//! let mut kn = Keynest::init(Zeroizing::new("password".to_string())).unwrap();
//!
//! // Store secrets
//! kn.set("api_key", "secret123").unwrap();
//! kn.save().unwrap();
//!
//! // Later: reopen the keystore
//! let kn = Keynest::open(Zeroizing::new("password".to_string())).unwrap();
//! assert_eq!(kn.get("api_key"), Some("secret123"));
//! ```

mod crypto;
mod error;
mod format;
mod storage;
mod store;

pub use crate::crypto::{KdfParams, algorithm::Algorithm};
use crate::format::{Header, KeystoreFile, parse, serialize};
pub use crate::storage::Storage;
use crate::store::SecretEntry;
use anyhow::{Context, Result, bail};
use directories::ProjectDirs;
use serde::Serialize;
use std::path::PathBuf;
use store::Store;
use zeroize::{Zeroize, Zeroizing};

/// A secure keystore for storing secrets locally.
///
/// `Keynest` provides methods to initialize, open, and manage a local encrypted
/// keystore. All secrets are encrypted at rest using XChaCha20-Poly1305 with a
/// key derived from your password using Argon2id.
///
/// The struct holds sensitive data (encryption key) which is zeroized on drop
/// for secure memory handling.
///
/// # Example
///
/// ```ignore
/// use keynest::{Keynest, KdfParams, Storage};
/// use zeroize::Zeroizing;
///
/// let storage = Storage::new("/path/to/keystore.db");
/// let kdf = KdfParams::default();
/// let mut kn = Keynest::init_with_storage_and_kdf(Zeroizing::new("password"), storage, kdf).unwrap();
/// kn.set("key", "value").unwrap();
/// kn.save().unwrap();
/// ```
pub struct Keynest {
    store: Store,
    storage: Storage,
    key: [u8; 32],
    keystore_file: KeystoreFile,
}

impl Drop for Keynest {
    fn drop(&mut self) {
        self.key.zeroize();
    }
}

impl Keynest {
    /// Creates a new keystore with the default KDF parameters.
    ///
    /// Uses default storage location (`~/.local/share/keynest/.keynest.db` on Linux).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - A keystore already exists at the default location
    /// - Key derivation fails
    /// - Encryption fails
    ///
    /// # Example
    ///
    /// ```ignore
    /// use keynest::Keynest;
    /// use zeroize::Zeroizing;
    ///
    /// let kn = Keynest::init(Zeroizing::new("password".to_string())).unwrap();
    /// ```
    pub fn init(password: Zeroizing<String>) -> Result<Self> {
        Self::init_with_kdf(password, KdfParams::default())
    }

    /// Creates a new keystore with custom KDF parameters.
    ///
    /// Uses default storage location. Useful for customizing Argon2 settings.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use keynest::{Keynest, KdfParams};
    /// use zeroize::Zeroizing;
    ///
    /// let kdf = KdfParams::new(131072, 4, 2).unwrap();
    /// let kn = Keynest::init_with_kdf(Zeroizing::new("password".to_string()), kdf).unwrap();
    /// ```
    pub fn init_with_kdf(password: Zeroizing<String>, kdf: KdfParams) -> Result<Self> {
        let storage = default_storage()?;
        Self::init_with_storage_and_kdf(password, storage, kdf)
    }

    /// Creates a new keystore with custom storage location and KDF parameters.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - A keystore already exists at the given storage path
    /// - Key derivation fails
    /// - Encryption fails
    pub fn init_with_storage_and_kdf(
        password: Zeroizing<String>,
        storage: Storage,
        kdf: KdfParams,
    ) -> Result<Self> {
        if storage.exists() {
            bail!(
                "keystore already exists: {}\nUse `keynest rekey` or remove the file.",
                storage.path().display()
            );
        }

        let store = Store::new();
        let salt = crypto::generate_salt()?;
        let key =
            crypto::derive_key(&password, &salt, kdf).context("failed to derive encryption key")?;

        drop(password);

        let plaintext = Zeroizing::new(serde_json::to_vec(&store)?);

        let (header, ciphertext) = Header::encrypt_store(
            kdf,
            Algorithm::XChaCha20Poly1305,
            salt.to_vec(),
            &key,
            &plaintext,
        )?;

        let keystore_file = KeystoreFile::new(header, ciphertext);
        let file = serialize(&keystore_file)?;
        storage.save(&file)?;

        Ok(Self {
            store,
            storage,
            key,
            keystore_file,
        })
    }

    /// Opens an existing keystore with the default storage location.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No keystore exists at the default location
    /// - The password is incorrect
    /// - The keystore is corrupted
    pub fn open(password: Zeroizing<String>) -> Result<Self> {
        let storage = default_storage()?;
        Self::open_with_storage(password, storage)
    }

    /// Opens an existing keystore from a custom storage location.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - No keystore exists at the given storage path
    /// - The password is incorrect
    /// - The keystore is corrupted
    pub fn open_with_storage(password: Zeroizing<String>, storage: Storage) -> Result<Self> {
        if !storage.exists() {
            bail!(
                "keystore does not exist: {}\nRun `keynest init` first.",
                storage.path().display()
            );
        }

        let data = storage.load()?;
        let keystore_file = parse(&data)?;

        let key = crypto::derive_key(&password, keystore_file.salt(), *keystore_file.kdf())
            .context("unable to derive encryption key")?;
        drop(password);

        let plaintext = keystore_file.decrypt(&key)?;
        let store = serde_json::from_slice(&plaintext)
            .context("failed to deserialize keystore; possibly wrong password or corrupted data")?;

        Ok(Self {
            store,
            storage,
            key,
            keystore_file,
        })
    }

    /// Stores a secret in the keystore.
    ///
    /// # Errors
    ///
    /// Returns an error if a secret with the given key already exists.
    /// Use `update` to change an existing secret.
    pub fn set(&mut self, key: &str, value: &str) -> Result<()> {
        self.store.set(key, value)?;
        Ok(())
    }

    /// Retrieves a secret by key.
    ///
    /// Returns `None` if the key does not exist.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.store.get(key)
    }

    /// Updates an existing secret's value.
    ///
    /// # Errors
    ///
    /// Returns an error if the key does not exist.
    /// Use `set` to create a new secret.
    pub fn update(&mut self, key: &str, value: &str) -> Result<()> {
        self.store.update(key, value)?;
        Ok(())
    }

    /// Removes a secret from the keystore.
    ///
    /// # Errors
    ///
    /// Returns an error if the key does not exist.
    pub fn remove(&mut self, key: &str) -> Result<()> {
        self.store.remove(key)?;
        Ok(())
    }

    /// Lists all secret keys.
    ///
    /// Returns a vector of references to the key strings.
    pub fn list(&self) -> Vec<&String> {
        self.store.keys().collect()
    }

    /// Lists all secrets with their metadata.
    ///
    /// Returns a vector of references to `SecretEntry` containing
    /// key, value, and update timestamp.
    pub fn list_all(&self) -> Vec<&SecretEntry> {
        self.store.entries().collect()
    }

    /// Persists the keystore to storage.
    ///
    /// Must be called after making changes (set, update, remove)
    /// to save them to disk.
    ///
    /// # Errors
    ///
    /// Returns an error if writing to storage fails.
    pub fn save(&mut self) -> Result<()> {
        let plaintext = Zeroizing::new(serde_json::to_vec(&self.store)?);

        let (header, ciphertext) = Header::encrypt_store(
            *self.keystore_file.kdf(),
            self.keystore_file.algorithm(),
            self.keystore_file.salt().to_vec(),
            &self.key,
            &plaintext,
        )?;

        self.keystore_file = KeystoreFile::new(header, ciphertext);
        let file = serialize(&self.keystore_file)?;
        self.storage.save(&file)?;
        Ok(())
    }

    /// Returns information about the keystore.
    ///
    /// Includes file path, size, creation date, secret count,
    /// and KDF/encryption parameters.
    ///
    /// # Errors
    ///
    /// Returns an error if the storage metadata cannot be read.
    pub fn info(&self) -> Result<StoreInfo> {
        let metadata = std::fs::metadata(self.storage.path())?;
        Ok(StoreInfo {
            path: self.storage.path().to_path_buf(),
            file_size: metadata.len(),
            creation_date: self.store.creation_date().to_string(),
            secrets_count: self.store.len(),
            kdf: *self.keystore_file.kdf(),
            algorithm: self.keystore_file.algorithm().name(),
            nonce_len: self.keystore_file.nonce().len(),
            version: self.keystore_file.version(),
        })
    }

    /// Changes the password and/or KDF parameters.
    ///
    /// Re-encrypts the keystore with a new key derived from the new password
    /// and optional new KDF parameters. The existing secrets are preserved.
    ///
    /// # Arguments
    ///
    /// * `new_password` - The new password to derive the encryption key from
    /// * `new_kdf` - The new KDF parameters (can be different from current)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Key derivation fails
    /// - Encryption fails
    /// - Writing to storage fails
    pub fn rekey(&mut self, new_password: Zeroizing<String>, new_kdf: KdfParams) -> Result<()> {
        let current_algorithm = self.keystore_file.algorithm();

        self.rekey_with_algorithm(new_password, new_kdf, current_algorithm)
    }

    fn rekey_with_algorithm(
        &mut self,
        new_password: Zeroizing<String>,
        new_kdf: KdfParams,
        new_algorithm: Algorithm,
    ) -> Result<()> {
        let new_salt = crypto::generate_salt()?;

        let new_key = crypto::derive_key(&new_password, &new_salt, new_kdf)
            .context("failed to derive new encryption key")?;

        drop(new_password);

        let plaintext = Zeroizing::new(serde_json::to_vec(&self.store)?);

        let (header, ciphertext) = Header::encrypt_store(
            new_kdf,
            new_algorithm,
            new_salt.to_vec(),
            &new_key,
            &plaintext,
        )?;

        self.keystore_file = KeystoreFile::new(header, ciphertext);
        let file = serialize(&self.keystore_file)?;
        self.storage.save(&file)?;

        self.key.zeroize();
        self.key = new_key;

        Ok(())
    }
}

/// Returns the default storage location for the keystore.
///
/// The default location is platform-specific:
/// - Linux: `~/.local/share/keynest/.keynest.db`
/// - macOS: `~/Library/Application Support/keynest/.keynest.db`
/// - Windows: `%APPDATA%\keynest\.keynest.db`
///
/// # Errors
///
/// Returns an error if the platform-specific directories cannot be determined.
pub fn default_storage() -> Result<Storage> {
    let project_dirs =
        ProjectDirs::from("", "", "keynest").context("could not determine platform directories")?;

    let path = project_dirs.data_dir().join(".keynest.db");

    Ok(Storage::new(path))
}

/// Information about a keystore.
///
/// Returned by [`Keynest::info`].
#[derive(Serialize)]
pub struct StoreInfo {
    path: PathBuf,
    file_size: u64,
    creation_date: String,
    secrets_count: usize,
    kdf: KdfParams,
    algorithm: &'static str,
    nonce_len: usize,
    version: u8,
}

impl StoreInfo {
    /// Returns the keystore creation date.
    pub fn creation_date(&self) -> &str {
        &self.creation_date
    }

    /// Returns the number of secrets stored.
    pub fn secrets_count(&self) -> usize {
        self.secrets_count
    }

    /// Returns the KDF parameters used for key derivation.
    pub fn kdf(&self) -> &KdfParams {
        &self.kdf
    }

    /// Returns the encryption algorithm.
    pub fn algorithm(&self) -> &'static str {
        self.algorithm
    }

    /// Returns the nonce length in bytes.
    pub fn nonce_len(&self) -> usize {
        self.nonce_len
    }

    /// Returns the format version.
    pub fn version(&self) -> u8 {
        self.version
    }

    /// Returns the file size in bytes.
    pub fn file_size(&self) -> u64 {
        self.file_size
    }

    /// Returns the file path.
    pub fn path(&self) -> &PathBuf {
        &self.path
    }
}

fn format_size(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.1} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.1} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.1} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} bytes", bytes)
    }
}

impl std::fmt::Display for StoreInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Keynest Store Information")?;
        writeln!(f, "────────────────────────────────────────")?;
        writeln!(f)?;

        writeln!(f, "Location")?;
        writeln!(f, "  Path:              {}", self.path.display())?;
        writeln!(f, "  Size:              {}", format_size(self.file_size))?;
        writeln!(f, "  Format version:    {}", self.version)?;
        writeln!(f)?;

        writeln!(f, "Metadata")?;
        writeln!(f, "  Created:           {}", self.creation_date)?;
        writeln!(f, "  Secrets stored:    {}", self.secrets_count)?;
        writeln!(f)?;

        writeln!(f, "Encryption")?;
        writeln!(f, "  Algorithm:         {}", self.algorithm)?;
        writeln!(f, "  Nonce length:      {} bytes", self.nonce_len)?;
        writeln!(f)?;

        writeln!(f, "Key Derivation")?;
        writeln!(f, "  Memory:            {} KiB", self.kdf.mem_cost_kib())?;
        writeln!(f, "  Time cost:         {}", self.kdf.time_cost())?;
        writeln!(f, "  Parallelism:       {}", self.kdf.parallelism())
    }
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::*;

    #[test]
    fn encrypt_decrypt_roundtrip() {
        use crate::crypto::*;
        use crate::format::{Header, KeystoreFile, parse, serialize};

        let kdf = KdfParams::default();
        let salt = generate_salt().unwrap();
        let key = derive_key("pw", &salt, kdf).unwrap();

        let data = b"secret data".to_vec();

        let (header, ciphertext) = Header::encrypt_store(
            kdf,
            Algorithm::XChaCha20Poly1305,
            salt.to_vec(),
            &key,
            &data,
        )
        .unwrap();

        let keystore_file = KeystoreFile::new(header, ciphertext);
        let file = serialize(&keystore_file).unwrap();

        let keystore_file2 = parse(&file).unwrap();
        let key2 = derive_key("pw", keystore_file2.salt(), *keystore_file2.kdf()).unwrap();
        let plaintext = keystore_file2.decrypt(&key2).unwrap();

        assert_eq!(*plaintext, data);
    }

    #[test]
    fn init_and_open_with_zeroize_wrappers() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keynest.db");
        let storage = Storage::new(path);
        let password = Zeroizing::new(String::from("pw"));
        let mut kn =
            Keynest::init_with_storage_and_kdf(password, storage.clone(), KdfParams::default())
                .unwrap();
        kn.set("A", "B").unwrap();
        kn.save().unwrap();

        let password = Zeroizing::new(String::from("pw"));
        let kn2 = Keynest::open_with_storage(password, storage).unwrap();
        assert_eq!(kn2.get("A"), Some("B"));
    }

    #[test]
    fn init_fails_if_store_exists() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("keynest.db");
        let storage = Storage::new(path);

        let password = Zeroizing::new(String::from("pw"));
        Keynest::init_with_storage_and_kdf(password, storage.clone(), KdfParams::default())
            .unwrap();
        let password = Zeroizing::new(String::from("pw"));
        assert!(
            Keynest::init_with_storage_and_kdf(password, storage, KdfParams::default()).is_err()
        );
    }

    #[test]
    fn wrong_password_fails() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        Keynest::init_with_storage_and_kdf(
            Zeroizing::new("correct".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        assert!(Keynest::open_with_storage(Zeroizing::new("wrong".to_string()), storage).is_err());
    }

    #[test]
    fn set_existing_key_fails() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();
        assert!(kn.set("A", "C").is_err());
    }

    #[test]
    fn update_key_works() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();
        kn.update("A", "C").unwrap();
        assert_eq!(kn.get("A").unwrap(), "C");
    }

    #[test]
    fn update_not_existing_key_fails() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();
        assert!(kn.update("Z", "C").is_err());
    }

    #[test]
    fn removing_key_works() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();

        assert_eq!(kn.get("A").unwrap(), "B");
        kn.remove("A").unwrap();
        assert_eq!(kn.get("A"), None);
    }

    #[test]
    fn removing_not_existing_key_fails() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        assert!(kn.remove("A").is_err());
    }

    #[test]
    fn list_works() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();

        assert!(kn.list().contains(&&"A".to_string()));
        assert!(!kn.list().contains(&&"B".to_string()));
    }

    #[test]
    fn list_all_works() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();
        for sec_entry in kn.list_all() {
            assert_eq!(sec_entry.key(), "A");
            assert_eq!(sec_entry.value(), "B");
            assert_ne!(sec_entry.updated(), "");
        }
    }

    #[test]
    fn rekey_changes_password() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("old".to_string()),
            storage.clone(),
            KdfParams::default(),
        )
        .unwrap();
        kn.set("A", "B").unwrap();
        kn.save().unwrap();

        //reopen
        let mut kn =
            Keynest::open_with_storage(Zeroizing::new("old".to_string()), storage.clone()).unwrap();

        //rekey
        kn.rekey(Zeroizing::new("new".to_string()), KdfParams::default())
            .unwrap();

        assert!(
            Keynest::open_with_storage(Zeroizing::new("old".to_string()), storage.clone()).is_err()
        );

        let kn2 = Keynest::open_with_storage(Zeroizing::new("new".to_string()), storage).unwrap();

        assert_eq!(kn2.get("A"), Some("B"));
    }

    #[test]
    fn rekey_changes_kdf_parameters() {
        let dir = tempfile::tempdir().unwrap();
        let storage = Storage::new(dir.path().join("keynest.db"));

        let original_kdf = KdfParams::default();

        // init
        let mut kn = Keynest::init_with_storage_and_kdf(
            Zeroizing::new("pw".to_string()),
            storage.clone(),
            original_kdf,
        )
        .unwrap();

        kn.save().unwrap();

        // reopen
        let mut kn =
            Keynest::open_with_storage(Zeroizing::new("pw".to_string()), storage.clone()).unwrap();

        // neue Parameter
        let new_kdf = KdfParams::new(
            original_kdf.mem_cost_kib() * 2,
            original_kdf.time_cost() + 1,
            original_kdf.parallelism(),
        )
        .unwrap();

        kn.rekey(Zeroizing::new("pw".to_string()), new_kdf).unwrap();

        // reopen mit neuem password
        let kn2 = Keynest::open_with_storage(Zeroizing::new("pw".to_string()), storage).unwrap();

        assert_eq!(
            kn2.keystore_file.kdf().mem_cost_kib(),
            new_kdf.mem_cost_kib()
        );
        assert_eq!(kn2.keystore_file.kdf().time_cost(), new_kdf.time_cost());
    }
}