Mastering Cryptography Fundamentals With Node’s Crypto Module

Rate this content
Bookmark

Do you know that meme of Homer Simpson trying to hide in the bushes? That's how I would feel when my coworkers would discuss asymmetric encryption, certificate signing, salting, and crazy-sounding acronyms like PBKDF2.

After years of trying to ignore this problem, I finally decided to do something about it. But rather than digging into the subject via textbooks and pseudo-code, I decided to research the massive amount of functionality that is offered by Node.js' built-in `crypto` module. Then I worked my way backwards to understand what each function does, what underling security best-practice it's based on, and when it's appropriate to use it.

So if you're like me then step out of the bushes, and join me in this talk to learn the fundamentals of protecting information in a practical way with Node.js.

This talk has been presented at JSNation 2024, check out the latest edition of this JavaScript Conference.

FAQ

Cryptography is the science or study of secret communication. It involves techniques to secure information and communications through the use of codes, so that only those for whom the information is intended can read and process it.

The crypto module in Node.js is a built-in module that provides cryptographic functionality. It includes a range of cryptographic algorithms that can be used in applications for encryption, decryption, and more.

The documentation for the crypto module in Node.js is not very beginner-friendly because it has a flat structure and assumes that users are already familiar with basic cryptographic concepts and algorithms. It primarily focuses on providing syntax without much conceptual explanation.

AES-256-CBC is an encryption algorithm from the Advanced Encryption Standard (AES) family. '256' refers to the key size of 256 bits, ensuring a high level of security. 'CBC' stands for Cipher Block Chaining, a mode of operation that uses an initialization vector (IV) to enhance security.

A key in encryption is a piece of data that is used to perform both the encryption and decryption processes. For the encryption to be secure, the key must be kept secret and only known to the relevant parties.

A Key Derivation Function (KDF) is a cryptographic function that derives a strong, long key from a human-memorable password. It is designed to be slow to make brute-force attacks more difficult.

In RSA encryption, a user generates a pair of keys: a public key and a private key. The public key is shared openly, while the private key is kept secret. Messages encrypted with the public key can only be decrypted with the corresponding private key, solving the key distribution problem.

Signing and verifying are cryptographic processes used to ensure the authenticity of a message. The sender uses their private key to generate a signature for the message, and the receiver uses the sender's public key to verify that the signature is valid and the message has not been tampered with.

Public key certificates are digital documents that bind a public key to an entity's identity. They are issued by trusted third parties known as Certificate Authorities (CAs) and help establish the ownership and authenticity of public keys.

The crypto module in Node.js provides several functions for generating random values, including randomBytes, randomFill, randomInt, and randomUUID. These are used to produce cryptographically secure random values for various purposes.

Yonatan Mevorach
Yonatan Mevorach
25 min
17 Jun, 2024

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This Talk provides an introduction to cryptography with Node.js, covering encryption concepts, AES-256-CBC algorithm, initialization vector for encryption, key derivation function and salt, randomness and key agreement, key distribution and RSA, signing and verification, public key certificates, and trust in certificate hierarchy.

1. Introduction to Cryptography with Node.js

Short description:

In this talk, I'll discuss mastering cryptography fundamentals with Node's crypto module. Cryptography is the science of secret communication, which is crucial in our online world. Node.js has a built-in crypto module that offers common cryptographic algorithms for application use. The module's documentation assumes familiarity with cryptography basics, so I'll provide a shortcut by covering the concepts and practical usage. Let's get started!

Hi everyone. So in this talk, I'd like to talk to you about this. Oh, sorry. The title of the talk is encrypted. So let's apply the decryption.

Today I want to talk about this. Okay. Mastering cryptography fundamentals with Node's crypto module. So this title is a bit of a mouthful. So let's break it down. First let's talk about what is cryptography. Cryptography is the science of or the study of means of secret communication. And as you can imagine, in our online world, this plays a very important part.

