-
Notifications
You must be signed in to change notification settings - Fork 1
/
ed25519.js
76 lines (57 loc) · 2.09 KB
/
ed25519.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
64
65
66
67
68
69
70
71
72
73
74
75
76
import fs from "fs";
import { Ed25519KeyIdentity, Ed25519PublicKey } from "@dfinity/identity";
import { Principal } from "@dfinity/principal";
import tweetnacl from "tweetnacl";
// ED25519 version 2
// Private key and public key are included
export const getIdentityFromPem = (pem) => {
pem = pem
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replace("\n", "")
.trim();
const raw = Buffer.from(pem, "base64")
.toString("hex")
.replace("3053020101300506032b657004220420", "")
.replace("a123032100", "");
// including private key (32 bytes before public key)
// and public key (last 32 bytes)
const key = new Uint8Array(Buffer.from(raw, "hex"));
const identity = Ed25519KeyIdentity.fromSecretKey(key);
// =============================== CONFIRM ===============================
console.log("Principal:", identity.getPrincipal().toText());
const pair = identity.getKeyPair();
console.log("Private key:", Buffer.from(pair.secretKey).toString("hex"));
console.log(
"Public key:",
Buffer.from(pair.publicKey.toRaw()).toString("hex")
);
console.log(
"=================================================================="
);
const newPair = tweetnacl.sign.keyPair.fromSeed(key.slice(0, 32));
console.log(
"New private key:",
Buffer.from(newPair.secretKey).toString("hex")
);
console.log(
"New public key:",
Buffer.from(newPair.publicKey).toString("hex")
);
console.log(
"=================================================================="
);
const challenge = new Date().getTime().toString();
console.log("Message to verify:", challenge);
const message = new Uint8Array(Buffer.from(challenge, "utf-8"));
const signature = tweetnacl.sign.detached(message, newPair.secretKey);
console.log("Signature:", Buffer.from(signature).toString("hex"));
const result = tweetnacl.sign.detached.verify(
message,
signature,
newPair.publicKey
);
console.log("Verify signature:", result);
};
const pem = fs.readFileSync(process.env.PEM_PATH).toString();
getIdentityFromPem(pem);