|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Btccom\JustEncrypt; |
|
4
|
|
|
|
|
5
|
|
|
use BitWasp\Buffertools\Buffer; |
|
6
|
|
|
use BitWasp\Buffertools\BufferInterface; |
|
7
|
|
|
use Btccom\JustEncrypt\Encoding\Mnemonic; |
|
8
|
|
|
use Btccom\JustEncrypt\Encoding\Wordlist; |
|
9
|
|
|
|
|
10
|
|
|
class EncryptionMnemonic |
|
11
|
|
|
{ |
|
12
|
|
|
const CHUNK_SIZE = 4; |
|
13
|
|
|
const PADDING_DUMMY = "\x81"; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @var Mnemonic |
|
17
|
|
|
*/ |
|
18
|
|
|
protected static $encoder; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @return Mnemonic |
|
22
|
|
|
*/ |
|
23
|
4 |
|
protected static function getEncoder() |
|
24
|
|
|
{ |
|
25
|
4 |
|
if (null === static::$encoder) { |
|
26
|
1 |
|
static::$encoder = new Mnemonic(new Wordlist()); |
|
27
|
|
|
} |
|
28
|
4 |
|
return static::$encoder; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param string $data |
|
33
|
|
|
* @return string |
|
34
|
|
|
*/ |
|
35
|
4 |
|
private static function derivePadding($data) |
|
36
|
|
|
{ |
|
37
|
4 |
|
if (strlen($data) > 0 && ord($data[0]) > 0x80) { |
|
38
|
|
|
throw new \RuntimeException('Sanity check: data for mnemonic is not valid'); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
4 |
|
$padLen = self::CHUNK_SIZE - (strlen($data) % self::CHUNK_SIZE); |
|
42
|
4 |
|
return str_pad('', $padLen, self::PADDING_DUMMY); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* @param BufferInterface $data |
|
47
|
|
|
* @return string |
|
48
|
|
|
*/ |
|
49
|
4 |
|
public static function encode(BufferInterface $data) |
|
50
|
|
|
{ |
|
51
|
4 |
|
$encoder = static::getEncoder(); |
|
52
|
4 |
|
$mnemonic = $encoder->entropyToMnemonic(new Buffer(self::derivePadding($data->getBinary()) . $data->getBinary())); |
|
53
|
|
|
|
|
54
|
|
|
try { |
|
55
|
4 |
|
$encoder->mnemonicToEntropy($mnemonic); |
|
56
|
|
|
} catch (\Exception $e) { |
|
57
|
|
|
throw new \RuntimeException('BIP39 produced an invalid mnemonic'); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
4 |
|
return $mnemonic; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param string $mnemonic |
|
65
|
|
|
* @return BufferInterface |
|
66
|
|
|
*/ |
|
67
|
4 |
|
public static function decode($mnemonic) |
|
68
|
|
|
{ |
|
69
|
4 |
|
$bip39 = static::getEncoder(); |
|
70
|
4 |
|
$decoded = $bip39->mnemonicToEntropy($mnemonic)->getBinary(); |
|
71
|
4 |
|
$padFinish = 0; |
|
72
|
4 |
|
while ($decoded[$padFinish] === self::PADDING_DUMMY) { |
|
73
|
4 |
|
$padFinish++; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
4 |
|
$data = substr($decoded, $padFinish); |
|
77
|
4 |
|
if (self::derivePadding($data) !== substr($decoded, 0, $padFinish)) { |
|
78
|
|
|
throw new \RuntimeException('The data was incorrectly padded'); |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
4 |
|
return new Buffer($data); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|