Given a wallet passphrase string and an unencrypted master key, determine the proper key * derivation parameters (should take at least 100ms) and encrypt the master key. */
| 563 | /* Given a wallet passphrase string and an unencrypted master key, determine the proper key |
| 564 | * derivation parameters (should take at least 100ms) and encrypt the master key. */ |
| 565 | static bool EncryptMasterKey(const SecureString& wallet_passphrase, const CKeyingMaterial& plain_master_key, CMasterKey& master_key) |
| 566 | { |
| 567 | constexpr MillisecondsDouble target_time{100}; |
| 568 | CCrypter crypter; |
| 569 | |
| 570 | // Get the weighted average of iterations we can do in 100ms over 2 runs. |
| 571 | for (int i = 0; i < 2; i++){ |
| 572 | auto start_time{NodeClock::now()}; |
| 573 | crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod); |
| 574 | auto elapsed_time{NodeClock::now() - start_time}; |
| 575 | |
| 576 | if (elapsed_time <= 0s) { |
| 577 | // We are probably in a test with a mocked clock. |
| 578 | master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS; |
| 579 | break; |
| 580 | } |
| 581 | |
| 582 | // target_iterations : elapsed_iterations :: target_time : elapsed_time |
| 583 | unsigned int target_iterations = master_key.nDeriveIterations * target_time / elapsed_time; |
| 584 | // Get the weighted average with previous runs. |
| 585 | master_key.nDeriveIterations = (i * master_key.nDeriveIterations + target_iterations) / (i + 1); |
| 586 | } |
| 587 | |
| 588 | if (master_key.nDeriveIterations < CMasterKey::DEFAULT_DERIVE_ITERATIONS) { |
| 589 | master_key.nDeriveIterations = CMasterKey::DEFAULT_DERIVE_ITERATIONS; |
| 590 | } |
| 591 | |
| 592 | if (!crypter.SetKeyFromPassphrase(wallet_passphrase, master_key.vchSalt, master_key.nDeriveIterations, master_key.nDerivationMethod)) { |
| 593 | return false; |
| 594 | } |
| 595 | if (!crypter.Encrypt(plain_master_key, master_key.vchCryptedKey)) { |
| 596 | return false; |
| 597 | } |
| 598 | |
| 599 | return true; |
| 600 | } |
| 601 | |
| 602 | static bool DecryptMasterKey(const SecureString& wallet_passphrase, const CMasterKey& master_key, CKeyingMaterial& plain_master_key) |
| 603 | { |
no test coverage detected