So luckily inside of Node.js we have a built-in module that's called the crypto module and it's there to offer common cryptographic algorithms that you can use in your application. Now this is a built-in module just like FS so you can start using it right away without installing anything. Also as a built-in module it has documentation. So when I wanted to start using it for the first time, this is where I went. And I found that this type of documentation isn't really suited for a beginner like me. Because it's a very flat structure. There's very little information about each method. It kind of assumes that you're already pretty familiar with the basics of cryptography, what each algorithm does. And it just gives you the specific syntax in Node.js. So what I had to do is go back to the beginning and read up on the concepts. And learn about what each different algorithm does, what problems it solves, when it's applicable to use it. And only then when I had this conceptual data I was able to go back and see the actual syntax in Node.js so I can get practical and experiment with writing code that uses that algorithm. And this is the process through which I want to give you a shortcut in today's talk. I want us to cover the basics of cryptography, the conceptual information, and then get practical and see how we can use these things in Node.js.

So let's get started. My name is Yonatan Navarro. I'm a web developer from Wix.com.

2. Encryption Concepts and AES-256-CBC

Short description:

The first concept in cryptography is encryption, which allows secure communication over an insecure channel. To perform encryption, we need to choose an encryption algorithm. One popular algorithm is AES-256-CBC, which ensures security and privacy. The algorithm's key size of 256 bits provides a large number of key combinations for attackers to guess. CBC mode and initialization vector enhance encryption security. The encryption process involves the plaintext and a shared key between the sender and receiver.

And this is where you can find me online. So the first concept in cryptography which we'll talk about is this idea of encryption. This lets two parties, let's say Alice and Bob, to exchange information over an insecure channel like the internet without having to worry that someone who has been able to capture the messages that are being sent across, someone like Eve, can actually understand the meaning behind these messages. And this is why we do encryption.

So the first thing we need to consider in order to perform encryption is which type of encryption algorithm to use. There are quite a few of them out there. They all pretty much work by this concept of substitution and transformation upon the original message and then doing the reverse in order to decrypt. Now this part of this code that I'm showing here is actually the first bit of code from the crypto module that I'm showing today, and this is called the getCypress function. And as the name suggests, this will return a list of all the cryptographic algorithms that you can run on your machine using the crypto module. For example, when I run this on my machine, it returns 171 results. So let's pick one to illustrate this idea of encryption.

So there's a family of encryption algorithms that are known as AES, Advanced Encryption Standard. And as the name suggests, these are algorithms that are advanced enough to be used in modern applications. And it's a standard, so they are implemented across different environments. Specifically, let's take a look at AES-256-CBC. So let's break it down. So 256 applies here to the size of the key. We'll talk about the key and the role it plays in decryption in a minute. But this is essentially the part of the algorithm that actually guarantees the security and privacy of the communication. What an attacker like Yves might try to do is try to brute force and try to guess the key that is used. So if we use a key with 256 bits, it means there is an astronomical number of different key combinations that the attacker would have to try.

