You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

36 lines
1.2 KiB
JavaScript

'use strict';
// ecsign (messageHash, privateKey) -> {r, s, v}
// ecrecover (messageHash, v, r, s) -> publicKey
// sha3 (message, bits) -> messageHash
// privateToPublic (privateKey) -> publicKey
const crypto = require("crypto");
const ethereumUtil = require("ethereumjs-util");
let privateKey = crypto.randomBytes(32);
let publicKey = ethereumUtil.privateToPublic(privateKey);
console.log("-- Key data:");
console.log("Private key: (hex)", privateKey.toString("hex"));
console.log("Public key: (hex)", publicKey.toString("hex"));
let message = "hello world!";
let messageHash = ethereumUtil.sha3(message);
console.log("-- Message:");
console.log("Plaintext:", message);
console.log("Hash: (hex)", messageHash.toString("hex"));
let signature = ethereumUtil.ecsign(messageHash, privateKey);
let recoveredPublicKey = ethereumUtil.ecrecover(messageHash, signature.v, signature.r, signature.s);
console.log("-- Signing:");
console.log("Signature:");
console.log(" v:", signature.v);
console.log(" r: (hex)", signature.r.toString("hex"));
console.log(" s: (hex)", signature.s.toString("hex"));
console.log("Recovered public key: (hex)", recoveredPublicKey.toString("hex"));
console.log("\nPublic keys match:", (publicKey.compare(recoveredPublicKey) === 0));