dup_crypto/
mnemonic.rs

1//  Copyright (C) 2020 Éloïs SANCHEZ.
2//
3// This program is free software: you can redistribute it and/or modify
4// it under the terms of the GNU Affero General Public License as
5// published by the Free Software Foundation, either version 3 of the
6// License, or (at your option) any later version.
7//
8// This program is distributed in the hope that it will be useful,
9// but WITHOUT ANY WARRANTY; without even the implied warranty of
10// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11// GNU Affero General Public License for more details.
12//
13// You should have received a copy of the GNU Affero General Public License
14// along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16//! Module to generate Mnemonic
17
18mod error;
19mod language;
20mod mnemonic_gen;
21mod mnemonic_type;
22mod utils;
23
24pub use error::MnemonicError;
25pub use language::Language;
26pub use mnemonic_gen::Mnemonic;
27pub use mnemonic_type::MnemonicType;
28
29///
30/// Generate seed from [`Mnemonic`][Mnemonic]
31///
32/// # Example
33///
34/// ```
35/// use dup_crypto::mnemonic::*;
36/// use dup_crypto::keys::{ed25519::KeyPairFromSeed32Generator, KeyPair};
37///
38/// let mnemonic = Mnemonic::new(MnemonicType::Words12, Language::English).expect("fail to generate random bytes");
39///
40/// let seed = mnemonic_to_seed(&mnemonic);
41///
42/// let keypair = KeyPairFromSeed32Generator::generate(seed);
43///
44/// println!("public key: {}", keypair.public_key());
45///
46/// ```
47///
48/// [Mnemonic]: ./mnemonic/struct.Mnemonic.html
49/// [Mnemonic::phrase()]: ./mnemonic/struct.Mnemonic.html#method.phrase
50pub fn mnemonic_to_seed(mnemonic: &Mnemonic) -> crate::keys::Seed32 {
51    let mnemonic_bytes = mnemonic.phrase().as_bytes();
52    let salt = crate::hashs::Hash::compute(format!("dubp{}", mnemonic.phrase()).as_bytes());
53    crate::keys::ed25519::KeyPairFromSaltedPasswordGenerator::with_default_parameters()
54        .generate_seed(mnemonic_bytes, salt.as_ref())
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_mnemonic_to_seed() -> Result<(), MnemonicError> {
63        let m = Mnemonic::from_phrase(
64            "tongue cute mail fossil great frozen same social weasel impact brush kind",
65            Language::English,
66        )?;
67
68        let seed = mnemonic_to_seed(&m);
69
70        assert_eq!(
71            "qGdvpbP9lJe7ZG4ZUSyu33KFeAEs/KkshAp9gEI4ReY=",
72            &base64::encode(seed.as_ref())
73        );
74
75        Ok(())
76    }
77}