JavaScript Crypto Libraries

JavaScript Crypto Libraries

...

Cryptography in JavaScript

    ECDSA with elliptic.js and js-sha3

ECDSA in JavaScript: Generate / Load Keys

1
npm install elliptic
2
npm install js-sha3
Copied!
...
1
let elliptic = require('elliptic');
2
let sha3 = require('js-sha3');
3
let ec = new elliptic.ec('secp256k1');
4
5
// let keyPair = ec.genKeyPair(); // Generate random keys
6
let keyPair = ec.keyFromPrivate(
7
"97ddae0f3a25b92268175400149d65d6887b9cefaf28ea2c078e05cdc15a3c0a");
8
let privKey = keyPair.getPrivate("hex");
9
let pubKey = keyPair.getPublic();
10
console.log(`Private key: ${privKey}`);
11
console.log("Public key :", pubKey.encode("hex").substr(2));
12
console.log("Public key (compressed):",
13
pubKey.encodeCompressed("hex"));
Copied!
Run the above code example: https://repl.it/@nakov/ECDSA-in-JS.
ECDSA in JavaScript: Sign Message
1
let msg = 'Message for signing';
2
let msgHash = sha3.keccak256(msg);
3
let signature =
4
ec.sign(msgHash, privKey, "hex", {canonical: true});
5
6
console.log(`Msg: ${msg}`);
7
console.log(`Msg hash: ${msgHash}`);
8
console.log("Signature:", signature);
Copied!

ECDSA in JavaScript: Verify Signature

1
let hexToDecimal = (x) => ec.keyFromPrivate(x, "hex")
2
.getPrivate().toString(10);
3
let pubKeyRecovered = ec.recoverPubKey(
4
hexToDecimal(msgHash), signature,
5
signature.recoveryParam, "hex");
6
console.log("Recovered pubKey:",
7
pubKeyRecovered.encodeCompressed("hex"));
8
let validSig = ec.verify(
9
msgHash, signature, pubKeyRecovered);
10
console.log("Signature valid?", validSig);
Copied!
Last modified 11d ago