crypto-js vs jsencrypt vs node-forge vs openpgp vs tweetnacl
Client-Side Cryptography: Choosing the Right Library for Web Security
crypto-jsjsencryptnode-forgeopenpgptweetnaclSimilar Packages:

Client-Side Cryptography: Choosing the Right Library for Web Security

These five libraries provide essential cryptographic primitives for JavaScript developers, but they serve vastly different purposes. crypto-js offers a broad collection of classic algorithms like AES and SHA for general hashing and symmetric encryption. jsencrypt is a lightweight wrapper specifically for RSA key generation and simple encrypt/decrypt operations. node-forge is a comprehensive toolkit implementing TLS, PKI, and ASN.1 parsing, often used for certificate handling. openpgp brings the full OpenPGP standard (RFC 4880) to the browser for secure email and file signing. Finally, tweetnacl provides a minimal, high-security set of modern elliptic curve functions focused on simplicity and safety.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
crypto-js016,399487 kB2783 years agoMIT
jsencrypt06,804901 kB146a year agoMIT
node-forge05,3271.65 MB4615 months ago(BSD-3-Clause OR GPL-2.0)
openpgp05,96617.4 MB363 months agoLGPL-3.0+
tweetnacl01,921-67 years agoUnlicense

Client-Side Cryptography: A Deep Dive into JS Libraries

Choosing a cryptography library in JavaScript is not just about picking an algorithm; it is about selecting a security model that fits your architecture. The five libraries discussed hereβ€”crypto-js, jsencrypt, node-forge, openpgp, and tweetnaclβ€”solve different problems. Some are Swiss Army knives for legacy standards, while others are precision instruments for modern elliptic curve cryptography. Let's break down how they handle real-world engineering challenges.

πŸ” Symmetric Encryption: AES and Data Privacy

