Sign in
Log inSign up

Digital signature in node js

gorgin's photo
gorgin
·Aug 8, 2021·

3 min read

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
somethings like what happen in cheques. in real world in can be done be signature and in digital world in can be done by digital signature. before we get start with digital signature we need to have basic knowledge about encryption

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 key

asymmetric 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)

Screen Shot 2021-08-06 at 2.55.40 AM

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.

Screen Shot 2021-08-06 at 3.05.28 AM

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

Screen Shot 2021-08-06 at 3.13.58 AM

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

Screen Shot 2021-08-06 at 3.19.29 AM

then we have to verify data using sender's public key

Screen Shot 2021-08-06 at 3.21.47 AM

note: every thing i said in this post in explained in more details in youtube videos.