Wednesday, January 20, 2021

Using ECDSA in JavaScript to Sign and Verify messages


  


In this post we will review how to sign and verify messages in JavaScript using ECDSA. This is an asymmetric encryption mechanism that is based on elliptic curve cryptography.


This post covers using a-symmetric encryption for sign/verify. In case of need of a-symmetric encryption to encrypt/decrypt, check this post.


First, lets generate a private key.



const EC = require('elliptic').ec
const ec = new EC('secp256k1')

function main() {
const seed = 'my-secret-password'
const privateKey = ec.keyFromPrivate(seed)



The private key is based on a seed. To recreate the private key, simply rerun this with the same seed.

From the private key, we can deduce the public key. The public key is used for verification of the signature, and as its name implied, is public, so we should send to the party that needs to verify the sender identity. The public key can be send using the X,Y variables, and imported on the other party side.



const publicKey = privateKey.getPublic()

const exportedPublicKey = JSON.stringify({
X: publicKey.getX().toString(16),
Y: publicKey.getY().toString(16),
})



Once we have a private key we can sign messages. First we hash the message using sha256, and then we sign the hash. The result of the signature is two variables: R,S. These should be sent as additional metadata for authentication of the message sender identify (as well as the public key that we have already sent). 



const message = 'Hello World!'
const hash = sha256(message)
const signature = privateKey.sign(hash)
const signatureData = {r: signature.r.toString(16), s: signature.s.toString(16)}



To verify the message we use the public key.



const valid = ec.verify(hash,signature,publicKey)




No comments:

Post a Comment