Essential Cryptography for JavaScript Developers. A practical guide to leveraging common cryptographic operations in Node.js… (Alessandro Segala)(Z-Library)
JavaScript
No Description
11
Views
0
Downloads
0.00
Total Donations
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
Essential Cryptography for JavaScript Developers Copyright © 2022 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Associate Group Product Manager: Rohit Rajkumar Senior Editor: Keagan Carneiro Content Development Editor: Divya Vijayan Technical Editor: Simran Udasi Copy Editor: Safis Editing Project Coordinator: Rashika Ba Proofreader: Safis Editing Indexer: Subalakshmi Govindhan Production Designer: Shyam Sundar Korumilli Marketing Coordinator: Anamika Singh First published: February 2022 Production reference: 1140122 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-80107-533-6 www.packt.com
Page
3
To my family and dearest friends; my girlfriend, Clare; my parents, Maria Grazia and Francesco; and my brother, Christian, who, even during these challenging times, have shown love and continued support to each other. – Alessandro Segala
Page
4
Contributors About the author Alessandro Segala is a product manager at Microsoft working on developer tools. A software engineer at heart, he has over a decade of experience building full stack web applications, having worked as a professional developer as well as contributing to and maintaining various open source projects. In addition to writing about software development on his blog, Alessandro had his first book, Svelte 3 Up and Running, published by Packt in 2020.
Page
5
About the reviewers Deepal Jayasekara is a staff software engineer who is experienced in building large-scale, secure applications for payments, infrastructure as a service (IaaS), and financial services industries. He writes and speaks about topics including JavaScript/Node.js, information security, and networking. He is also the founder of bibliocircle.com. Justin Boyer is a tech enthusiast, self-proclaimed proud geek, and writer. He spent over 8 years in software development, focusing on CRM and web development technologies. He piloted the adoption of Node.js in his company and grew to appreciate its unique strengths. He later transitioned to application security, gaining his CSSLP and Security+ certifications and authoring several Pluralsight courses on appsec topics. He now works for himself, providing writing services to tech and cybersecurity companies, while keeping his tech chops current by volunteering his security expertise for a nonprofit and authoring more courses. Josh Robinson is a code craftsman who thrives on cutting-edge technology. His love for coding began with the blue glow of a second hand Commodore 64 and has continued into his career building the future. He can be stalked at JoshRobinson on Twitter and found creating new decentralized tech at bproto.io, where he is a founder.
Page
6
(This page has no text content)
Page
7
Table of Contents Preface Part 1 – Getting Started 1 Cryptography for Developers What is cryptography and why should a developer care? 4 Protecting secrets… 4 …and the other uses of modern cryptography 5 Why this matters to developers 5 What this book is about – and what it's not 8 Rules of engagement 9 Defining "safe" 9 Types and "layers" of encryption 12 Summary 14 2 Dealing with Binary and Random Data Encoding and representing binary data 16 A brief word on character encodings and why we encode binary data 17 Buffers in Node.js 18 Hex encoding 20 Base64 22 Generating cryptographically secure random byte sequences 25 The importance of randomness 25 Using crypto.randomBytes 26 Summary 28
Page
8
viii Table of Contents Part 2 – Using Common Cryptographic Operations with Node.js 3 File and Password Hashing with Node.js Technical requirements 32 An overview of hashing functions 32 Properties of hashing functions, and how they differ from encryption 32 Uses for hashing functions 33 Calculating digests and generating identifiers 36 Hashing a short message or string 36 Hashing large files and streams 37 How to "break" a hash 40 Fast hashing functions and low-entropy inputs 41 Rainbow tables 42 Hashing passwords and deriving keys 43 Argon2 44 Scrypt 46 Older hashing functions 50 Collisions 51 Summary 52 4 Symmetric Encryption in Node.js Technical requirements 54 Symmetric and asymmetric encryption 54 Symmetric encryption with AES 56 Key length 56 Mode of operation 58 Initialization vector 60 Using AES with Node.js 60 Symmetric encryption with ChaCha20-Poly1305 70 Example usage with Node.js 71 When to use ChaCha20-Poly1305 or AES-GCM 73 Key derivation 73 Reusing keys 76 Wrapping keys and best practices for encrypting large documents 77 AES Key Wrap 78 Wrapping user keys 78 Summary 80
Page
9
Table of Contents ix 5 Using Asymmetric and Hybrid Encryption in Node.js Technical requirements 82 Understanding public-key and hybrid cryptosystems 82 The need for public-key cryptography 82 Hybrid cryptosystems 84 Loading, exporting, and encoding public and private keys 85 Encoding keys as PEM 85 Reading and exporting keys 86 Using RSA with Node.js 88 Generating an RSA key pair 88 Using RSA for encryption and decryption 90 Hybrid encryption with RSA and AES 93 Key agreements with Elliptic-Curve Diffie-Hellman 96 Picking a curve 96 Generating EC key pairs 98 Diffie-Hellman key agreements and Perfect Forward Secrecy 99 Performing an ECDH key agreement 101 Data encryption with ECIES 103 Summary 108 6 Digital Signatures with Node.js and Trust Technical requirements 110 The what, how, and why of digital signatures 110 Hashes and digital signatures 110 Properties of digital signatures 111 How digital signatures work 112 Digital signatures and encryption 112 How developers use digital signatures 113 Calculating and verifying digital signatures with Node.js 115 Using RSA 115 Using elliptic curves 119 Trust and certificates 123 The problem of trusting keys 123 Public keys and certificates 124 Public Key Infrastructure 126 Alternative approaches 130 Summary 134
Page
10
x Table of Contents Part 3 – Cryptography in the Browser 7 Introduction to Cryptography in the Browser Technical requirements 138 Playground 138 In Node.js 138 About cryptography in the browser – uses and challenges 139 Challenges of cryptography in the browser 140 Building browser-based apps that use cryptography 145 Binary data in the browser 147 Buffers and typed arrays in the browser 148 Generating random data 151 Keys in Web Crypto 152 The CryptoKey object 152 Generating keys 153 Importing keys 157 Exporting keys 160 Summary 162 8 Performing Common Cryptographic Operations in the Browser Technical requirements 164 Hashing and key derivation 165 Calculating checksums 165 Hashing passwords 167 Deriving encryption keys 169 Symmetric encryption 170 Encrypting and decrypting messages with AES 170 Asymmetric and hybrid cryptography 176 Encrypting and decrypting short messages with RSA 176 Hybrid encryption with RSA and AES 178 Using elliptic curves for ECDH key agreements and ECIES hybrid encryption 180 Digital signatures 185 Digital signatures with the WebCrypto APIs 185 Calculating and verifying RSA signatures 186 Calculating and verifying ECDSA signatures 188 Summary 190 Index Other Books You May Enjoy
Page
11
Preface The need for cryptography in application development is increasing steadily and goes hand-in-hand with the need to build solutions that better protect users' privacy and are safe even from more widespread, complex threats. This book is designed to help software developers understand how to build common cryptographic operations as part of their solutions and to do so safely, using hashing, symmetric and asymmetric encryption, and digital signatures. Throughout the book, we focus on the practical aspects that are relevant to all application developers, even those without a background in cryptography. For each class of cryptographic operation, we will learn about the role it plays in improving applications or unlocking new opportunities, which algorithms are commonly used, and what you need to know to be able to use it safely. Written by a developer for developers, this book contains what I've learned over many years of working with cryptography and implementing applications based on common cryptographic schemes. I've made a conscious decision to skip formal explanations of how algorithms work, including the mathematical formulations behind them, and I'm instead focusing on practical, actionable knowledge that every developer can feel comfortable leveraging as part of the solutions they're building. Who this book is for This book is for software developers that don't necessarily have a background in cryptography yet have a curiosity in the topic and want to know how to leverage it as part of their solutions, correctly and safely. Throughout the book, examples will be provided of code samples in JavaScript, running in a Node.js environment first and then inside browser-based applications. We chose JavaScript because of its potential to be used anywhere, from servers and browsers to desktop and mobile applications. However, aside from the specific code samples, the concepts explained in this book – including the descriptions of the various cryptographic operations, what they're used for, and how they're used – are relevant to developers working with any programming language or framework.
Page
12
xii Preface What this book covers Chapter 1, Cryptography for Developers, introduces the book by presenting the value that leveraging cryptography provides to developers, and then explains some core concepts used throughout all the chapters. Chapter 2, Dealing with Binary and Random Data, demonstrates how binary data is managed in Node.js and how it is encoded to strings, as well as how to generate random sequences of bytes, all of which are operations frequently used when working with cryptography. Chapter 3, File and Password Hashing with Node.js, is a practical overview of how to calculate digests of messages and files with Node.js with the SHA-2 family of functions, as well as how to hash passwords and derive keys with Argon2 and scrypt. Chapter 4, Symmetric Encryption in Node.js, explains how to use symmetric ciphers such as AES and ChaCha20-Poly1305 with Node.js to encrypt messages and files. Chapter 5, Using Asymmetric and Hybrid Encryption in Node.js, demonstrates using asymmetric cryptography to encrypt data with Node.js; this includes using RSA and hybrid encryption schemes based on RSA or Elliptic Curve Cryptography with ECIES. Chapter 6, Digital Signatures with Node.js and Trust, includes both an introduction to calculating and verifying digital signatures with Node.js (using RSA or Elliptic Curve Cryptography) and an explanation of certificates and trust. Chapter 7, Introduction to Cryptography in the Browser, explains the benefits and challenges of performing cryptography in the browser with JavaScript and includes an overview of dealing with binary and random data in frontend apps. Chapter 8, Performing Common Cryptographic Operations in the Browser, demonstrates performing the cryptographic operations analyzed throughout the book in the context of apps running inside a web browser. To get the most out of this book All the code samples in this book are written in modern JavaScript, adopting syntax up to ES2017, including Promises and async/await. Nevertheless, the concepts presented in this book can be leveraged by developers working with other programming languages and frameworks, too. In the first six chapters, we are assuming that all JavaScript code runs in a Node.js environment, for example, in a server-side application or using frameworks such as Electron. The minimum version of Node.js that is capable of running every code sample in this book is 15; however, we recommend using Node.js 16 (the current LTS as of writing) or higher.
Page
13
Preface xiii The last two chapters include JavaScript code that is meant to be executed inside a web browser, using APIs that are available in recent versions of all modern desktop and mobile browsers, including Chrome, Edge, Firefox, Safari, or another Chromium-based browser (notably, Internet Explorer is not supported). It's assumed that the code will be included in frontend applications packaged with a bundler such as Webpack, Rollup, or esbuild (the usage of those tools falls outside the scope of this book). More information on browser support and links to compatibility tables are included in the Technical requirements section of Chapter 7, Introduction to Cryptography in the Browser. For development and experimentation with frontend code, we have also provided a "playground" that can run inside a web browser: https://bit.ly/crypto-playground. If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code. Download the example code files You can download the example code files for this book from GitHub at https://bit.ly/crypto-gh. If there's an update to the code, it will be updated in the GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out! Download the color images We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://static.packt-cdn.com/ downloads/9781801075336_ColorImages.pdf.
Page
14
xiv Preface Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: " We use the decipher object, just like we did with the cipher object in the previous method, invoking decipher.update with the ciphertext to decrypt and use decipher.final when we're done." A block of code is set as follows: const crypto = require('crypto') const fs = require('fs') const util = require('util') const readFile = util.promisify(fs.readFile) When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold: const bobPublicKeyPem = bobKeyPair.publicKey.export( {type: 'spki', format: 'pem'} ) const aliceSharedSecret = crypto.diffieHellman({ publicKey: crypto.createPublicKey(bobPublicKeyPem), privateKey: aliceKeyPair.privateKey Any command-line input or output is written as follows: $ openssl genrsa -out private.pem 4096 Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "Select System info from the Administration panel." Tips or Important Notes Appear like this.
Page
15
Preface xv Get in touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, email us at customercare@packtpub.com and mention the book title in the subject of your message. Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form. Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com. Share Your Thoughts Once you've read Essential Cryptography for JavaScript Developers, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback. Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.
Page
16
(This page has no text content)
Page
17
Part 1 – Getting Started In this first section, we will begin with an overview of the main topics covered in this book, the various operations we're covering, and the core principles that will guide the rest of the book. We will then proceed to learn about how to work with binary and random data in Node.js, two common occurrences while working with cryptography. This section comprises the following chapters: • Chapter 1, Cryptography for Developers • Chapter 2, Dealing with Binary and Random Data
Page
18
(This page has no text content)
Page
19
1 Cryptography for Developers "Dance like no one's watching. Encrypt like everyone is." – Anonymous Few things are as important for application security as cryptography. Done properly, it can make data unreadable to attackers even if you suffer a breach. But do it wrong, and it can actually amplify the impact of other vulnerabilities. While cryptography is incredibly accessible to developers nowadays, many still have questions around how to use it, when to use it, and which of the many options or algorithms to pick. This book will try to answer those questions without going into formal, academic explanations, and without complex mathematical formulas or diagrams, in a way that is friendly to developers. Unlike many other books on the topic, our goal won't be to train you to become a cryptographer. Instead, by the end of this book, you'll hopefully have enough knowledge of the most important algorithms to be able to use them in your code confidently.
Page
20
4 Cryptography for Developers All code samples in this book are written in JavaScript and assume a Node.js execution environment, with the exception of Part 3, Cryptography in the browser, in which we'll look at the Web Crypto APIs for usage in a web browser. However, even if you code in a different programming language, you will be able to follow along to learn the core concepts, and then replicate them in your preferred stack using one of the many libraries that are available to you. In this first chapter, we're going to introduce the book and cover the following topics: • An overview of what cryptography is and why it matters to developers • A definition of "safe" in the context of cryptography • Types and "layers" of encryption What is cryptography and why should a developer care? Cryptography is everywhere around us and it impacts directly or indirectly on every aspect of our lives, every day, even when you don't notice it. Cryptography is used to protect the information we share on the internet. You'll also find it when you're authenticating yourself to use your phone or laptop, or swiping the badge to get into your office. Cryptography is used to secure every digital payment transaction and to guarantee contracts that are signed digitally. It is also used to protect data we store on our devices, both from unauthorized access and from accidental corruption. Protecting secrets… Most people, even those who are not particularly tech-savvy, know that cryptography as the science and practice of protecting messages, files, and data, such as by encrypting and decrypting them. In fact, this use of cryptography, to shield messages from adversaries, is thousands of years old. A common example is the Caesar cipher (a cipher is an algorithm used for encryption or decryption), which is named after the Roman emperor Julius Caesar; this is a classic example of a "substitution cipher," in which letters of the alphabet are substituted with one another. In the case of the Caesar cipher, each letter was shifted by three, so the letter A became D, B became E, Z became C, and so on.
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
AI guide
【One-Line Pitch】
A developer-friendly field guide to using cryptography correctly in Node.js: it skips academic math and focuses on which standard-library operations to reach for, when to use them, and how to avoid common mistakes. Best for JavaScript/Node.js engineers who need to add hashing, encryption, or signatures to real applications without becoming cryptographers.
【Book Arc】
- **Opening (~0%–10%)**: Frames why developers should care about cryptography, introduces core concepts, and sets the book's practical, non-academic tone—teaching you to use algorithms confidently rather than to design them.
- **Early (~10%–32%)**: Builds the foundation for all later work: handling binary data with Buffers, encoding bytes as hex/base64, and generating cryptographically safe random values with `crypto.randomBytes` instead of `Math.random()`.
- **Middle (~32%–52%)**: Covers hashing in practice—calculating SHA-2 digests for strings, large files, and streams, then moves to password hashing and key derivation with Argon2 and scrypt, explaining why fast hashes are unsafe for passwords.
- **Late (~52%–80%)**: Explains symmetric encryption with AES and ChaCha20-Poly1305, including key length, modes of operation, initialization vectors, key derivation, key reuse, and key wrapping for large documents.
- **Ending (~80%–100%)**: Extends to asymmetric and hybrid encryption (RSA, ECIES) and digital signatures with Node.js, tying cryptographic operations to questions of trust. (Excerpts do not cover the full detail of these final chapters.)
【Key Takeaways】
- **Cryptography is necessary but not sufficient** (Opening): Encryption limits breach impact but won't stop social engineering or account takeover; treat it as one layer in defense in depth.
- **Wrong usage is as dangerous as no usage** (Early): Broken algorithms, buggy libraries, or picking the wrong operation (e.g., encrypting passwords instead of hashing them) can be worse than doing nothing.
- **Binary data needs deliberate handling** (Early): Encrypted messages, keys, and hashes contain non-printable bytes; Node.js `Buffer` objects plus hex/base64 encoding make them storable, transferable, and debuggable.
- **Randomness must be cryptographically safe** (Early): `Math.random()` is seeded once and predictable; use `crypto.randomBytes` for keys, salts, and seeds.
- **Hashing is one-way, deterministic, and avalanche-sensitive** (Middle): SHA-256 and the SHA-2 family are ideal for integrity checks and identifiers, but not for passwords or key derivation.
- **Passwords need slow, memory-hard hashing** (Middle): Argon2 (preferably Argon2id) is the default choice; scrypt is a solid alternative, while legacy hashes like MD5 and SHA-1 should be avoided for new applications.
- **Symmetric encryption requires careful parameter choices** (Late): AES and ChaCha20-Poly1305 differ in key length, mode, and IV handling; key derivation, key reuse, and key wrapping all affect real-world safety.
- **Asymmetric and hybrid schemes solve different problems** (Ending): RSA and ECIES enable encryption without shared secrets, while digital signatures address trust and authenticity. (Excerpts do not cover the full detail of these chapters.)
【Reading Tips】
- **Deep-read the early binary/random chapters**: They underpin every later example; skimming them will make the Node.js code in later chapters harder to follow.
- **Treat the hashing chapter as a decision guide**: Focus on when to use SHA-2 versus Argon2/scrypt, not on memorizing digest outputs.
- **Skim the historical/cryptanalysis asides**: The frequency-analysis and "breaking a hash" sections are context, not implementation guidance.
- **Run the code samples**: The book is built around Node.js `crypto` usage; typing and executing examples cements the API patterns.
- **Take away the "which operation when" map**: The lasting value is knowing which cryptographic primitive fits which problem, not the specific algorithms alone.
【Coverage Limits】
This guide is synthesized from stratified excerpts covering roughly the first half of the book in detail; the asymmetric encryption, hybrid encryption, and digital signature chapters are only partially represented, so their treatment here is necessarily high-level.
Passage locations
Excerpt 1
tions 33 deriving keys 43 Calculating digests and Argon2 44 generating identifiers 36 Scrypt 46 Hashing a short message or string 36 Older hashing functions...
View in text
Excerpt 2
ning the password of your online banking account today; if technological innovation allowed an attacker to crack it in "only" 100 years from now, it might no...
View in text
Excerpt 3
of the length size that are safe for cryptographic usage. As you can see from its signature, the function is asynchronous and it passes the result to a funct...
View in text
Excerpt 4
rs, we explained that "breaking" a cryptographic algorithm requires finding ways to derive the plaintext – or, in the case of hashes, finding collisions – wi...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay