One of the common interview questions for a Node.js developer position. Most often, it comes up in discussions about the difference between HTTP and HTTPS or in the context of authorization, especially JWT.
First, you need to understand what private and public keys are. A public key is not secret and can be shared freely, while a private key must be stored securely and never shown to anyone.
Encryption
In this example, we’ll explain in simple terms how encryption works. Imagine you have a friend and want them to send you some secret information in encrypted form so you can decrypt it after receiving it.
To do this, you need to generate a key pair (a public key and a private key). You keep the private key secret while giving your friend the public key. Using the public key, your friend can encrypt the message and send it to you. But only the person who has the private key can decrypt it.
Signature
Continuing with our message example, imagine that now you want to send a secret message to your friend. Your friend generates a key pair and gives you their public key. Then you encrypt the message with their public key so that only they can decrypt it. But if they have shared their public key with several people, the question arises: how can they be sure that the message is really from you and that no one has forged it or changed it along the way?
This is exactly the problem that a digital signature solves. You sign the message with your private key, and your friend verifies the signature using your public key. That way, even if many people have your public key and can encrypt messages for you, they still cannot forge your signature, because that would require your private key.
If you’re now trying to remember where else you’ve seen this, the same principle is used in authorization with JWT tokens.