Now CBC stands for cipher block chaining. This is a mode of encryption where as part of the encryption process, the message is split into these different blocks. And in order to compute the very first block, you need to supply something which is called an IV or an initialization vector. And we'll talk about its role and how it makes our encryption more secure in a minute. So let's talk about the encryption process. Let's say that Yves wants to send Bob an encrypted message. He would need the plaintext, which is the original message, the key, which we'll talk about more later. We'll talk about how we decide on what value to use as the key and how to transport the key. But for now, let's just say that it is a piece of data that Yves has and Bob has to have an identical key, meaning the exact same piece of data in order to perform the decryption.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
The talk discusses the importance of supply chain security in the open source ecosystem, highlighting the risks of relying on open source code without proper code review. It explores the trend of supply chain attacks and the need for a new approach to detect and block malicious dependencies. The talk also introduces Socket, a tool that assesses the security of packages and provides automation and analysis to protect against malware and supply chain attacks. It emphasizes the need to prioritize security in software development and offers insights into potential solutions such as realms and Deno's command line flags.
The State of Passwordless Auth on the Web
JSNation 2023JSNation 2023
30 min
The State of Passwordless Auth on the Web
Passwords are terrible and easily hacked, with most people not using password managers. The credential management API and autocomplete attribute can improve user experience and security. Two-factor authentication enhances security but regresses user experience. Passkeys offer a seamless and secure login experience, but browser support may be limited. Recommendations include detecting Passkey support and offering fallbacks to passwords and two-factor authentication.
5 Ways You Could Have Hacked Node.js
JSNation 2023JSNation 2023
22 min
5 Ways You Could Have Hacked Node.js
Top Content
The Node.js security team is responsible for addressing vulnerabilities and receives reports through HackerOne. The Talk discusses various hacking techniques, including DLL injections and DNS rebinding attacks. It also highlights Node.js security vulnerabilities such as HTTP request smuggling and certification validation. The importance of using HTTP proxy tunneling and the experimental permission model in Node.js 20 is emphasized. NearForm, a company specializing in Node.js, offers services for scaling and improving security.
Content Security Policy with Next.js: Leveling Up your Website's Security
React Summit US 2023React Summit US 2023
9 min
Content Security Policy with Next.js: Leveling Up your Website's Security
Top Content
Watch video: Content Security Policy with Next.js: Leveling Up your Website's Security
Lucas Estevão, a Principal UI Engineer and Technical Manager at Avenue Code, discusses how to implement Content Security Policy (CSP) with Next.js to enhance website security. He explains that CSP is a security layer that protects against cross-site scripting and data injection attacks by restricting browser functionality. The talk covers adding CSP to an XJS application using meta tags or headers, and demonstrates the use of the 'nonce' attribute for allowing inline scripts securely. Estevão also highlights the importance of using content security reports to identify and improve application security.
Let Me Show You How React Applications Get Hacked in the Real-World
React Advanced 2021React Advanced 2021
22 min
Let Me Show You How React Applications Get Hacked in the Real-World
Top Content
React's default security against XSS vulnerabilities, exploring and fixing XSS vulnerabilities in React, exploring control characters and security issues, exploring an alternative solution for JSON parsing, and exploring JSON input and third-party dependencies.
How React Applications Get Hacked in the Real-World
React Summit 2022React Summit 2022
7 min
How React Applications Get Hacked in the Real-World
How to hack a RealWorld live React application in seven minutes. Tips, best practices, and pitfalls when writing React code. XSS and cross-site scripting in React. React's secure by default, but not always. The first thing to discover: adding a link to a React application. React code vulnerability: cross-site scripting with Twitter link. React doesn't sanitize or output H ref attributes. Fix attempts: detect JavaScript, use dummy hashtag, transition to lowercase. Control corrector exploit. Best practices: avoid denialist approach, sanitize user inputs. React's lack of sanitization and output encoding for user inputs. Exploring XSS vulnerabilities and the need to pretty print JSON. The React JSON pretty package and its potential XSS risks. The importance of context encoding and secure coding practices.

Workshops on related topic

