Elliptic Curve Digital Signatures with Node.js (ECDSA)
[Node.js Home][Home]
With a digital signature, Bob signs a message with his private key, and then Alice verifies it with his public key. In this case we will use a range of elliptic curve methods and hashing methods in order to sign a message, and then verify it. One example is the secp256k1 curve and which is used in Bitcoin and Ethereum. The standard signature used is ECDSA (Elliptic Curve Digital Signature Algorithm).
|
Theory
<With public-key encryption, we create a key pair: a public key and a private key. If Alice is sending data to Bob, she can add her digital signature, and which will prove that she is the sender and also verify that the data has not been changed. She does this by signing the data with her private key, and then Bob can prove the signature with Alice's public key. In this example, we will use ECC keys to sign a message, and then verify the correct signature.
The code is:
const crypto = require("crypto"); var hash="sha256"; var message="hello"; var curve="secp256k1"; var args = process.argv; if (args.length>2) message=args[2]; if (args.length>3) curve=args[3]; if (args.length>4) hash=args[4]; const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', { namedCurve: curve, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' }, }); console.log("Private key:\n",privateKey.toString('base64')); console.log("Public key:\n",publicKey.toString('base64')); const sign = crypto.createSign(hash); sign.write(message); sign.end(); var signature = sign.sign(privateKey, 'hex'); const verify = crypto.createVerify(hash); verify.write(message); verify.end(); console.log("Message:\t",message); console.log("Hash:\t\t",hash); console.log("Curve:\t\t",curve); console.log("\nSignature: ",signature.toString('hex')); console.log("Signature verified: ",verify.verify(publicKey, signature, 'hex'));
A sample run is:
Private key: -----BEGIN PRIVATE KEY----- MG8CAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQEEVTBTAgEBBBioRvvOWSyB/0imnBVs lQl0S+hxezfGNWShNAMyAAQ/oyuK8vT2qxD4Sq9/WjckKW++STba/deNXUX+SSwi WLGsP1LI2MUuzKjHw8PacBA= -----END PRIVATE KEY----- Public key: -----BEGIN PUBLIC KEY----- MEkwEwYHKoZIzj0CAQYIKoZIzj0DAQEDMgAEP6MrivL09qsQ+Eqvf1o3JClvvkk2 2v3XjV1F/kksIlixrD9SyNjFLsyox8PD2nAQ -----END PUBLIC KEY----- Message: Test 123 Hash: sha3-224 Curve: prime192v1 Signature: 303502187b879c84d181fc2600af98105ad3c0aad079da0faa20661d021900f3bc537e5d3ec58bd38387020ea24b1cc18ab21d8e7396ee Signature verified: true