-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathKeyGenerator.ts
More file actions
57 lines (52 loc) · 1.93 KB
/
KeyGenerator.ts
File metadata and controls
57 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { crypto } from 'bitcoinjs-lib';
import randombytes from 'randombytes';
import * as bip39 from 'bip39';
import { pbkdf2Sync } from 'pbkdf2';
import * as ecurve from 'ecurve';
import { GeneratedKey } from '../components/pages/keyGenerator/KeyGeneratorContent';
const bigi = require('bigi');
const wif = require('wif');
const getBitsFromBytes = (bytes: Buffer) => {
let bits = '';
bytes.forEach(bit => {
let binaryBit = bit.toString(2);
const missingZeros = 8 - binaryBit.length;
for (let i = missingZeros; i > 0; i--) {
binaryBit = '0' + binaryBit;
}
bits += binaryBit;
});
return bits;
}
const create132BitKeyWithSha256 = (generatedBytes: Buffer, random128bits: string) => {
const sha256Bits = getBitsFromBytes(crypto.sha256(generatedBytes));
return sha256Bits.slice(0, 4) + random128bits;
}
const generateWordsFromBytes = (random132bits: string) => {
const dividedBits = random132bits.match(/.{1,11}/g);
return dividedBits?.map(bit => {
const index = parseInt(bit, 2);
return bip39.wordlists.english[index];
});
}
export const generateNewKeys = (): GeneratedKey => {
const generatedBytes = randombytes(16);
const random128bits = getBitsFromBytes(generatedBytes);
const random132bits = create132BitKeyWithSha256(generatedBytes, random128bits);
const generatedWords = generateWordsFromBytes(random132bits);
const privateKey = pbkdf2Sync(random128bits, random132bits.slice(0, 4), 1, 32, 'sha256');
const curve = ecurve.getCurveByName('secp256k1');
const publicKey = curve.G.multiply(bigi.fromBuffer(privateKey)).getEncoded(false).toString('hex');
let networkWIF;
if (process.env.REACT_APP_NETWORK === 'testnet' || process.env.REACT_APP_NETWORK === 'regtest') {
networkWIF = 0xef;
} else {
networkWIF = 0x80;
}
return {
publicKey,
privateKey: privateKey.toString('hex'),
privateKeyWIF: wif.encode(networkWIF, privateKey, false),
words: generatedWords || []
};
}