Digital signature in node js
introduction
hi everyone in this post i'm gonna talk about digital signature. first we start with theory behind digital signature that is a service of cryptography and then check out how to use that in node js using its first party module. note that digital signature is an important part of cryptocurrencies.
imagine person A wants to sent a letter to person B with to condition:
- first: person B can make sure really person A sends the letter
- second: person A not be able to deny he sends the letter
encryption
here are 2 major version of encryption available- symmetric encryption
- asymmetric encryption
symmetric encryption
in symmetric encryption data can encrypt with a key and decrypt with exact same keyasymmetric encryption
in asymmetric encryption anyone has its own pair of keys. a public key and a private key. in this kind of encryptions the data can encrypt with a key and decrypt with its pair. (more detail in top video)create digital signature using asymmetric encryption
to create digital signature, first the sender have to calculate the hash of data and then encrypts that with his/her private key. the result is digital signature. so he have to add it to original data. the result id digitally signed data.verify digital signature
on the other hand to verify digital signature receiver should separate data and digital signature then he have to decrypt signature using senders public key and also calculate hash of original data (that separated in previous step) and compare hash together. if hash are equal signature is valid.
use these concepts in node js
for this sample project i use express js framwork
first we need to generate key pair to do this i use crypto module
so first i open up index.js in router directory and add some apis
generated keys are in buffer type. i prefer to convert them to base64 encoding to make them more readable.
next step is using private key to sign data so we have to get sender's private key and data, sign them and return back them as response
then we have to verify data using sender's public key
note: every thing i said in this post in explained in more details in youtube videos.