1 | <?php |
||
14 | class Bip39Mnemonic implements MnemonicInterface |
||
15 | { |
||
16 | /** |
||
17 | * @var EcAdapterInterface |
||
18 | */ |
||
19 | private $ecAdapter; |
||
20 | |||
21 | /** |
||
22 | * @var Bip39WordListInterface |
||
23 | */ |
||
24 | private $wordList; |
||
25 | |||
26 | /** |
||
27 | * @param EcAdapterInterface $ecAdapter |
||
28 | * @param Bip39WordListInterface $wordList |
||
29 | */ |
||
30 | 6 | public function __construct(EcAdapterInterface $ecAdapter, Bip39WordListInterface $wordList) |
|
31 | { |
||
32 | 6 | $this->ecAdapter = $ecAdapter; |
|
33 | 6 | $this->wordList = $wordList; |
|
34 | 6 | } |
|
35 | |||
36 | /** |
||
37 | * Creates a new Bip39 mnemonic string. |
||
38 | * |
||
39 | * @param int $entropySize |
||
40 | * @return string |
||
41 | * @throws \BitWasp\Bitcoin\Exceptions\RandomBytesFailure |
||
42 | */ |
||
43 | public function create($entropySize = 512): string |
||
44 | { |
||
45 | $random = new Random(); |
||
46 | $entropy = $random->bytes($entropySize / 8); |
||
47 | |||
48 | return $this->entropyToMnemonic($entropy); |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * @param BufferInterface $entropy |
||
53 | * @param integer $CSlen |
||
54 | * @return string |
||
55 | */ |
||
56 | 49 | private function calculateChecksum(BufferInterface $entropy, int $CSlen): string |
|
57 | { |
||
58 | 49 | $entHash = Hash::sha256($entropy); |
|
59 | |||
60 | // Convert byte string to padded binary string of 0/1's. |
||
61 | 49 | $hashBits = str_pad(gmp_strval($entHash->getGmp(), 2), 256, '0', STR_PAD_LEFT); |
|
62 | |||
63 | // Take $CSlen bits for the checksum |
||
64 | 49 | $checksumBits = substr($hashBits, 0, $CSlen); |
|
65 | |||
66 | 49 | return $checksumBits; |
|
67 | } |
||
68 | |||
69 | /** |
||
70 | * @param BufferInterface $entropy |
||
71 | * @return string[] |
||
72 | */ |
||
73 | 26 | public function entropyToWords(BufferInterface $entropy): array |
|
100 | |||
101 | /** |
||
102 | * @param BufferInterface $entropy |
||
103 | * @return string |
||
104 | */ |
||
105 | 26 | public function entropyToMnemonic(BufferInterface $entropy): string |
|
109 | |||
110 | /** |
||
111 | * @param string $mnemonic |
||
112 | * @return BufferInterface |
||
113 | */ |
||
114 | 27 | public function mnemonicToEntropy(string $mnemonic): BufferInterface |
|
157 | } |
||
158 |