0 to Auth in an hour with ReactJS
React Summit 2023React Summit 2023
56 min
0 to Auth in an hour with ReactJS
WorkshopFree
Kevin Gao
Kevin Gao
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool. There are multiple alternatives that are much better than passwords to identify and authenticate your users - including SSO, SAML, OAuth, Magic Links, One-Time Passwords, and Authenticator Apps.
While addressing security aspects and avoiding common pitfalls, we will enhance a full-stack JS application (Node.js backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session securely for subsequent client requests, validating / refreshing sessions- Basic Authorization - extracting and validating claims from the session token JWT and handling authorization in backend flows
At the end of the workshop, we will also touch other approaches of authentication implementation with Descope - using frontend or backend SDKs.
OWASP Top Ten Security Vulnerabilities in Node.js
JSNation 2024JSNation 2024
97 min
OWASP Top Ten Security Vulnerabilities in Node.js
Workshop
Marco Ippolito
Marco Ippolito
In this workshop, we'll cover the top 10 most common vulnerabilities and critical security risks identified by OWASP, which is a trusted authority in Web Application Security.During the workshop, you will learn how to prevent these vulnerabilities and develop the ability to recognize them in web applications.The workshop includes 10 code challenges that represent each of the OWASP's most common vulnerabilities. There will be given hints to help solve the vulnerabilities and pass the tests.The trainer will also provide detailed explanations, slides, and real-life examples in Node.js to help understand the problems better. Additionally, you'll gain insights from a Node.js Maintainer who will share how they manage security within a large project.It's suitable for Node.js Developers of all skill levels, from beginners to experts, it requires a general knowledge of web application and JavaScript.
Table of contents:- Broken Access Control- Cryptographic Failures- Injection- Insecure Design- Security Misconfiguration- Vulnerable and Outdated Components- Identification and Authentication Failures- Software and Data Integrity Failures- Security Logging and Monitoring Failures- Server-Side Request Forgery
How to Build Front-End Access Control with NFTs
JSNation 2024JSNation 2024
88 min
How to Build Front-End Access Control with NFTs
WorkshopFree
Solange Gueiros
Solange Gueiros
Understand the fundamentals of NFT technology and its application in bolstering web security. Through practical demonstrations and hands-on exercises, attendees will learn how to seamlessly integrate NFT-based access control mechanisms into their front-end development projects.
Finding, Hacking and fixing your NodeJS Vulnerabilities with Snyk
JSNation 2022JSNation 2022
99 min
Finding, Hacking and fixing your NodeJS Vulnerabilities with Snyk
WorkshopFree
Matthew Salmon
Matthew Salmon
npm and security, how much do you know about your dependencies?Hack-along, live hacking of a vulnerable Node app https://github.com/snyk-labs/nodejs-goof, Vulnerabilities from both Open source and written code. Encouraged to download the application and hack along with us.Fixing the issues and an introduction to Snyk with a demo.Open questions.
Bring Code Quality and Security to your CI/CD pipeline
DevOps.js Conf 2022DevOps.js Conf 2022
76 min
Bring Code Quality and Security to your CI/CD pipeline
WorkshopFree
Elena Vilchik
Elena Vilchik
In this workshop we will go through all the aspects and stages when integrating your project into Code Quality and Security Ecosystem. We will take a simple web-application as a starting point and create a CI pipeline triggering code quality monitoring for it. We will do a full development cycle starting from coding in the IDE and opening a Pull Request and I will show you how you can control the quality at those stages. At the end of the workshop you will be ready to enable such integration for your own projects.
Passwordless Auth to Servers: hands on with ASA
DevOps.js Conf 2022DevOps.js Conf 2022
32 min
Passwordless Auth to Servers: hands on with ASA
WorkshopFree
E. Dunham
E. Dunham
These days, you don't need a separate password for every website you log into. Yet thanks to tech debt and tradition, many DevOps professionals are still wrangling a host of SSH keys to access the servers where we sometimes need to be. With modern OAuth, a single login and second factor to prove your identity are enough to securely get you into every service that you're authorized to access. What if SSHing into servers was that easy? In this workshop, we'll use Okta's Advanced Server Access tool (formerly ScaleFT) to experience one way that the dream of sending SSH keys the way of the password has been realized.
- we'll discuss how ASA works and when it's the right tool for the job- we'll walk through setting up a free trial Okta account to use ASA from, and configuring the ASA gateway and server on Linux servers- we'll then SSH into our hosts with the ASA clients without needing to supply an SSH key from our laptops- we'll review the audit logs of our SSH sessions to examine what commands were run