forked from fybx/zkl-kds
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkey-derivation.js
63 lines (56 loc) · 1.83 KB
/
key-derivation.js
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
58
59
60
61
62
63
import {
generateMnemonic as generateMnemonic_bip39,
mnemonicToSeed
} from "web-bip39";
import wordlist from "web-bip39/wordlists/english";
import elliptic from "elliptic";
import { Key } from "./key";
const MNEMONIC_STRENGTH = 192;
//const CURVE = "curve25519"
const CURVE = "secp256k1";
/**
* Generates a new key pair from a mnemonic.
*
* @param {string} mnemonic - The mnemonic to generate the key pair from.
* @returns {Promise<{ publicKey: Key; privateKey: Key }>} A promise that resolves to an object containing the public and private keys.
*/
export async function generateKeypair(mnemonic) {
const seed = (await mnemonicToSeed(mnemonic)).toString("hex");
const ec = new elliptic.ec(CURVE);
const keypair = ec.genKeyPair({
entropy: seed.slice(0, 32)
});
return {
publicKey: new Key("public", { fromHexString: keypair.getPublic("hex") }),
privateKey: new Key("private", {
fromHexString: keypair.getPrivate("hex")
})
};
}
/**
* Generates a new mnemonic.
*
* @returns {string} The generated mnemonic.
*/
export function generateMnemonic() {
return generateMnemonic_bip39(wordlist, MNEMONIC_STRENGTH);
}
/**
* Gets a key pair from a private key.
*
* @param {Key} key - The private key to get the key pair from.
* @returns {{ publicKey: Key; privateKey: Key }} An object containing the public and private keys.
* @throws {TypeError} If the provided key is not a private key.
*/
export function getPairFromPrivate(key) {
if (key.keyType != "private")
throw new TypeError("Required property 'key' must be a private key");
const ec = new elliptic.ec(CURVE);
const keypair = ec.keyFromPrivate(key.asHexString);
return {
publicKey: new Key("public", { fromHexString: keypair.getPublic("hex") }),
privateKey: new Key("private", {
fromHexString: keypair.getPrivate("hex")
})
};
}