Book Image

Essential Cryptography for JavaScript Developers

By : Alessandro Segala
Book Image

Essential Cryptography for JavaScript Developers

By: Alessandro Segala

Overview of this book

If you’re a software developer, this book will give you an introduction to cryptography, helping you understand how to make the most of it for your applications. The book contains extensive code samples in JavaScript, both for Node.js and for frontend apps running in a web browser, although the core concepts can be used by developers working with any programming language and framework. With a purely hands-on approach that is focused on sharing actionable knowledge, you’ll learn about the common categories of cryptographic operations that you can leverage in all apps you’re developing, including hashing, encryption with symmetric, asymmetric and hybrid ciphers, and digital signatures. You’ll learn when to use these operations and how to choose and implement the most popular algorithms to perform them, including SHA-2, Argon2, AES, ChaCha20-Poly1305, RSA, and Elliptic Curve Cryptography. Later, you’ll learn how to deal with password and key management. All code in this book is written in JavaScript and designed to run in Node.js or as part of frontend apps for web browsers. By the end of this book, you'll be able to build solutions that leverage cryptography to protect user privacy, offer better security against an expanding and more complex threat landscape, help meet data protection requirements, and unlock new opportunities.
Table of Contents (13 chapters)
1
Part 1 – Getting Started
4
Part 2 – Using Common Cryptographic Operations with Node.js
9
Part 3 – Cryptography in the Browser

Using RSA with Node.js

We're finally ready to start writing some code to use public-key cryptography with Node.js!

In this section, we're going to learn how to generate RSA key pairs in Node.js and encrypt and decrypt messages with RSA. We'll then look at how to create a hybrid scheme based on RSA and a symmetric cipher such as AES to encrypt messages of any length.

Generating an RSA key pair

You can generate an RSA key pair with Node.js using the crypto.generateKeyPair function, as shown in this example:

5.1: Generate an RSA key pair (rsa-gen-keypair.js)

const crypto = require('crypto')
const fs = require('fs')
const util = require('util')
const generateKeyPair = util.promisify(crypto.generateKeyPair)
const writeFile = util.promisify(fs.writeFile)
;(async function() {
    const keyPair = await generateKeyPair('rsa', {
        modulusLength: 4096,
 ...