Convert Figma logo to code with AI

brix logocrypto-js

JavaScript library of crypto standards.

15,712
2,379
15,712
272

Top Related Projects

5,034

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps

Fast Elliptic Curve Cryptography in plain javascript

7,179

Stanford Javascript Crypto Library

Port of TweetNaCl cryptographic library to JavaScript

1,441

A pure JavaScript implementation of the AES block cipher and all common modes of operation for node.js or web browsers.

Quick Overview

CryptoJS is a JavaScript library of cryptographic standards and algorithms. It provides a wide range of cryptographic functions, including hashing, encryption, and encoding, making it useful for implementing security features in web applications.

Pros

  • Comprehensive set of cryptographic functions
  • Easy to use and integrate into existing projects
  • Well-documented with examples
  • Supports both browser and Node.js environments

Cons

  • Not actively maintained (last commit was in 2019)
  • Performance may be slower compared to native implementations
  • Limited support for more recent cryptographic algorithms
  • Potential security vulnerabilities due to lack of updates

Code Examples

  1. SHA-256 Hashing:
const hash = CryptoJS.SHA256("Hello, World!");
console.log(hash.toString());
  1. AES Encryption and Decryption:
const plaintext = "Secret message";
const key = "MySecretKey123";

const encrypted = CryptoJS.AES.encrypt(plaintext, key).toString();
console.log("Encrypted:", encrypted);

const decrypted = CryptoJS.AES.decrypt(encrypted, key).toString(CryptoJS.enc.Utf8);
console.log("Decrypted:", decrypted);
  1. Base64 Encoding and Decoding:
const data = "Hello, World!";
const encoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data));
console.log("Encoded:", encoded);

const decoded = CryptoJS.enc.Base64.parse(encoded).toString(CryptoJS.enc.Utf8);
console.log("Decoded:", decoded);

Getting Started

  1. Install CryptoJS using npm:
npm install crypto-js
  1. Import and use CryptoJS in your JavaScript file:
const CryptoJS = require('crypto-js');

// Example usage
const hash = CryptoJS.MD5("Hello, World!");
console.log(hash.toString());

For browser usage, include the CryptoJS library in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

Then use CryptoJS functions directly in your JavaScript code.

Competitor Comparisons

5,034

A native implementation of TLS in Javascript and tools to write crypto-based and network-heavy webapps

Pros of Forge

  • More comprehensive cryptographic toolkit with a wider range of algorithms and utilities
  • Better performance for certain operations, especially in Node.js environments
  • Active development and maintenance with regular updates

Cons of Forge

  • Larger bundle size, which may impact load times in browser environments
  • Steeper learning curve due to its more extensive API and features
  • Less widespread adoption compared to Crypto-js

Code Comparison

Forge:

var md = forge.md.sha256.create();
md.update('The quick brown fox jumps over the lazy dog');
console.log(md.digest().toHex());

Crypto-js:

var hash = CryptoJS.SHA256('The quick brown fox jumps over the lazy dog');
console.log(hash.toString(CryptoJS.enc.Hex));

Both libraries provide similar functionality for common cryptographic operations, but Forge offers a more object-oriented approach with additional methods and options. Crypto-js tends to have a simpler API for basic use cases, while Forge provides more flexibility and control over the cryptographic processes.

Forge is generally preferred for more complex cryptographic needs or when performance is crucial, especially in Node.js environments. Crypto-js remains popular for its simplicity and ease of use, particularly in browser-based applications where a smaller bundle size is advantageous.

Fast Elliptic Curve Cryptography in plain javascript

Pros of elliptic

  • Specialized for elliptic curve cryptography, offering more advanced ECC operations
  • Lightweight and focused, potentially better performance for ECC-specific tasks
  • Supports a wider range of elliptic curves and algorithms

Cons of elliptic

  • Limited to elliptic curve cryptography, less versatile for general cryptographic needs
  • Smaller community and fewer resources compared to the more popular crypto-js
  • May require more cryptographic expertise to use effectively

Code Comparison

elliptic:

const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const key = ec.genKeyPair();
const publicKey = key.getPublic('hex');
const signature = key.sign('message').toDER('hex');

crypto-js:

const CryptoJS = require('crypto-js');
const message = 'Hello, World!';
const secret = 'mySecret';
const encrypted = CryptoJS.AES.encrypt(message, secret).toString();
const decrypted = CryptoJS.AES.decrypt(encrypted, secret).toString(CryptoJS.enc.Utf8);

