-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathKeyUtils.ts
More file actions
55 lines (42 loc) · 1.88 KB
/
Copy pathKeyUtils.ts
File metadata and controls
55 lines (42 loc) · 1.88 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
import bs58 from 'bs58';
import * as crypto from 'crypto';
import * as elliptic from 'elliptic';
const ec = new elliptic.ec('secp256k1');
export class KeyUtils {
public generate_keypair(): elliptic.ec.KeyPair {
const kp = ec.genKeyPair();
return kp;
}
public load_keypair(buf: Buffer | string | elliptic.ec.KeyPair): elliptic.ec.KeyPair {
return ec.keyFromPrivate(buf);
}
public get_sin_from_key(kp: elliptic.ec.KeyPair): string {
const pk: Buffer = Buffer.from(kp.getPublic().encodeCompressed());
const version: Buffer = this.get_version_from_compressed_key(pk);
const checksum: Buffer = this.get_checksum_from_version(version);
return bs58.encode(Buffer.concat([version, checksum]));
}
public signOrig(data: string, kp: elliptic.ec.KeyPair): Buffer {
const digest = crypto.createHash('sha256').update(data).digest();
return Buffer.from(kp.sign(digest).toDER());
}
public sign(data: string, privkey: elliptic.ec.KeyPair): string {
const dataBuffer = Buffer.from(data, 'utf-8');
const hashBuffer = crypto.createHash('sha256').update(dataBuffer).digest();
return Buffer.from(privkey.sign(hashBuffer).toDER()).toString('hex');
}
public getPublicKeyFromPrivateKey(privkey: string | Buffer | elliptic.ec.KeyPair): string {
const ecKey = this.load_keypair(privkey);
return ecKey.getPublic().encodeCompressed('hex');
}
private get_version_from_compressed_key(pk: Buffer): Buffer {
const sh2 = crypto.createHash('sha256').update(pk).digest();
const rp = crypto.createHash('ripemd160').update(sh2).digest();
return Buffer.concat([Buffer.from('0F', 'hex'), Buffer.from('02', 'hex'), rp]);
}
private get_checksum_from_version(version: Buffer): Buffer {
const h1 = crypto.createHash('sha256').update(version).digest();
const h2 = crypto.createHash('sha256').update(h1).digest();
return h2.slice(0, 4);
}
}