search
HomeWeb Front-endJS TutorialCryptography in JavaScript: A Practical Guide

Cryptography in JavaScript: A Practical Guide

Cryptography protects data by transforming it into a format only intended recipients can understand. It's essential for securing passwords, online transactions, and sensitive communications. Below, you'll learn about encryption, hashing, and using JavaScript to implement them.


What is Cryptography?

Cryptography transforms readable data (plaintext) into an unreadable format (ciphertext). Only authorized parties can reverse the process.

Key Concepts:

  • Encryption: Converts plaintext into ciphertext.
  • Decryption: Reverses ciphertext back to plaintext using a key.

Types of Encryption

1. Symmetric Encryption

Uses the same key for encryption and decryption. The key must be shared securely between sender and receiver. AES is a widely used type of symmetric encryption algorithm that secures data by converting it into an unreadable format. It relies on secret keys and supports 128, 192, or 256-bit key lengths, providing strong protection against unauthorized access. AES is essential for:

  • Securing Internet Communication: Safeguarding online interactions like HTTPS.
  • Protecting Sensitive Data: Ensuring confidentiality in storage and transmission.
  • Encrypting Files: Keeping personal and professional information safe.

Key Elements of AES

Key elements of AES include the key and the Initialization Vector (IV). The key is a secret value shared between parties, determining how data is encrypted and decrypted, and it must always remain confidential. The IV is a random value used alongside the key to ensure that identical plaintext encrypts to different ciphertexts, adding randomness to prevent pattern recognition. While the IV can be public, it must never be reused with the same key. Together, these elements enable AES to effectively counter cyber threats, making it a cornerstone of data security.

Example: AES (Advanced Encryption Standard)

AES encrypts data using a shared key and an initialization vector (IV) for added randomness.

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return { encrypted, iv: iv.toString('hex'), key: key.toString('hex') };
}

function decrypt(encrypted, ivHex, keyHex) {
  const decipher = crypto.createDecipheriv(algorithm, Buffer.from(keyHex, 'hex'), Buffer.from(ivHex, 'hex'));
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

// Usage
const message = "Secret Message";
const encryptedData = encrypt(message);
console.log("Encrypted:", encryptedData);

const decryptedMessage = decrypt(encryptedData.encrypted, encryptedData.iv, encryptedData.key);
console.log("Decrypted:", decryptedMessage);


2. Asymmetric Encryption

To create a secure encrypted system, asymmetric encryption is often the solution. It uses two keys: a public key for encryption and a private key for decryption. This setup enables secure communication without sharing a single key.

How It Works

  1. Key Pair Generation

    A public-private key pair is generated. The public key is shared openly, while the private key stays confidential.

  2. Encryption

    The recipient's public key encrypts the data. Only their private key can decrypt it, keeping the data safe even if intercepted.

  3. Decryption

    The recipient decrypts the data using their private key.

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return { encrypted, iv: iv.toString('hex'), key: key.toString('hex') };
}

function decrypt(encrypted, ivHex, keyHex) {
  const decipher = crypto.createDecipheriv(algorithm, Buffer.from(keyHex, 'hex'), Buffer.from(ivHex, 'hex'));
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

// Usage
const message = "Secret Message";
const encryptedData = encrypt(message);
console.log("Encrypted:", encryptedData);

const decryptedMessage = decrypt(encryptedData.encrypted, encryptedData.iv, encryptedData.key);
console.log("Decrypted:", decryptedMessage);


Hashing in Cryptography

Hashing converts data into a fixed-length, irreversible string (hash). It's commonly used for verifying data integrity and securely storing passwords.

Popular Hashing Algorithms:

  • SHA-256: Secure and widely used.
  • SHA-3: Newer with enhanced security.
  • MD5 and SHA-1: Deprecated due to vulnerabilities.

Example of Hashing a String in Node.js

const crypto = require('crypto');

// Generate keys
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });

const data = "Confidential Data";

// Encrypt
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(data));
console.log("Encrypted:", encrypted.toString('base64'));

// Decrypt
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log("Decrypted:", decrypted.toString());


Encryption vs. Hashing

Feature Encryption Hashing
Feature Encryption Hashing
Process Two-way (encrypt/decrypt) One-way
Purpose Data confidentiality Data integrity
Reversible Yes No
Example AES, RSA SHA-256, bcrypt
Process
Two-way (encrypt/decrypt) One-way
Purpose Data confidentiality Data integrity
Reversible Yes No
Example AES, RSA SHA-256, bcrypt

Practical Example: Asymmetric Encryption in Projects

In my project Whisper, we used asymmetric encryption to secure anonymous chat messages. Messages are encrypted with the recipient's public key, ensuring only the recipient can decrypt them using their private key.

For client-side React implementation, we used crypto-js for encryption and decryption:

const crypto = require('crypto');

const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  const cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  return { encrypted, iv: iv.toString('hex'), key: key.toString('hex') };
}

function decrypt(encrypted, ivHex, keyHex) {
  const decipher = crypto.createDecipheriv(algorithm, Buffer.from(keyHex, 'hex'), Buffer.from(ivHex, 'hex'));
  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');
  return decrypted;
}

// Usage
const message = "Secret Message";
const encryptedData = encrypt(message);
console.log("Encrypted:", encryptedData);

const decryptedMessage = decrypt(encryptedData.encrypted, encryptedData.iv, encryptedData.key);
console.log("Decrypted:", decryptedMessage);

Decryption uses the private key:

const crypto = require('crypto');

// Generate keys
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });

const data = "Confidential Data";

// Encrypt
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(data));
console.log("Encrypted:", encrypted.toString('base64'));

// Decrypt
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log("Decrypted:", decrypted.toString());

Explore Whisper's Code for detailed examples.


Conclusion

Cryptography strengthens data security in applications. Use symmetric encryption like AES for shared-key scenarios and asymmetric encryption for public-private key systems. Hashing ensures data integrity, especially for passwords. Select the right cryptographic approach based on your application's needs.

Need more knowledge?

Read more on Shared Key
Read more on Public Key
Read more on SHA-256
Read more on SHA-3
Read more on MD5
Read more on SHA-1
Read more on Symmetric-encryption
Read more on AES

Thanks for reading, let me know what you think about this and if you would like to see more, if you think i made a mistake or missed something, don't hesitate to comment

The above is the detailed content of Cryptography in JavaScript: A Practical Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use