When you need to encrypt data locally (like saving a user's draft to LocalStorage) or secure a channel with a shared secret, you typically reach for AES. However, the implementation details vary wildly.

crypto-js provides a very approachable API for AES. It supports various modes, but developers often default to CBC without realizing they also need to manage Initialization Vectors (IVs) manually to ensure security.

// crypto-js: AES Encryption
import CryptoJS from 'crypto-js';

const message = "Secret Data";
const key = "MySecretKey12345"; // Must be 16, 24, or 32 chars

// Default is CBC mode. You MUST generate a random IV for production.
const iv = CryptoJS.lib.WordArray.random(128/8);
const encrypted = CryptoJS.AES.encrypt(message, key, { iv: iv });

console.log(encrypted.toString());

node-forge handles AES with a more verbose, low-level API that gives you explicit control over every byte. It is excellent when you need to match a specific legacy system's exact padding or mode requirements.

// node-forge: AES Encryption
import forge from 'node-forge';

const message = "Secret Data";
const key = forge.random.getBytesSync(16); // 128-bit key
const iv = forge.random.getBytesSync(16);

const cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({ iv: iv });
cipher.update(forge.util.createBuffer(message, 'utf8'));
cipher.finish();

const encrypted = cipher.output.getBytes();

tweetnacl does not support raw AES. Instead, it forces you to use crypto_secretbox, which combines XSalsa20 encryption and Poly1305 authentication. This prevents common mistakes like using AES without integrity checks, which can lead to padding oracle attacks.

// tweetnacl: Authenticated Encryption
import nacl from 'tweetnacl';

const message = nacl.util.decodeUTF8("Secret Data");
const nonce = nacl.randomBytes(nacl.secretbox.nonceLength);
const key = nacl.randomBytes(nacl.secretbox.keyLength);

const encryptedBox = nacl.secretbox(message, nonce, key);
// The result includes the authentication tag automatically

openpgp handles symmetric encryption differently. It is designed to encrypt sessions or files using a passphrase, automatically handling the complex packet structure of the OpenPGP standard.

// openpgp: Symmetric Encryption
import * as openpgp from 'openpgp';

const message = await openpgp.createMessage({ text: "Secret Data" });
const encrypted = await openpgp.encrypt({
  message,
  passwords: ['my-secret-passphrase'] // Uses SKESK (Symmetric Key Encrypted Session Key)
});

console.log(encrypted); // Returns armored PGP string

jsencrypt does not support symmetric encryption directly. It is strictly for RSA. To encrypt large data, you would typically generate a random AES key, encrypt the data with crypto-js, and then encrypt the AES key with jsencrypt.

πŸ”‘ Asymmetric Keys: RSA vs. Elliptic Curves

Public-key cryptography is essential for key exchange and digital signatures. The choice here defines your security posture and compatibility.

jsencrypt is the simplest way to get RSA working in the browser. It generates keys and encrypts small strings instantly. It is perfect for sending a login password or a session key to a server that holds the private RSA key.

// jsencrypt: RSA Key Generation & Encryption
import { JSEncrypt } from 'jsencrypt';

const encryptor = new JSEncrypt();
const keys = encryptor.generateKey(1024); // Generates 1024-bit pair

encryptor.setPublicKey(keys.publicKey);
const encrypted = encryptor.encrypt("Sensitive Token");

// Note: RSA can only encrypt data smaller than the key size.

node-forge offers a full RSA implementation including key generation, encryption, and signing. It allows you to manipulate the raw components (modulus, exponents) if you need to interoperate with Java or .NET systems that export keys in specific formats.

// node-forge: RSA Encryption
import forge from 'node-forge';

const pair = forge.pki.rsa.generateKeyPair(2048);
const publicKeyPem = forge.pki.publicKeyToPem(pair.publicKey);

const publicKey = forge.pki.publicKeyFromPem(publicKeyPem);
const encrypted = publicKey.encrypt("Sensitive Token", 'RSA-OAEP');

tweetnacl rejects RSA entirely in favor of Curve25519 (for encryption) and Ed25519 (for signatures). These curves are faster and safer against side-channel attacks. The API uses "boxes" where you combine your private key with the recipient's public key.

// tweetnacl: Elliptic Curve Encryption
import nacl from 'tweetnacl';

const recipientKeyPair = nacl.box.keyPair();
const myKeyPair = nacl.box.keyPair();

const message = nacl.util.decodeUTF8("Secure Message");
const nonce = nacl.randomBytes(nacl.box.nonceLength);

// Encrypts using recipient's public key and our private key
const encrypted = nacl.box(message, nonce, recipientKeyPair.publicKey, myKeyPair.secretKey);

openpgp manages complex key rings. It doesn't just encrypt; it binds identities to keys. You can encrypt a message to multiple recipients, and the library handles the session key encryption for each person automatically.

// openpgp: Multi-recipient Encryption
import * as openpgp from 'openpgp';

const recipientKeys = await openpgp.readKey({ armoredKey: publicKeyArmored });
const message = await openpgp.createMessage({ text: "Hello Alice and Bob" });

const encrypted = await openpgp.encrypt({
  message,
  encryptionKeys: [recipientKeys] // Can pass an array of keys
});

crypto-js does not support asymmetric cryptography. It is strictly for symmetric algorithms and hashing. Trying to implement RSA with crypto-js would require importing additional, non-standard plugins that are often unmaintained.

✍️ Digital Signatures and Integrity

Verifying that data hasn't been tampered with is critical for software updates, financial transactions, and API requests.

tweetnacl makes signing incredibly simple with crypto_sign. It produces a signature that is attached to the message, ensuring both integrity and authenticity using Ed25519.

// tweetnacl: Signing
import nacl from 'tweetnacl';

const keyPair = nacl.sign.keyPair();
const message = nacl.util.decodeUTF8("Do not transfer funds");

const signedMessage = nacl.sign(message, keyPair.secretKey);
// signedMessage contains both the original message and the signature

const isValid = nacl.sign.open(signedMessage, keyPair.publicKey) !== null;

node-forge provides detailed control over signing, allowing you to choose hash algorithms (SHA-256, SHA-1) and padding schemes explicitly. This is necessary when verifying signatures from legacy Certificate Authorities.

// node-forge: Signing
import forge from 'node-forge';

const md = forge.md.sha256.create();
md.update("Data to sign", 'utf8');

const privateKey = forge.pki.privateKeyFromPem(pemString);
const signature = privateKey.sign(md);

// Verification requires re-hashing and comparing

openpgp creates detached signatures or cleartext signed messages that are compatible with GPG command-line tools. This is the standard for verifying software releases (e.g., verifying a Linux distro ISO).

// openpgp: Detached Signature
import * as openpgp from 'openpgp';

const signingKey = await openpgp.readPrivateKey({ armoredKey: privateKeyArmored });
const message = await openpgp.createMessage({ text: "Release v1.0" });

const signature = await openpgp.sign({
  message,
  signingKeys: signingKey,
  detached: true // Returns only the signature packet
});

crypto-js handles hashing (SHA-256, HMAC) but does not create public/private key signatures. You can create an HMAC if both parties share a secret, but you cannot prove identity to a third party without a private key.

// crypto-js: HMAC (Shared Secret Integrity)
import CryptoJS from 'crypto-js';

const hash = CryptoJS.HmacSHA256("Message", "SharedSecret");
// This proves integrity but not identity to outsiders

jsencrypt supports RSA signing, but it is basic. It is useful if you need to sign a challenge-response authentication token using an RSA key pair generated in the browser.

// jsencrypt: RSA Signing
import { JSEncrypt } from 'jsencrypt';

const encryptor = new JSEncrypt();
encryptor.setPrivateKey(privateKeyPem);

const signature = encryptor.sign("Data to sign", "SHA256", "PKCS1v1.5");

πŸ› οΈ PKI and Certificate Handling

This is where the libraries diverge most sharply. Most web developers never touch X.509 certificates in the browser, but when you do, there is really only one choice.

node-forge is the undisputed leader here. It can parse PEM files, read Certificate Revocation Lists (CRLs), and even act as a Certificate Authority (CA) to issue new certificates entirely in client-side code. No other library on this list comes close to this capability.

// node-forge: Parsing a Certificate
import forge from 'node-forge';

const certPem = "-----BEGIN CERTIFICATE-----...";
const cert = forge.pki.certificateFromPem(certPem);

console.log(cert.subject.getField('CN').value); // Extract Common Name
console.log(cert.validity.notAfter); // Check expiration

openpgp manages its own form of PKI via the "Web of Trust," which is different from the X.509 hierarchy used by TLS. It handles key revocation certificates and user IDs within the PGP standard.

// openpgp: Revocation
import * as openpgp from 'openpgp';

const privateKey = await openpgp.readPrivateKey({ armoredKey: keyArmored });
const revocationCert = await privateKey.getRevocationCertificate();
// This certificate can be published to prove the key is no longer valid

crypto-js, jsencrypt, and tweetnacl have zero support for X.509 certificates or PKI infrastructure. They operate purely on raw keys and data buffers.

🧩 Interoperability and Standards

If your frontend needs to talk to a specific backend ecosystem, your choice is often made for you.

  • Legacy Enterprise / .NET / Java: If your backend uses standard Java javax.crypto or .NET System.Security.Cryptography, crypto-js is often the easiest match for AES and SHA. node-forge is required if the backend exchanges X.509 certificates.
  • Modern Microservices / Go / Rust: These languages often favor modern curves. tweetnacl (or its wrapper nacl-fast) aligns perfectly with libsodium-based backends, offering better performance and security defaults.
  • Email / Security Tools: If you are building a secure email client or a tool that must verify gpg --verify output, openpgp is the only viable option.
  • Simple Handshakes: For a quick login flow where the browser encrypts a password with a server's public key, jsencrypt reduces boilerplate significantly.

πŸ“Š Summary Comparison

Featurecrypto-jsjsencryptnode-forgeopenpgptweetnacl
Primary FocusClassic AlgorithmsSimple RSAPKI & TLSOpenPGP StandardModern Elliptic Curves
Symmetric Encryptionβœ… AES, DES, RC4βŒβœ… AES, DESβœ… (via Session Keys)βœ… (XSalsa20-Poly1305)
Asymmetric EncryptionβŒβœ… RSAβœ… RSAβœ… RSA + ECCβœ… Curve25519
Digital Signatures❌ (HMAC only)βœ… RSAβœ… RSA, DSAβœ… RSA + EdDSAβœ… Ed25519
Hashingβœ… MD5, SHA, RIPEMDβŒβœ… SHA, MD5βœ… SHA-2, SHA-3βœ… SHA-512 (internal)
Certificate (X.509)βŒβŒβœ… Full Support❌ (Uses PGP Keys)❌
Ease of Use⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐⭐
Security Defaults⚠️ Manual IV/Mode⚠️ Key Size Config⚠️ Complex APIβœ… Strong Defaultsβœ… Hardcoded Safe Defaults

πŸ’‘ The Architect's Recommendation

For new, security-critical applications, start with tweetnacl. Its API forces you into safe patterns (authenticated encryption) and uses modern math that is resistant to many attacks that plague older RSA/AES implementations. It is small, fast, and hard to misuse.

If you are building infrastructure tools that need to read certificates, generate CSRs, or interact with a traditional PKI, node-forge is your only real option in pure JavaScript. It is heavy, but it is the most powerful toolkit available.

Use openpgp strictly when you need compatibility with the PGP ecosystem (email, file signing). Do not use it for general-purpose HTTPS-style encryption; it is over-engineered for that.

Reserve crypto-js and jsencrypt for maintenance of legacy systems or for very specific, low-risk tasks like hashing a password before transmission (though HTTPS makes this redundant) or simple RSA handshakes where introducing a larger library is not justified. In greenfield projects requiring robust security, prefer the modern guarantees of tweetnacl or the comprehensive standards of openpgp.

How to Choose: crypto-js vs jsencrypt vs node-forge vs openpgp vs tweetnacl

  • crypto-js:

    Choose crypto-js when you need a quick, reliable implementation of standard algorithms like AES, DES, or SHA-256 for non-critical data obfuscation or legacy interoperability. It is ideal for hashing passwords before sending them over HTTPS or encrypting local storage data where key exchange is already handled by your backend. Avoid it for building new secure communication protocols, as it lacks modern authenticated encryption modes by default and requires careful configuration to prevent vulnerabilities.

  • jsencrypt:

    Select jsencrypt if your sole requirement is to perform simple RSA encryption in the browser, typically to secure a symmetric key or a small payload before sending it to a server. It is perfect for scenarios where you need to generate a key pair client-side and export the public key to a backend without dealing with complex ASN.1 structures. Do not use it for signing large documents or implementing full PKI workflows, as it is strictly limited to basic RSA operations.

  • node-forge:

    Opt for node-forge when your application requires heavy-duty PKI operations, such as parsing X.509 certificates, generating Certificate Signing Requests (CSRs), or handling TLS handshakes entirely in JavaScript. It is the go-to choice for tools that need to read PEM files, manage Certificate Authorities, or implement custom secure channels that rely on standard web PKI infrastructure. Be aware that its comprehensive feature set comes with a larger code footprint, making it less suitable for simple, lightweight tasks.

  • openpgp:

    Use openpgp when you need end-to-end encryption compatible with existing PGP/GPG ecosystems, such as secure email clients, file signing, or verifying software releases. It is the only choice here that fully implements the OpenPGP standard, supporting key rings, identity verification, and armored text formats. This library is essential if your users already possess PGP keys or if you need to interoperate with GNU Privacy Guard tools on the server side.

  • tweetnacl:

    Pick tweetnacl for modern applications requiring high-security, authenticated encryption using elliptic curves (Curve25519, Ed25519) with a minimal API surface. It is designed for developers who want to avoid configuration pitfalls by enforcing secure defaults, such as using crypto_box for sealed-box encryption or crypto_sign for digital signatures. Choose this for new security-critical features like secure messaging or wallet implementations where performance and resistance to side-channel attacks are paramount.

README for crypto-js

crypto-js

JavaScript library of crypto standards.

Discontinued

Active development of CryptoJS has been discontinued. This library is no longer maintained.

Nowadays, NodeJS and modern browsers have a native Crypto module. The latest version of CryptoJS already uses the native Crypto module for random number generation, since Math.random() is not crypto-safe. Further development of CryptoJS would result in it only being a wrapper of native Crypto. Therefore, development and maintenance has been discontinued, it is time to go for the native crypto module.

Node.js (Install)

Requirements:

  • Node.js
  • npm (Node.js package manager)
npm install crypto-js

Usage

ES6 import for typical API call signing use case:

import sha256 from 'crypto-js/sha256';
import hmacSHA512 from 'crypto-js/hmac-sha512';
import Base64 from 'crypto-js/enc-base64';

const message, nonce, path, privateKey; // ...
const hashDigest = sha256(nonce + message);
const hmacDigest = Base64.stringify(hmacSHA512(path + hashDigest, privateKey));

Modular include:

var AES = require("crypto-js/aes");
var SHA256 = require("crypto-js/sha256");
...
console.log(SHA256("Message"));

Including all libraries, for access to extra methods:

var CryptoJS = require("crypto-js");
console.log(CryptoJS.HmacSHA1("Message", "Key"));

Client (browser)

Requirements:

  • Node.js
  • Bower (package manager for frontend)
bower install crypto-js

Usage

Modular include:

require.config({
    packages: [
        {
            name: 'crypto-js',
            location: 'path-to/bower_components/crypto-js',
            main: 'index'
        }
    ]
});

require(["crypto-js/aes", "crypto-js/sha256"], function (AES, SHA256) {
    console.log(SHA256("Message"));
});

Including all libraries, for access to extra methods:

// Above-mentioned will work or use this simple form
require.config({
    paths: {
        'crypto-js': 'path-to/bower_components/crypto-js/crypto-js'
    }
});

require(["crypto-js"], function (CryptoJS) {
    console.log(CryptoJS.HmacSHA1("Message", "Key"));
});

Usage without RequireJS

<script type="text/javascript" src="path-to/bower_components/crypto-js/crypto-js.js"></script>
<script type="text/javascript">
    var encrypted = CryptoJS.AES(...);
    var encrypted = CryptoJS.SHA256(...);
</script>

API

See: https://cryptojs.gitbook.io/docs/

AES Encryption

Plain text encryption

var CryptoJS = require("crypto-js");

// Encrypt
var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123').toString();

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var originalText = bytes.toString(CryptoJS.enc.Utf8);

console.log(originalText); // 'my message'

Object encryption

var CryptoJS = require("crypto-js");

var data = [{id: 1}, {id: 2}]

// Encrypt
var ciphertext = CryptoJS.AES.encrypt(JSON.stringify(data), 'secret key 123').toString();

// Decrypt
var bytes  = CryptoJS.AES.decrypt(ciphertext, 'secret key 123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));

console.log(decryptedData); // [{id: 1}, {id: 2}]

List of modules

  • crypto-js/core
  • crypto-js/x64-core
  • crypto-js/lib-typedarrays

  • crypto-js/md5
  • crypto-js/sha1
  • crypto-js/sha256
  • crypto-js/sha224
  • crypto-js/sha512
  • crypto-js/sha384
  • crypto-js/sha3
  • crypto-js/ripemd160

  • crypto-js/hmac-md5
  • crypto-js/hmac-sha1
  • crypto-js/hmac-sha256
  • crypto-js/hmac-sha224
  • crypto-js/hmac-sha512
  • crypto-js/hmac-sha384
  • crypto-js/hmac-sha3
  • crypto-js/hmac-ripemd160

  • crypto-js/pbkdf2

  • crypto-js/aes
  • crypto-js/tripledes
  • crypto-js/rc4
  • crypto-js/rabbit
  • crypto-js/rabbit-legacy
  • crypto-js/evpkdf

  • crypto-js/format-openssl
  • crypto-js/format-hex

  • crypto-js/enc-latin1
  • crypto-js/enc-utf8
  • crypto-js/enc-hex
  • crypto-js/enc-utf16
  • crypto-js/enc-base64

  • crypto-js/mode-cfb
  • crypto-js/mode-ctr
  • crypto-js/mode-ctr-gladman
  • crypto-js/mode-ofb
  • crypto-js/mode-ecb

  • crypto-js/pad-pkcs7
  • crypto-js/pad-ansix923
  • crypto-js/pad-iso10126
  • crypto-js/pad-iso97971
  • crypto-js/pad-zeropadding
  • crypto-js/pad-nopadding

Release notes

4.2.0

Change default hash algorithm and iteration's for PBKDF2 to prevent weak security by using the default configuration.

Custom KDF Hasher

Blowfish support

4.1.1

Fix module order in bundled release.

Include the browser field in the released package.json.

4.1.0

Added url safe variant of base64 encoding. 357

Avoid webpack to add crypto-browser package. 364

4.0.0

This is an update including breaking changes for some environments.

In this version Math.random() has been replaced by the random methods of the native crypto module.

For this reason CryptoJS might not run in some JavaScript environments without native crypto module. Such as IE 10 or before or React Native.

3.3.0

Rollback, 3.3.0 is the same as 3.1.9-1.

The move of using native secure crypto module will be shifted to a new 4.x.x version. As it is a breaking change the impact is too big for a minor release.

3.2.1

The usage of the native crypto module has been fixed. The import and access of the native crypto module has been improved.

3.2.0

In this version Math.random() has been replaced by the random methods of the native crypto module.

For this reason CryptoJS might does not run in some JavaScript environments without native crypto module. Such as IE 10 or before.

If it's absolute required to run CryptoJS in such an environment, stay with 3.1.x version. Encrypting and decrypting stays compatible. But keep in mind 3.1.x versions still use Math.random() which is cryptographically not secure, as it's not random enough.

This version came along with CRITICAL BUG.

DO NOT USE THIS VERSION! Please, go for a newer version!

3.1.x

The 3.1.x are based on the original CryptoJS, wrapped in CommonJS modules.