Summary

elliptic is a specialized library for elliptic curve cryptography, offering advanced ECC operations and supporting various curves. It's lightweight and potentially more performant for ECC tasks. However, it's limited in scope compared to crypto-js, which provides a broader range of cryptographic functions. crypto-js is more versatile and has a larger community, making it easier to use for general cryptographic needs. The choice between the two depends on the specific requirements of your project and your level of cryptographic expertise.

7,179

Stanford Javascript Crypto Library

Pros of sjcl

  • Better performance for certain cryptographic operations
  • More comprehensive suite of cryptographic primitives
  • Designed with a focus on security and resistance to side-channel attacks

Cons of sjcl

  • Less actively maintained compared to crypto-js
  • Steeper learning curve for beginners
  • Smaller community and fewer resources available online

Code Comparison

sjcl:

var encrypted = sjcl.encrypt("password", "message");
var decrypted = sjcl.decrypt("password", encrypted);

crypto-js:

var encrypted = CryptoJS.AES.encrypt("message", "password");
var decrypted = CryptoJS.AES.decrypt(encrypted, "password").toString(CryptoJS.enc.Utf8);

Both libraries offer similar functionality for basic encryption and decryption operations. However, sjcl provides a more concise API for these tasks, while crypto-js requires additional steps for decryption and encoding.

sjcl is generally considered more secure and performant for advanced cryptographic operations, but crypto-js has a larger user base and more frequent updates. The choice between the two depends on specific project requirements, security needs, and developer familiarity with each library.

Port of TweetNaCl cryptographic library to JavaScript

Pros of TweetNaCl-js

  • Focused on modern, high-security cryptographic primitives
  • Smaller library size, suitable for lightweight applications
  • Implements the entire NaCl cryptography library in JavaScript

Cons of TweetNaCl-js

  • Limited to NaCl algorithms, less versatile than CryptoJS
  • May have a steeper learning curve for developers unfamiliar with NaCl

Code Comparison

TweetNaCl-js:

import nacl from 'tweetnacl';

const keyPair = nacl.box.keyPair();
const message = 'Hello, World!';
const nonce = nacl.randomBytes(nacl.box.nonceLength);
const encrypted = nacl.box(message, nonce, keyPair.publicKey, keyPair.secretKey);

CryptoJS:

import CryptoJS from 'crypto-js';

const secretKey = 'mySecretKey';
const message = 'Hello, World!';
const encrypted = CryptoJS.AES.encrypt(message, secretKey).toString();

Summary

TweetNaCl-js is a compact, modern cryptography library focused on NaCl algorithms, while CryptoJS offers a broader range of cryptographic functions. TweetNaCl-js is ideal for projects requiring high-security primitives and minimal size, whereas CryptoJS provides more versatility and familiarity for general-purpose cryptography needs.

1,441

A pure JavaScript implementation of the AES block cipher and all common modes of operation for node.js or web browsers.

Pros of aes-js

  • Lightweight and focused specifically on AES encryption
  • Provides a simpler API for basic AES operations
  • Supports various modes of operation (ECB, CBC, CFB, OFB, CTR)

Cons of aes-js

  • Limited to AES encryption only, lacking other cryptographic functions
  • Less actively maintained compared to crypto-js
  • Smaller community and fewer resources available

Code Comparison

aes-js:

var aesjs = require('aes-js');
var key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
var text = 'Text may be any length you wish, no padding is required.';
var textBytes = aesjs.utils.utf8.toBytes(text);
var aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(textBytes);

crypto-js:

var CryptoJS = require('crypto-js');
var key = CryptoJS.enc.Utf8.parse('1234567890123456');
var iv = CryptoJS.enc.Utf8.parse('1234567890123456');
var encrypted = CryptoJS.AES.encrypt('Message', key, { iv: iv });
var decrypted = CryptoJS.AES.decrypt(encrypted, key, { iv: iv });

Both libraries offer AES encryption capabilities, but crypto-js provides a more comprehensive set of cryptographic functions beyond just AES. aes-js is more lightweight and focused, while crypto-js offers a broader range of features and has a larger community. The choice between them depends on specific project requirements and the need for additional cryptographic operations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

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.

NPM DownloadsLast 30 Days