JavaScript library of crypto standards.

Overview

crypto-js

JavaScript library of crypto standards.

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.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.

Comments
  • Native crypto module could not be used to get secure random number.

    Native crypto module could not be used to get secure random number.

    crypto-js npm runkit error.

    var CryptoJS = require("crypto-js");
    
    // Encrypt
    var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123');
    
    // Decrypt
    var bytes  = CryptoJS.AES.decrypt(ciphertext.toString(), 'secret key 123');
    var plaintext = bytes.toString(CryptoJS.enc.Utf8);
    

    run.

    Error: Native crypto module could not be used to get secure random number.

    opened by rkdqudtjs1 40
  • Security issue

    Security issue

    I'm a member of the Node.js Foundation Ecosystem Security Working Group and we received a report of a vulnerability in this module.

    We tried inviting the author by e-mail but received no response so I'm opening this issue and inviting anyone with commit and npm publish rights to collaborate with us on a fix.

    opened by MarcinHoppe 17
  • On BlockCipher reset, don't recreate _mode, just re-init.

    On BlockCipher reset, don't recreate _mode, just re-init.

    Crypto functions that need to reset their cipher a lot (such as CMAC) waste a lot of time repeatedly re-creating the encryptor/decryptor. While not exactly equivalent, re-initing the existing encryptor/decryptor turns out to be sufficient, thanks to the way modes are written to ignore any previous block information if the IV is set.

    This change might break custom block cipher modes, but it seems unlikely and would be easy to fix, so IMHO the performance improvement is worth it.


    This change is Reviewable

    opened by pkaminski 16
  • Bower support

    Bower support

    • Added bower.json file
    • Added .npmignore for easier NPM publish, it will prevent unneeded files to sneak in NPM installations
    • Modified package.json file (bumped version, added reference to build script, see new README.md section)
    • Commented out cleanup after build procedure (files are needed for Bower and NPM)

    Unfortunately, NPM publish directly from repository is not yet possible:

    require('crypto-js/build/crypto-js/lib-uncompressed/aes')
    

    is very ugly and I don't want to break backward compatibility with existing installations. So far I haven't found a way to explain NPM/Node to look for crypto-js/whatever not in root folder of package, but somewhere else.

    So for now NPM publish procedure will stay the same, unless I'll find a way to leave files in sub-folders and refer to them as before. Bower requires only pre-build and can be published without extra efforts.

    In order to register Bower package please do:

    bower register crypto-js git://github.com/evanvosberg/crypto-js.git
    

    So far package name crypto-js is not taken yet, so be quick :)

    What could be done after this is to make the following structure (I can't make builder to produce this kind of output):

    • crypto-js
    • build
      • components
      • rollupds
    • lib note that this folder will now contain uncompressed files
      • ...nodejs/amd stuff, point package.json's main property to index file there
    • lib-compressed
      • ...nodejs/amd stuff
    • src
      • ...raw files

    This will require users of previous NPM package to update their references from require('crypto-js/whatever') to require('crypto-js/lib/whatever') but it seems that this is a wide-spread practice to put stuff into lib.

    opened by kirill-konshin 15
  • [3.2.1] Unable to resolve module `crypto` from `node_modules/crypto-js/core.js`: crypto could not be found within the project.

    [3.2.1] Unable to resolve module `crypto` from `node_modules/crypto-js/core.js`: crypto could not be found within the project.

    I got

    Unable to resolve module `crypto` from `node_modules/crypto-js/core.js`: crypto could not be found within the project.
    

    when updated from 3.2.0 to 3.2.1

    duplicate 
    opened by Bardiamist 13
  • Error: Unable to resolve module `crypto` from

    Error: Unable to resolve module `crypto` from

    crypto-js use version @4.0.0

    My project is reactnative,I'm just do...

    1. npm install —-save crypto-js

    2. import MD5 from 'crypto-js/md5'

    And then,Is an error,The following information:

    error: bundling failed: Error: Unable to resolve module crypto from node_modules/crypto-js/core.js: crypto could not be found within the project.

    Please tell me what I should do,,Thank you very mucha

    opened by 90Mark 12
  • Decrypt stopped to work after update

    Decrypt stopped to work after update

    Hi guys, I am wondering why this not work after @[email protected] and @types/[email protected] upgrade:

    return CryptoJS.AES.decrypt(textToDecrypt, SECRET_KEY.trim()).toString(CryptoJS.enc.Utf8);

    image

    Could you tell me how to make it work after the library update?

    opened by tomaszzmudzinski 11
  • Use Object.create() instead of manipulating F.prototype.

    Use Object.create() instead of manipulating F.prototype.

    This makes a big improvement to performance throughout, since so many operations pass through extend and JITs get upset when a prototype is repeatedly (re)set.

    The caveat is that Object.create is not supported in IE8 and earlier. I didn't see any formal statement of what browsers crypto-js aims to be compatible with so hopefully that's all right.

    (@evanvosberg, I needed to get the crypto running faster in my app, so I spent a solid day profiling and optimizing. More PRs coming up.)


    This change is Reviewable

    enhancement 
    opened by pkaminski 8
  • Converting circular structure to JSON

    Converting circular structure to JSON

    Hi,

    I installed crypro js and was trying to do AES encrypt as follows.

    var userAES = CryptoJS.AES.encrypt(JSON.stringify(info.user), 'thisisakey');

    But it says "Unhandled rejection TypeError: Converting circular structure to JSON"

    opened by arunlals 8
  • Don't uglify NPM package source files

    Don't uglify NPM package source files

    The NPM source is uglified, which makes it difficult to debug errors when using it.

    I think it's best to not uglify the package, and people interested in doing so for browser usage can then run it through browserify and uglify when needed.

    This is related to https://github.com/bitcoinjs/bitcoinjs-lib/pull/57

    enhancement 
    opened by kyledrake 7
  • CryptoJS equivalent

    CryptoJS equivalent

    I'm trying to get CryptoJS to do the same as this from the "crypto" library...

    const what = timestamp + method.toUpperCase() + path + body;
    const key = Buffer.from(auth.secret, 'base64');
    const hmac = crypto.createHmac('sha256', key);
    const signature = hmac.update(what).digest('base64');
    

    This is what I have...

    const what = `${timestamp}${method}${path}${body}`;
    const hmac = CryptoJS.HmacSHA512(what, secret).toString();
    const wordArray = CryptoJS.enc.Utf8.parse(signed);
    const signature = CryptoJS.enc.Base64.stringify(wordArray);
    

    I'm sure it is something small but I can't seem to get it working.

    Is someone able to help?

    opened by whittlem 6
  • Unresolved variable enc, anything...

    Unresolved variable enc, anything...

    I used yarn add crypto-js to install and it's the latest version 4.1.1. However, no matter it's import CryptoJS from "crypto-js" or const CryptoJS = require("crypto-js"), I just couldn't use CryptoJS.enc, CryptoJS.AES and anything else, and WebStorm always tells me something like unresolved variable enc. 2022-12-29_20-35-39 2022-12-29_20-36-48 I don't understand why I meet this problem since everything is right with my other imports or requires.

    opened by oustr 0
  • 'TypeError: Cannot read properties of undefined (reading 'words')' error occuring while refreshing the application.

    'TypeError: Cannot read properties of undefined (reading 'words')' error occuring while refreshing the application.

    Hi everyone!

    I have implemented the crypto-Js in my application for local storage encryption and decryption. It works fine.

    Problem: : While refreshing, the page goes black and the console throws the error below:

    TypeError: Cannot read properties of undefined (reading 'words')
        at Object._doReset (aes.js:103:1)
        at Object.reset (cipher-core.js:119:1)
        at Object.reset (cipher-core.js:461:1)
        at Object.init (cipher-core.js:104:1)
        at subtype.init (core.js:149:1)
        at subtype.init (core.js:149:1)
        at subtype.init (core.js:149:1)
        at Object.create (core.js:176:1)
        at Object.createDecryptor (cipher-core.js:81:1)
        at Object.decrypt (cipher-core.js:728:1)
    

    NOTE : If i clear the local storage and try agian it works.But whenever i refresh the page this error occures and page goes blank.

    I would like to show you the encryption and decryption function that i have used as below:

    ................... imports .............
    import * as CryptoJs from 'crypto-js';
    
    let key: string;
    
    const SECURE_DATA = {
      encrypt: (state: string) => CryptoJs.AES.encrypt(state, key).toString(),
      decrypt: (state: string) => CryptoJs.AES.decrypt(state, key).toString(CryptoJs.enc.Utf8),
    };
    
    const STORE_KEYS_TO_PERSIST = [
      { auth: SECURE_DATA },
     ...
    
    ];
    
    export interface StoreState {
      auth: User;
    ....
    
    }
    
    export const reducers: ActionReducerMap<StoreState> = {
      auth: authReducer,
    ....
    };
    
    export function localStorageSyncReducer(
      reducer: ActionReducer<StoreState>
    ): ActionReducer<StoreState> {
      return localStorageSync({
        keys: STORE_KEYS_TO_PERSIST,
        rehydrate: true,
        syncCondition(state) {
          key = state.auth.token;
          return true;
        },
      })(reducer);
    }
    
    export function clearState(reducer) {
      return function (state, action) {
        if (action.type === ActionTypes.LOG_OUT) {
          state = undefined;
        }
        return reducer(state, action);
      };
    }
    
    export const metaReducers: Array<MetaReducer<StoreState, Action>> = [
      localStorageSyncReducer,
      clearState,
    ];
    
    
    opened by vijay310301 1
  • AES encrypt throws error when we pass key as WordArray

    AES encrypt throws error when we pass key as WordArray

    CryptoJS throws error when we pass AES key as WordArray. Here is a sample code to get this error.

    const CryptoJS = require("crypto-js");
    
    const data = JSON.stringify({ name: "John Doe" });
    const key = CryptoJS.enc.Utf8.parse("Example");
    
    const encrypted = CryptoJS.AES.encrypt(data, key);
    const decrypted = CryptoJS.AES.decrypt(encrypted, key);
    
    const decryptedString = decrypted.toString(CryptoJS.enc.Utf8);
    const decoded = JSON.parse(decryptedString);
    console.log(decoded);
    

    And this is what I get

    /Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:371
                            words[offset + i] ^= block[i];
                                                      ^
    
    TypeError: Cannot read properties of undefined (reading '0')
        at Object.xorBlock (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:371:44)
        at Object.processBlock (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:314:27)
        at Object._doProcessBlock (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:486:25)
        at Object._process (/Users/alex/Desktop/scripts/node_modules/crypto-js/core.js:632:27)
        at Object._doFinalize (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:501:46)
        at Object.finalize (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:163:44)
        at Object.encrypt (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:685:41)
        at Object.encrypt (/Users/alex/Desktop/scripts/node_modules/crypto-js/cipher-core.js:201:59)
        at Object.<anonymous> (/Users/alex/Desktop/scripts/decrypt.js:6:32)
        at Module._compile (node:internal/modules/cjs/loader:1159:14)
    
    Node.js v18.12.0
    

    The simple solution would be to pass key as a string, but in the project I'm working on we can only decrypt when we pass key as CryptoJS.enc.Utf8.parse().

    opened by alexandrsek 2
  • How to use Crypto JS in chrome extension.

    How to use Crypto JS in chrome extension.

    Hi, I am developing a chrome extension with crypto capabilities like aes256, sha256, and some assymetric encryption techniques. Is it possible to use crypto-js in chrome extension. If so can anyone please guide how to import the functions like SHA256 or AES?

    opened by mai1x9 2
  • Importing CryptoJS as JavaScript module

    Importing CryptoJS as JavaScript module

    There are some data that have been encrypted using CryptoJS v3.1.2 in a Chrome extension, that need to be decrypted once (no encrypting) in an upgrade.

    • I would like to import them as standard JavaScript module
    • I would like to decrypt with minimal amount of code possible

    The decryption process is:

    CryptoJS.AES.decrypt(item, key).toString(CryptoJS.enc.Utf8)
    
    opened by erosman 6
Owner
Brix
JavaScript Libraries by Evan Vosberg
Brix
Crypto-tracker - Get crypto currency data in one click. Followed by a few more clicks.

https://crypto-tracker-ayaanzaveri08.vercel.app/ Crypto Tracker Crypto Tracker tracks crypto with the CoinGecko API. This app uses the React framework

Ayaan Zaveri 0 Apr 30, 2022
🌈 Put a date and a crypto, optionally a quantity of that crypto, to see how much has augmented/increased in dollars & percentage

crypif Put a date and a crypto, optionally a quantity of that crypto, to see how much has augmented/increased in dollars & percentage Figma I still ha

Eliaz Bobadilla 8 Apr 4, 2022
An easy-to-read, quick reference for JS best practices, accepted coding standards, and links around the Web

Feel free to contribute! Where? http://www.jstherightway.org Why? Today we have a bunch of websites running JavaScript. I think we need a place to put

BrazilJS 8.5k Jan 1, 2023
Fast & Robust Front-End Micro-framework based on modern standards

Chat on gitter Hello slim.js - your declarative web components library import { Slim } from 'slim-js'; import { tag, template } from 'slim-js/decorato

slim.js 942 Dec 30, 2022
An implementation of Saudi Arabia ZATCA's E-Invoicing requirements, processes, and standards in TypeScript.

v0.1.0 (experimental) An implementation of Saudi Arabia ZATCA's E-Invoicing requirements, processes, and standards in TypeScript. Read the documentati

wes4m 32 Dec 27, 2022
Shikhar 4 Oct 9, 2022
A Multichain crypto wallet library that supports Ethereum, Solana and other EVM compatible blockchains.

Multichain Crypto Wallet A Multichain crypto wallet library that supports Ethereum, Solana and other EVM compatible blockchains. Installation npm inst

Abdulfatai Suleiman 117 Jan 2, 2023
Multi-chain defi crypto sniper written in typescript/javascript. Fastest method of sniping with auto-sell and rug prevention features.

CryptoSniper Community Edition Multi-chain defi crypto sniper written in typescript/javascript. Fastest method of sniping with auto-sell and rug preve

null 18 Nov 3, 2022
A super simple and lightweight API to get crypto token live information.

TokenStats ?? ?? A super simple and lightweight API to get crypto token live information. APP URL https://tokenstats.herokuapp.com/ Quick Start To get

Abdulfatai Suleiman 21 Jun 28, 2022
🪙💬 Update a gist to contain a crypto price

crypto-box Update a pinned gist to contain a crypto price ?? ✨ For more pinned-gist projects like this one, check out: matchai/awesome-pinned-gists Se

Austen Stone 3 Nov 30, 2022
Pay Creators to Promote your Product in $CRYPTO

Next.js + Tailwind CSS Example This example shows how to use Tailwind CSS (v3.0) with Next.js. It follows the steps outlined in the official Tailwind

Satyam Kulkarni 1 Feb 7, 2022
An api named Crypto Versus, a multiplayer versus hacking simulator. Project still in the making!

Crypto Versus A Multiplayer Versus Hacking Simulation Inspired by the Steam game Bitburner Table of content Possible ouputs for all endpoints routes /

null 3 Jan 29, 2022
Awesome critique of crypto / web3. Curated list of high quality critique plus background. Seek to be as constructive as possible.

Awesome critique of crypto/web3 Awesome critique of crypto/web3, etc. Contributions are welcome. Critique General Stephen Diehl series - https://www.s

Rufus Pollock 1.5k Jan 1, 2023
Crawler Crypto using NodeJS for performance with Elasticsearch DB for high efficiency.

Coin crawler - Coingecko version Crawler using NodeJS for performance with Elasticsearch DB for high efficiency. Requirements For development, you wil

Minh.N.Pham 1 Jan 20, 2022
A super simple web3 API to allow crypto interactions with the Solana Network 🔑🌐

orca.js A JavaScript API for web3 Transaction and Authenticating PLEASE NOTE: orca.js is still in development! And comming soon in 2022. Stay tuned on

null 3 Mar 20, 2022
A super simple web3 API to allow crypto interactions with the Solana Network 🔑🌐

orca.js A JavaScript API for web3 Transaction and Authenticating PLEASE NOTE: orca.js is still in development! And comming soon in 2022. Stay tuned on

null 3 Mar 20, 2022
Stays: book accommodation on-chain, pay in crypto, and help local communities

Stays: on-chain bookings Installation Make sure you have node and nvm installed: nvm use v16 npm install -g yarn npm install -g lerna yarn install ler

Winding Tree 8 Jun 2, 2022
MultiSafe is a shared crypto wallet for managing Stacks (STX) and Bitcoin (BTC).

MultiSafe MultiSafe is a shared crypto wallet for managing Stacks (STX) and Bitcoin (BTC). Deploy a MultiSafe https://app.multisafe.xyz/ Features Curr

Trust Machines 22 Dec 26, 2022
Crypto Basket - Free Blockchain Press Release

ADD YOUR CONTENT Upload all files to IPFS All non-IPFS links should be inside LINKS Sections Use markdown syntax How to add content to CryptoBasket ?

Money Mafia 14 Dec 15, 2022