Class: Derivator::Mnemonic
- Inherits:
-
Object
- Object
- Derivator::Mnemonic
- Defined in:
- lib/derivator/mnemonic.rb
Overview
BIP39 mnemonic generation.
Constant Summary collapse
- WORDS =
Word list (ordered). Only English is supported.
File.readlines(__dir__ + '/word_lists/english.txt', chomp: true)
- SEED_ITERATIONS =
2048- SEED_KEY_LENGTH =
64
Class Method Summary collapse
-
.generate(bytes = random_bytes) ⇒ String
Generates mnemonic.
-
.random_bytes ⇒ String
Generates 128 bits of random.
-
.seed(mnemonic, password = '') ⇒ Object
Generates master seed.
Class Method Details
.generate(bytes = random_bytes) ⇒ String
Generates mnemonic.
22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/derivator/mnemonic.rb', line 22 def generate(bytes = random_bytes) checksum = OpenSSL::Digest::SHA256.new(bytes).digest[0..0] checksum_bits = checksum[0..0].unpack('B4').first # first 4 bits bits = bytes.unpack('B*').first + checksum_bits mnemonic = bits.chars. each_slice(11). map(&:join). map { |x| x.to_i(2) }. map { |x| WORDS[x] }. join(' ') end |
.random_bytes ⇒ String
Generates 128 bits of random
14 15 16 |
# File 'lib/derivator/mnemonic.rb', line 14 def random_bytes SecureRandom.random_bytes(128 / 8) # 128 bits end |
.seed(mnemonic, password = '') ⇒ Object
Generates master seed.
38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/derivator/mnemonic.rb', line 38 def seed(mnemonic, password = '') salt = "mnemonic#{password}" result_bytes = OpenSSL::KDF.pbkdf2_hmac( mnemonic, salt: salt, iterations: SEED_ITERATIONS, length: SEED_KEY_LENGTH, hash: 'SHA512' ) result_bytes.unpack('H*').first end |