1use aes::cipher::{KeyIvInit, StreamCipher};
8use quai_crypto::{SecretKey, keccak256};
9use quai_primitives::Address;
10use quai_wallet::{ExtendedPrivateKey, Language, Mnemonic};
11use serde_json::Value;
12use std::fmt;
13use subtle::ConstantTimeEq;
14use unicode_normalization::UnicodeNormalization;
15use zeroize::Zeroizing;
16pub mod derive;
18mod json;
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
25#[non_exhaustive]
26pub enum KeystoreError {
27 #[error("invalid or unsupported legacy keystore")]
29 Format,
30 #[error("legacy keystore exceeds resource limits")]
32 Limit,
33 #[error("legacy keystore authentication or ownership check failed")]
35 Authentication,
36 #[error("secure randomness unavailable")]
38 Randomness,
39 #[error("legacy keystore key derivation is weaker than the accepted minimum")]
45 WeakParameters,
46}
47pub enum Password<'a> {
49 Text(&'a str),
51 Bytes(&'a [u8]),
53}
54impl fmt::Debug for Password<'_> {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 f.write_str("Password([REDACTED])")
57 }
58}
59impl Password<'_> {
60 fn guarded(&self) -> Result<Zeroizing<Vec<u8>>, KeystoreError> {
61 let bytes = match self {
62 Self::Text(s) if s.len() <= 1024 => {
63 let mut normalized = Zeroizing::new(Vec::with_capacity(4096));
66 let mut utf8 = Zeroizing::new([0u8; 4]);
67 for character in s.nfkc() {
68 let encoded = character.encode_utf8(&mut utf8[..]).as_bytes();
69 if normalized.len() + encoded.len() > 4096 {
70 return Err(KeystoreError::Limit);
71 }
72 normalized.extend_from_slice(encoded);
73 }
74 normalized
75 }
76 Self::Bytes(b) if b.len() <= 1024 => Zeroizing::new(b.to_vec()),
77 _ => return Err(KeystoreError::Limit),
78 };
79 if bytes.len() > 4096 {
80 return Err(KeystoreError::Limit);
81 }
82 Ok(bytes)
83 }
84}
85#[derive(Clone, Copy, Debug)]
94#[non_exhaustive]
95pub struct KdfLimits {
96 pub max_memory_bytes: u64,
103 pub max_scrypt_work: u64,
105 pub max_pbkdf2_rounds: u32,
107 pub min_scrypt_work: u64,
115 pub min_pbkdf2_rounds: u32,
117 pub min_salt_bytes: usize,
122}
123impl Default for KdfLimits {
124 fn default() -> Self {
125 Self {
126 max_memory_bytes: 256 * 1024 * 1024 + 64 * 1024,
127 max_scrypt_work: 1 << 24,
128 max_pbkdf2_rounds: 2_000_000,
129 min_scrypt_work: 1 << 20,
130 min_pbkdf2_rounds: 100_000,
131 min_salt_bytes: 16,
132 }
133 }
134}
135impl KdfLimits {
136 #[must_use]
138 pub fn with_max_memory_bytes(mut self, bytes: u64) -> Self {
139 self.max_memory_bytes = bytes;
140 self
141 }
142 #[must_use]
144 pub fn with_max_scrypt_work(mut self, work: u64) -> Self {
145 self.max_scrypt_work = work;
146 self
147 }
148 #[must_use]
150 pub fn with_max_pbkdf2_rounds(mut self, rounds: u32) -> Self {
151 self.max_pbkdf2_rounds = rounds;
152 self
153 }
154 #[must_use]
156 pub fn with_min_scrypt_work(mut self, work: u64) -> Self {
157 self.min_scrypt_work = work;
158 self
159 }
160 #[must_use]
162 pub fn with_min_pbkdf2_rounds(mut self, rounds: u32) -> Self {
163 self.min_pbkdf2_rounds = rounds;
164 self
165 }
166 #[must_use]
168 pub fn with_min_salt_bytes(mut self, bytes: usize) -> Self {
169 self.min_salt_bytes = bytes;
170 self
171 }
172 #[must_use]
177 pub fn with_strength_floors(self) -> Self {
178 let defaults = Self::default();
179 self.with_min_scrypt_work(defaults.min_scrypt_work)
180 .with_min_pbkdf2_rounds(defaults.min_pbkdf2_rounds)
181 .with_min_salt_bytes(defaults.min_salt_bytes)
182 }
183 #[must_use]
195 pub fn without_strength_floors(self) -> Self {
196 self.with_min_scrypt_work(0)
197 .with_min_pbkdf2_rounds(0)
198 .with_min_salt_bytes(0)
199 }
200}
201#[derive(Clone, Copy)]
202enum Kdf {
203 Scrypt { log_n: u8, r: u32, p: u32 },
204 Pbkdf2 { rounds: u32, sha512: bool },
205}
206impl Kdf {
207 fn validate(self, limits: KdfLimits) -> Result<(), KeystoreError> {
208 if limits.max_memory_bytes > 1024 * 1024 * 1024
210 || limits.max_scrypt_work > 1 << 28
211 || limits.max_pbkdf2_rounds > 10_000_000
212 {
213 return Err(KeystoreError::Limit);
214 }
215 if limits.min_scrypt_work > limits.max_scrypt_work
219 || limits.min_pbkdf2_rounds > limits.max_pbkdf2_rounds
220 {
221 return Err(KeystoreError::Limit);
222 }
223 match self {
224 Self::Scrypt { log_n, r, p } => {
225 let n = 1u64.checked_shl(log_n.into()).ok_or(KeystoreError::Limit)?;
226 let memory = n
229 .checked_add(2)
230 .and_then(|x| x.checked_mul(u64::from(p)))
231 .and_then(|x| x.checked_mul(u64::from(r)))
232 .and_then(|x| x.checked_mul(128))
233 .ok_or(KeystoreError::Limit)?;
234 let work = n
235 .checked_mul(u64::from(r))
236 .and_then(|x| x.checked_mul(u64::from(p)))
237 .ok_or(KeystoreError::Limit)?;
238 if memory > limits.max_memory_bytes || work > limits.max_scrypt_work {
239 return Err(KeystoreError::Limit);
240 }
241 if work < limits.min_scrypt_work {
242 return Err(KeystoreError::WeakParameters);
243 }
244 if u32::from(log_n) >= r.saturating_mul(16) {
247 return Err(KeystoreError::Format);
248 }
249 scrypt::Params::new(log_n, r, p).map_err(|_| KeystoreError::Format)?;
250 }
251 Self::Pbkdf2 { rounds, .. } => {
252 if rounds == 0 || rounds > limits.max_pbkdf2_rounds {
253 return Err(KeystoreError::Limit);
254 }
255 if rounds < limits.min_pbkdf2_rounds {
256 return Err(KeystoreError::WeakParameters);
257 }
258 }
259 }
260 Ok(())
261 }
262 fn derive(
263 self,
264 password: &[u8],
265 salt: &[u8],
266 limits: KdfLimits,
267 ) -> Result<Zeroizing<[u8; 64]>, KeystoreError> {
268 self.validate(limits)?;
269 if salt.len() < limits.min_salt_bytes {
272 return Err(KeystoreError::WeakParameters);
273 }
274 let mut key = Zeroizing::new([0; 64]);
275 match self {
276 Self::Scrypt { log_n, r, p } => scrypt::scrypt(
277 password,
278 salt,
279 &scrypt::Params::new(log_n, r, p).map_err(|_| KeystoreError::Format)?,
280 key.as_mut(),
281 )
282 .map_err(|_| KeystoreError::Format)?,
283 Self::Pbkdf2 {
284 rounds,
285 sha512: false,
286 } => {
287 pbkdf2::pbkdf2_hmac::<pbkdf2::sha2::Sha256>(password, salt, rounds, &mut key[..32])
288 }
289 Self::Pbkdf2 {
290 rounds,
291 sha512: true,
292 } => {
293 pbkdf2::pbkdf2_hmac::<pbkdf2::sha2::Sha512>(password, salt, rounds, &mut key[..32])
294 }
295 }
296 Ok(key)
297 }
298}
299struct MnemonicData {
300 ciphertext: Vec<u8>,
301 iv: [u8; 16],
302 language: Language,
303 path: String,
304}
305pub struct Keystore {
307 address: Address,
308 iv: [u8; 16],
309 ciphertext: [u8; 32],
310 mac: [u8; 32],
311 salt: Vec<u8>,
312 kdf: Kdf,
313 mnemonic: Option<MnemonicData>,
314}
315impl fmt::Debug for Keystore {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 f.write_str("Keystore([ENCRYPTED])")
318 }
319}
320pub struct KeystoreAccount {
322 key: SecretKey,
323 mnemonic: Option<VerifiedMnemonic>,
324}
325impl fmt::Debug for KeystoreAccount {
326 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327 f.write_str("KeystoreAccount([REDACTED])")
328 }
329}
330impl KeystoreAccount {
331 pub fn address(&self) -> Address {
333 self.key.public_key().address()
334 }
335 pub fn secret_key(&self) -> &SecretKey {
337 &self.key
338 }
339 pub fn mnemonic(&self) -> Option<&VerifiedMnemonic> {
341 self.mnemonic.as_ref()
342 }
343 pub fn into_secret_key(self) -> SecretKey {
345 self.key
346 }
347}
348pub struct VerifiedMnemonic {
350 mnemonic: Mnemonic,
351 path: String,
352}
353impl fmt::Debug for VerifiedMnemonic {
354 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355 f.write_str("VerifiedMnemonic([REDACTED])")
356 }
357}
358impl VerifiedMnemonic {
359 pub fn mnemonic(&self) -> &Mnemonic {
361 &self.mnemonic
362 }
363 pub fn path(&self) -> &str {
365 &self.path
366 }
367}
368fn string(v: &Value) -> Result<&str, KeystoreError> {
369 v.as_str().ok_or(KeystoreError::Format)
370}
371fn uint(v: &Value) -> Result<u64, KeystoreError> {
372 v.as_u64().ok_or(KeystoreError::Format)
373}
374fn bytes(v: &Value, min: usize, max: usize) -> Result<Vec<u8>, KeystoreError> {
375 let text = string(v)?;
376 let text = text.strip_prefix("0x").unwrap_or(text);
377 if text.len() % 2 != 0
378 || text.len() / 2 < min
379 || text.len() / 2 > max
380 || !text.bytes().all(|b| b.is_ascii_hexdigit())
381 {
382 return Err(KeystoreError::Format);
383 }
384 text.as_bytes()
385 .chunks_exact(2)
386 .map(|pair| {
387 u8::from_str_radix(
388 std::str::from_utf8(pair).map_err(|_| KeystoreError::Format)?,
389 16,
390 )
391 .map_err(|_| KeystoreError::Format)
392 })
393 .collect()
394}
395fn fixed<const N: usize>(v: &Value) -> Result<[u8; N], KeystoreError> {
396 bytes(v, N, N)?
397 .try_into()
398 .map_err(|_| KeystoreError::Format)
399}
400fn allowed(v: &Value, keys: &[&str]) -> Result<(), KeystoreError> {
401 let map = v.as_object().ok_or(KeystoreError::Format)?;
402 if map.keys().any(|k| !keys.contains(&k.as_str())) {
403 return Err(KeystoreError::Format);
404 }
405 Ok(())
406}
407fn language(locale: &str) -> Result<Language, KeystoreError> {
408 match locale {
409 "en" => Ok(Language::English),
410 "es" => Ok(Language::Spanish),
411 "fr" => Ok(Language::French),
412 "it" => Ok(Language::Italian),
413 "ja" => Ok(Language::Japanese),
414 "ko" => Ok(Language::Korean),
415 "zh_cn" => Ok(Language::SimplifiedChinese),
416 "zh_tw" => Ok(Language::TraditionalChinese),
417 "cz" => Ok(Language::Czech),
418 "pt" => Ok(Language::Portuguese),
419 _ => Err(KeystoreError::Format),
420 }
421}
422impl Keystore {
423 pub fn from_json(document: &[u8], limits: KdfLimits) -> Result<Self, KeystoreError> {
427 let v = json::parse(document)?;
428 allowed(&v, &["address", "id", "version", "crypto", "x-quais"])?;
429 if uint(&v["version"])? != 3 {
430 return Err(KeystoreError::Format);
431 }
432 let address = Address::from_bytes(fixed::<20>(&v["address"])?);
433 let c = &v["crypto"];
434 allowed(
435 c,
436 &[
437 "cipher",
438 "cipherparams",
439 "ciphertext",
440 "kdf",
441 "kdfparams",
442 "mac",
443 ],
444 )?;
445 allowed(&c["cipherparams"], &["iv"])?;
446 if string(&c["cipher"])? != "aes-128-ctr" {
447 return Err(KeystoreError::Format);
448 }
449 let p = &c["kdfparams"];
450 if uint(&p["dklen"])? != 32 {
451 return Err(KeystoreError::Format);
452 }
453 let kdf = match string(&c["kdf"])? {
454 "scrypt" => {
455 allowed(p, &["salt", "n", "r", "p", "dklen"])?;
456 let n = uint(&p["n"])?;
457 if !n.is_power_of_two() || n < 2 {
458 return Err(KeystoreError::Format);
459 }
460 Kdf::Scrypt {
461 log_n: n.trailing_zeros() as u8,
462 r: uint(&p["r"])?
463 .try_into()
464 .map_err(|_| KeystoreError::Limit)?,
465 p: uint(&p["p"])?
466 .try_into()
467 .map_err(|_| KeystoreError::Limit)?,
468 }
469 }
470 "pbkdf2" => {
471 allowed(p, &["salt", "c", "prf", "dklen"])?;
472 let sha512 = match string(&p["prf"])? {
473 "hmac-sha256" => false,
474 "hmac-sha512" => true,
475 _ => return Err(KeystoreError::Format),
476 };
477 Kdf::Pbkdf2 {
478 rounds: uint(&p["c"])?
479 .try_into()
480 .map_err(|_| KeystoreError::Limit)?,
481 sha512,
482 }
483 }
484 _ => return Err(KeystoreError::Format),
485 };
486 kdf.validate(limits)?;
487 let mnemonic = if let Some(m) = v.get("x-quais") {
488 allowed(
489 m,
490 &[
491 "version",
492 "mnemonicciphertext",
493 "mnemoniccounter",
494 "path",
495 "locale",
496 "client",
497 "gethfilename",
498 ],
499 )?;
500 if !matches!(kdf, Kdf::Scrypt { .. }) || string(&m["version"])? != "0.1" {
501 return Err(KeystoreError::Format);
502 }
503 let ciphertext = bytes(&m["mnemonicciphertext"], 16, 32)?;
504 if ciphertext.len() % 4 != 0 {
505 return Err(KeystoreError::Format);
506 }
507 let path = m
508 .get("path")
509 .map(string)
510 .transpose()?
511 .unwrap_or("m/44'/994'/0'/0/0");
512 if path.is_empty() || path.len() > 1024 {
513 return Err(KeystoreError::Limit);
514 }
515 Some(MnemonicData {
516 ciphertext,
517 iv: fixed(&m["mnemoniccounter"])?,
518 path: path.to_owned(),
519 language: language(m.get("locale").map(string).transpose()?.unwrap_or("en"))?,
520 })
521 } else {
522 None
523 };
524 Ok(Self {
525 address,
526 iv: fixed(&c["cipherparams"]["iv"])?,
527 ciphertext: fixed(&c["ciphertext"])?,
528 mac: fixed(&c["mac"])?,
529 salt: bytes(&p["salt"], 1, 64)?,
530 kdf,
531 mnemonic,
532 })
533 }
534 pub fn decrypt(
537 &self,
538 password: Password<'_>,
539 limits: KdfLimits,
540 ) -> Result<KeystoreAccount, KeystoreError> {
541 let password = password.guarded()?;
542 let derived = self.kdf.derive(&password, &self.salt, limits)?;
543 let mut mac_data = Zeroizing::new([0u8; 48]);
544 mac_data[..16].copy_from_slice(&derived[16..32]);
545 mac_data[16..].copy_from_slice(&self.ciphertext);
546 if !bool::from(keccak256(&mac_data[..]).ct_eq(&self.mac)) {
547 return Err(KeystoreError::Authentication);
548 }
549 let mut plain = Zeroizing::new(self.ciphertext);
550 ctr::Ctr128BE::<aes::Aes128>::new_from_slices(&derived[..16], &self.iv)
551 .map_err(|_| KeystoreError::Format)?
552 .try_apply_keystream(&mut plain[..])
553 .map_err(|_| KeystoreError::Format)?;
554 let key = SecretKey::from_bytes(&plain).map_err(|_| KeystoreError::Authentication)?;
555 if key.public_key().address() != self.address {
556 return Err(KeystoreError::Authentication);
557 }
558 let mnemonic = if let Some(m) = &self.mnemonic {
559 let mut entropy = Zeroizing::new(m.ciphertext.clone());
560 ctr::Ctr128BE::<aes::Aes256>::new_from_slices(&derived[32..], &m.iv)
561 .map_err(|_| KeystoreError::Format)?
562 .try_apply_keystream(&mut entropy)
563 .map_err(|_| KeystoreError::Format)?;
564 Some(verify_mnemonic(&key, &entropy, m.language, &m.path)?)
565 } else {
566 None
567 };
568 Ok(KeystoreAccount { key, mnemonic })
569 }
570}
571fn verify_mnemonic(
572 key: &SecretKey,
573 entropy: &[u8],
574 language: Language,
575 path: &str,
576) -> Result<VerifiedMnemonic, KeystoreError> {
577 let mnemonic =
578 Mnemonic::from_entropy(language, entropy).map_err(|_| KeystoreError::Authentication)?;
579 let seed = mnemonic.to_seed("");
580 let derived = ExtendedPrivateKey::from_seed(seed.expose())
581 .and_then(|root| root.derive_path(path))
582 .and_then(|node| node.secret_key())
583 .map_err(|_| KeystoreError::Authentication)?;
584 if !bool::from(
585 derived
586 .export_bytes()
587 .as_bytes()
588 .ct_eq(key.export_bytes().as_bytes()),
589 ) {
590 return Err(KeystoreError::Authentication);
591 }
592 Ok(VerifiedMnemonic {
593 mnemonic,
594 path: path.to_owned(),
595 })
596}
597
598pub struct EncryptedKeystore(String);
600impl fmt::Debug for EncryptedKeystore {
601 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602 f.write_str("EncryptedKeystore([ENCRYPTED])")
603 }
604}
605impl EncryptedKeystore {
606 pub fn as_json(&self) -> &str {
608 &self.0
609 }
610}
611pub fn encrypt(
614 key: &SecretKey,
615 password: Password<'_>,
616) -> Result<EncryptedKeystore, KeystoreError> {
617 encrypt_randomized(key, password, None)
618}
619pub fn encrypt_with_mnemonic(
623 key: &SecretKey,
624 password: Password<'_>,
625 entropy: &[u8],
626 language: Language,
627 path: &str,
628) -> Result<EncryptedKeystore, KeystoreError> {
629 if path.len() > 1024 {
630 return Err(KeystoreError::Limit);
631 }
632 verify_mnemonic(key, entropy, language, path)?;
633 encrypt_randomized(key, password, Some((entropy, language, path)))
634}
635fn encrypt_randomized(
636 key: &SecretKey,
637 password: Password<'_>,
638 mnemonic: Option<(&[u8], Language, &str)>,
639) -> Result<EncryptedKeystore, KeystoreError> {
640 let password = password.guarded()?;
641 let mut random = [0; 80];
642 quai_crypto::fill_random(&mut random).map_err(|_| KeystoreError::Randomness)?;
643 seal(
644 key,
645 &password,
646 mnemonic,
647 Kdf::Scrypt {
648 log_n: 17,
649 r: 8,
650 p: 1,
651 },
652 &random,
653 KdfLimits::default(),
654 )
655}
656fn hex(bytes: &[u8]) -> String {
657 bytes.iter().map(|b| format!("{b:02x}")).collect()
658}
659fn locale(language: Language) -> &'static str {
660 match language {
661 Language::English => "en",
662 Language::Spanish => "es",
663 Language::French => "fr",
664 Language::Italian => "it",
665 Language::Japanese => "ja",
666 Language::Korean => "ko",
667 Language::SimplifiedChinese => "zh_cn",
668 Language::TraditionalChinese => "zh_tw",
669 Language::Czech => "cz",
670 Language::Portuguese => "pt",
671 }
672}
673fn seal(
677 key: &SecretKey,
678 password: &[u8],
679 mnemonic: Option<(&[u8], Language, &str)>,
680 kdf: Kdf,
681 random: &[u8; 80],
682 limits: KdfLimits,
683) -> Result<EncryptedKeystore, KeystoreError> {
684 let Kdf::Scrypt { log_n, r, p } = kdf else {
685 return Err(KeystoreError::Format);
686 };
687 let derived = kdf.derive(password, &random[..32], limits.without_strength_floors())?;
693 let mut ciphertext = Zeroizing::new(*key.export_bytes().as_bytes());
694 ctr::Ctr128BE::<aes::Aes128>::new_from_slices(&derived[..16], &random[32..48])
695 .map_err(|_| KeystoreError::Format)?
696 .try_apply_keystream(&mut ciphertext[..])
697 .map_err(|_| KeystoreError::Format)?;
698 let mut mac_data = Zeroizing::new([0; 48]);
699 mac_data[..16].copy_from_slice(&derived[16..32]);
700 mac_data[16..].copy_from_slice(&ciphertext[..]);
701 let mut uuid: [u8; 16] = random[48..64]
702 .try_into()
703 .map_err(|_| KeystoreError::Format)?;
704 uuid[6] = (uuid[6] & 15) | 64;
705 uuid[8] = (uuid[8] & 63) | 128;
706 let id = hex(&uuid);
707 let id = format!(
708 "{}-{}-{}-{}-{}",
709 &id[..8],
710 &id[8..12],
711 &id[12..16],
712 &id[16..20],
713 &id[20..]
714 );
715 let mut document = serde_json::json!({"address":hex(key.public_key().address().bytes()),"id":id,"version":3,"Crypto":{"cipher":"aes-128-ctr","cipherparams":{"iv":hex(&random[32..48])},"ciphertext":hex(&ciphertext[..]),"kdf":"scrypt","kdfparams":{"salt":hex(&random[..32]),"n":1u64<<log_n,"r":r,"p":p,"dklen":32},"mac":hex(&keccak256(&mac_data[..]))}});
716 if let Some((entropy, language, path)) = mnemonic {
717 let mut encrypted = Zeroizing::new(entropy.to_vec());
718 ctr::Ctr128BE::<aes::Aes256>::new_from_slices(&derived[32..], &random[64..])
719 .map_err(|_| KeystoreError::Format)?
720 .try_apply_keystream(&mut encrypted)
721 .map_err(|_| KeystoreError::Format)?;
722 document["x-quais"] = serde_json::json!({"version":"0.1","client":"quai-rust-sdk","path":path,"locale":locale(language),"mnemonicCounter":hex(&random[64..]),"mnemonicCiphertext":hex(&encrypted)});
723 }
724 Ok(EncryptedKeystore(
725 serde_json::to_string(&document).map_err(|_| KeystoreError::Format)?,
726 ))
727}
728
729#[cfg(test)]
730mod tests {
731 use super::*;
732
733 fn fixture_limits() -> KdfLimits {
740 KdfLimits::default().without_strength_floors()
744 }
745
746 #[test]
747 fn normalized_password_growth_is_bounded_before_secret_reallocation() {
748 let near_limit = "\u{fdfa}".repeat(124);
750 let guarded = Password::Text(&near_limit).guarded().unwrap();
751 assert_eq!(guarded.len(), 4092);
752 assert_eq!(guarded.capacity(), 4096);
753 let over_limit = "\u{fdfa}".repeat(125);
754 assert!(matches!(
755 Password::Text(&over_limit).guarded(),
756 Err(KeystoreError::Limit)
757 ));
758 assert!(Password::Text("").guarded().unwrap().is_empty());
759 }
760
761 #[test]
762 fn deterministic_rust_encryption_matches_javascript_ciphertext_mac_and_uuid() {
763 let fixture: Value =
764 serde_json::from_str(include_str!("../tests/fixtures/keystores.json")).unwrap();
765 let v = &fixture["vectors"][0];
766 let key_bytes = fixed::<32>(&v["expected"]["privateKey"]).unwrap();
767 let key = SecretKey::from_bytes(&key_bytes).unwrap();
768 let mut random = [0; 80];
769 random[..32].fill(0x11);
770 random[32..48].fill(0x22);
771 random[48..64].fill(0x33);
772 random[64..].fill(0x44);
773 let encrypted = seal(
774 &key,
775 b"PUBLIC password",
776 None,
777 Kdf::Scrypt {
778 log_n: 4,
779 r: 1,
780 p: 1,
781 },
782 &random,
783 fixture_limits(),
784 )
785 .unwrap();
786 assert_eq!(
787 serde_json::from_str::<Value>(encrypted.as_json()).unwrap(),
788 v["json"]
789 );
790 for row in fixture["vectors"]
791 .as_array()
792 .unwrap()
793 .iter()
794 .filter(|r| r["expected"].get("mnemonic").is_some())
795 {
796 let key =
797 SecretKey::from_bytes(&fixed(&row["expected"]["privateKey"]).unwrap()).unwrap();
798 let m = &row["expected"]["mnemonic"];
799 let entropy = bytes(&m["entropy"], 16, 32).unwrap();
800 let language = language(string(&m["locale"]).unwrap()).unwrap();
801 let path = string(&m["path"]).unwrap();
802 let encrypted = seal(
803 &key,
804 b"PUBLIC mnemonic",
805 Some((&entropy, language, path)),
806 Kdf::Scrypt {
807 log_n: 4,
808 r: 1,
809 p: 1,
810 },
811 &random,
812 fixture_limits(),
813 )
814 .unwrap();
815 let result: Value = serde_json::from_str(encrypted.as_json()).unwrap();
816 assert_eq!(result["Crypto"], row["json"]["Crypto"]);
817 for field in ["mnemonicCiphertext", "mnemonicCounter", "path", "locale"] {
818 assert_eq!(result["x-quais"][field], row["json"]["x-quais"][field]);
819 }
820 Keystore::from_json(encrypted.as_json().as_bytes(), fixture_limits())
821 .unwrap()
822 .decrypt(Password::Text("PUBLIC mnemonic"), fixture_limits())
823 .unwrap();
824 }
825 }
826}