Convert Figma logo to code with AI

ricmoo logoaes-js

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

1,441
273
1,441
32

Top Related Projects

15,712

JavaScript library of crypto standards.

7,179

Stanford Javascript Crypto Library

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

Quick Overview

aes-js is a pure JavaScript implementation of the AES (Advanced Encryption Standard) block cipher algorithm. It provides a lightweight and easy-to-use solution for AES encryption and decryption in JavaScript environments, including both browser and Node.js.

Pros

  • Pure JavaScript implementation, no external dependencies
  • Supports multiple modes of operation (ECB, CBC, CFB, OFB, CTR)
  • Compatible with both browser and Node.js environments
  • Lightweight and easy to integrate into existing projects

Cons

  • May have lower performance compared to native implementations
  • Not actively maintained (last commit was in 2019)
  • Limited to AES encryption only, doesn't provide a full cryptographic suite
  • Lacks some advanced features found in more comprehensive libraries

Code Examples

  1. Basic AES-128 ECB encryption:
const aesjs = require('aes-js');

const key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const text = 'Text may be any length you wish, no padding is required.';
const textBytes = aesjs.utils.utf8.toBytes(text);

const aesCtr = new aesjs.ModeOfOperation.ecb(key);
const encryptedBytes = aesCtr.encrypt(textBytes);

const encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
  1. AES-256 CTR mode encryption and decryption:
const aesjs = require('aes-js');

const key = aesjs.utils.utf8.toBytes('ThisIsA32ByteKeyForAES256BitEnc');
const text = 'Text to be encrypted';
const textBytes = aesjs.utils.utf8.toBytes(text);

const aesCtr = new aesjs.ModeOfOperation.ctr(key);
const encryptedBytes = aesCtr.encrypt(textBytes);

// To decrypt, we create a new instance with the same key
const aesCtr2 = new aesjs.ModeOfOperation.ctr(key);
const decryptedBytes = aesCtr2.decrypt(encryptedBytes);

const decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
  1. Using CBC mode with a random IV:
const aesjs = require('aes-js');
const crypto = require('crypto');

const key = aesjs.utils.utf8.toBytes('ThisIsA32ByteKeyForAES256BitEnc');
const iv = crypto.randomBytes(16);
const text = 'Text to be encrypted';
const textBytes = aesjs.utils.utf8.toBytes(text);

const aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
const encryptedBytes = aesCbc.encrypt(aesjs.padding.pkcs7.pad(textBytes));

console.log(aesjs.utils.hex.fromBytes(encryptedBytes));

Getting Started

To use aes-js in your project, follow these steps:

  1. Install the library using npm:

    npm install aes-js
    
  2. Import the library in your JavaScript file:

    const aesjs = require('aes-js');
    
  3. Create an encryption key and initialize the desired mode of operation:

    const key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
    const aesCtr = new aesjs.ModeOfOperation.ctr(key);
    
  4. Encrypt or decrypt data as needed using the methods provided by the library.

Competitor Comparisons

15,712

JavaScript library of crypto standards.

Pros of crypto-js

  • Comprehensive library with support for multiple cryptographic algorithms
  • Well-established and widely used in the community
  • Provides a higher-level API for easier implementation

Cons of crypto-js

  • Larger file size due to its comprehensive nature
  • May have slower performance for specific AES operations
  • Less focused on AES-specific optimizations

Code Comparison

crypto-js:

var CryptoJS = require("crypto-js");
var encrypted = CryptoJS.AES.encrypt("Message", "Secret Passphrase");
var decrypted = CryptoJS.AES.decrypt(encrypted, "Secret Passphrase");
var plaintext = decrypted.toString(CryptoJS.enc.Utf8);

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 aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(aesjs.utils.utf8.toBytes("Message"));
var decryptedBytes = aesCtr.decrypt(encryptedBytes);

Summary

crypto-js offers a more comprehensive solution for various cryptographic needs, while aes-js focuses specifically on AES implementation. crypto-js provides an easier-to-use API but may have performance trade-offs for AES operations. aes-js offers a more lightweight and AES-focused approach, potentially providing better performance for specific AES use cases.

7,179

Stanford Javascript Crypto Library

Pros of sjcl

  • More comprehensive cryptographic library with additional algorithms beyond AES
  • Supports a wider range of encryption modes (e.g., CCM, OCB)
  • Actively maintained with regular updates and contributions

Cons of sjcl

  • Larger file size due to its comprehensive nature
  • Steeper learning curve for developers only needing basic AES functionality
  • May have slower performance for simple AES operations due to additional features

Code Comparison

sjcl:

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

aes-js:

var key = aesjs.utils.utf8.toBytes("password");
var aesCtr = new aesjs.ModeOfOperation.ctr(key);
var encrypted = aesCtr.encrypt(aesjs.utils.utf8.toBytes("message"));
var decrypted = aesCtr.decrypt(encrypted);

Summary

sjcl offers a more comprehensive cryptographic solution with support for various algorithms and modes, making it suitable for complex security requirements. However, this comes at the cost of a larger file size and potentially slower performance for basic AES operations. aes-js, on the other hand, provides a lightweight and focused AES implementation, which may be preferable for projects with simpler encryption needs or performance constraints.

5,034

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

Pros of Forge

  • Comprehensive cryptographic toolkit with support for multiple algorithms and protocols
  • Active development and maintenance with regular updates
  • Extensive documentation and examples for various use cases

Cons of Forge

  • Larger file size and potentially slower performance due to its comprehensive nature
  • Steeper learning curve for developers who only need basic AES functionality
  • May include unnecessary features for projects requiring only AES encryption

Code Comparison

AES encryption using Forge:

var cipher = forge.cipher.createCipher('AES-CBC', key);
cipher.start({iv: iv});
cipher.update(forge.util.createBuffer(plaintext));
cipher.finish();
var encrypted = cipher.output.getBytes();

AES encryption using aes-js:

var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
var encrypted = aesCbc.encrypt(aesjs.utils.utf8.toBytes(plaintext));

Forge offers a more verbose API with additional configuration options, while aes-js provides a simpler, more straightforward approach for basic AES operations. Forge's comprehensive nature makes it suitable for projects requiring various cryptographic functionalities, whereas aes-js is more focused and lightweight, ideal for projects specifically needing AES encryption.

Fast Elliptic Curve Cryptography in plain javascript

Pros of elliptic

  • Broader cryptographic functionality, including elliptic curve cryptography
  • More comprehensive and feature-rich library for cryptographic operations
  • Active development and maintenance

Cons of elliptic

  • Larger library size, potentially impacting load times and bundle sizes
  • Steeper learning curve due to more complex API and wider range of features
  • May be overkill for projects only requiring AES encryption

Code Comparison

elliptic (Elliptic Curve Key Generation):

const EC = require('elliptic').ec;
const ec = new EC('secp256k1');
const key = ec.genKeyPair();

aes-js (AES Encryption):

const aesjs = require('aes-js');
const key = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const aesCtr = new aesjs.ModeOfOperation.ctr(key);

Summary

elliptic offers a more comprehensive cryptographic toolkit, including elliptic curve operations, making it suitable for complex cryptographic needs. However, it comes with increased complexity and size. aes-js, on the other hand, focuses solely on AES encryption, providing a simpler and more lightweight solution for projects with specific AES requirements.

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

AES-JS

npm version

A pure JavaScript implementation of the AES block cipher algorithm and all common modes of operation (CBC, CFB, CTR, ECB and OFB).

Features

  • Pure JavaScript (with no dependencies)
  • Supports all key sizes (128-bit, 192-bit and 256-bit)
  • Supports all common modes of operation (CBC, CFB, CTR, ECB and OFB)
  • Works in either node.js or web browsers

Migrating from 2.x to 3.x

The utility functions have been renamed in the 3.x branch, since they were causing a great deal of confusion converting between bytes and string.

The examples have also been updated to encode binary data as printable hex strings.

Strings and Bytes

Strings should NOT be used as keys. UTF-8 allows variable length, multi-byte characters, so a string that is 16 characters long may not be 16 bytes long.

Also, UTF8 should NOT be used to store arbitrary binary data as it is a string encoding format, not a binary encoding format.

// aesjs.util.convertStringToBytes(aString)
// Becomes:
aesjs.utils.utf8.toBytes(aString)


// aesjs.util.convertBytesToString(aString)
// Becomes:
aesjs.utils.utf8.fromBytes(aString)

Bytes and Hex strings

Binary data, such as encrypted bytes, can safely be stored and printed as hexidecimal strings.

// aesjs.util.convertStringToBytes(aString, 'hex')
// Becomes:
aesjs.utils.hex.toBytes(aString)


// aesjs.util.convertBytesToString(aString, 'hex')
// Becomes:
aesjs.utils.hex.fromBytes(aString)

Typed Arrays

The 3.x and above versions of aes-js use Uint8Array instead of Array, which reduces code size when used with Browserify (it no longer pulls in Buffer) and is also about twice the speed.

However, if you need to support browsers older than IE 10, you should continue using version 2.x.

API

Node.js

To install aes-js in your node.js project:

npm install aes-js

And to access it from within node, simply add:

var aesjs = require('aes-js');

Web Browser

To use aes-js in a web page, add the following:

<script type="text/javascript" src="https://cdn.rawgit.com/ricmoo/aes-js/e27b99df/index.js"></script>

Keys

All keys must be 128 bits (16 bytes), 192 bits (24 bytes) or 256 bits (32 bytes) long.

The library work with Array, Uint8Array and Buffer objects as well as any array-like object (i.e. must have a length property, and have a valid byte value for each entry).

// 128-bit, 192-bit and 256-bit keys
var key_128 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
var key_192 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
               16, 17, 18, 19, 20, 21, 22, 23];
var key_256 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
               16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
               29, 30, 31];

// or, you may use Uint8Array:
var key_128_array = new Uint8Array(key_128);
var key_192_array = new Uint8Array(key_192);
var key_256_array = new Uint8Array(key_256);

// or, you may use Buffer in node.js:
var key_128_buffer = Buffer.from(key_128);
var key_192_buffer = Buffer.from(key_192);
var key_256_buffer = Buffer.from(key_256);

To generate keys from simple-to-remember passwords, consider using a password-based key-derivation function such as scrypt or bcrypt.

Common Modes of Operation

There are several modes of operations, each with various pros and cons. In general though, the CBC and CTR modes are recommended. The ECB is NOT recommended., and is included primarily for completeness.

CTR - Counter (recommended)

// An example 128-bit key (16 bytes * 8 bits/byte = 128 bits)
var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// Convert text to bytes
var text = 'Text may be any length you wish, no padding is required.';
var textBytes = aesjs.utils.utf8.toBytes(text);

// The counter is optional, and if omitted will begin at 1
var aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
var encryptedBytes = aesCtr.encrypt(textBytes);

// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// "a338eda3874ed884b6199150d36f49988c90f5c47fe7792b0cf8c7f77eeffd87
//  ea145b73e82aefcf2076f881c88879e4e25b1d7b24ba2788"

// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// The counter mode of operation maintains internal state, so to
// decrypt a new instance must be instantiated.
var aesCtr = new aesjs.ModeOfOperation.ctr(key, new aesjs.Counter(5));
var decryptedBytes = aesCtr.decrypt(encryptedBytes);

// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
// "Text may be any length you wish, no padding is required."

CBC - Cipher-Block Chaining (recommended)

// An example 128-bit key
var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// The initialization vector (must be 16 bytes)
var iv = [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];

// Convert text to bytes (text must be a multiple of 16 bytes)
var text = 'TextMustBe16Byte';
var textBytes = aesjs.utils.utf8.toBytes(text);

var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
var encryptedBytes = aesCbc.encrypt(textBytes);

// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// "104fb073f9a131f2cab49184bb864ca2"

// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// The cipher-block chaining mode of operation maintains internal
// state, so to decrypt a new instance must be instantiated.
var aesCbc = new aesjs.ModeOfOperation.cbc(key, iv);
var decryptedBytes = aesCbc.decrypt(encryptedBytes);

// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
// "TextMustBe16Byte"

CFB - Cipher Feedback

// An example 128-bit key
var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// The initialization vector (must be 16 bytes)
var iv = [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];

// Convert text to bytes (must be a multiple of the segment size you choose below)
var text = 'TextMustBeAMultipleOfSegmentSize';
var textBytes = aesjs.utils.utf8.toBytes(text);

// The segment size is optional, and defaults to 1
var segmentSize = 8;
var aesCfb = new aesjs.ModeOfOperation.cfb(key, iv, segmentSize);
var encryptedBytes = aesCfb.encrypt(textBytes);

// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// "55e3af2638c560b4fdb9d26a630733ea60197ec23deb85b1f60f71f10409ce27"

// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// The cipher feedback mode of operation maintains internal state,
// so to decrypt a new instance must be instantiated.
var aesCfb = new aesjs.ModeOfOperation.cfb(key, iv, 8);
var decryptedBytes = aesCfb.decrypt(encryptedBytes);

// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
// "TextMustBeAMultipleOfSegmentSize"

OFB - Output Feedback

// An example 128-bit key
var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// The initialization vector (must be 16 bytes)
var iv = [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34,35, 36 ];

// Convert text to bytes
var text = 'Text may be any length you wish, no padding is required.';
var textBytes = aesjs.utils.utf8.toBytes(text);

var aesOfb = new aesjs.ModeOfOperation.ofb(key, iv);
var encryptedBytes = aesOfb.encrypt(textBytes);

// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// "55e3af2655dd72b9f32456042f39bae9accff6259159e608be55a1aa313c598d
//  b4b18406d89c83841c9d1af13b56de8eda8fcfe9ec8e75e8"

// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// The output feedback mode of operation maintains internal state,
// so to decrypt a new instance must be instantiated.
var aesOfb = new aesjs.ModeOfOperation.ofb(key, iv);
var decryptedBytes = aesOfb.decrypt(encryptedBytes);

// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
// "Text may be any length you wish, no padding is required."

ECB - Electronic Codebook (NOT recommended)

This mode is not recommended. Since, for a given key, the same plaintext block in produces the same ciphertext block out, this mode of operation can leak data, such as patterns. For more details and examples, see the Wikipedia article, Electronic Codebook.

// An example 128-bit key
var key = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ];

// Convert text to bytes
var text = 'TextMustBe16Byte';
var textBytes = aesjs.utils.utf8.toBytes(text);

var aesEcb = new aesjs.ModeOfOperation.ecb(key);
var encryptedBytes = aesEcb.encrypt(textBytes);

// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// "a7d93b35368519fac347498dec18b458"

// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// Since electronic codebook does not store state, we can
// reuse the same instance.
//var aesEcb = new aesjs.ModeOfOperation.ecb(key);
var decryptedBytes = aesEcb.decrypt(encryptedBytes);

// Convert our bytes back into text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
// "TextMustBe16Byte"

Block Cipher

You should usually use one of the above common modes of operation. Using the block cipher algorithm directly is also possible using ECB as that mode of operation is merely a thin wrapper.

But this might be useful to experiment with custom modes of operation or play with block cipher algorithms.


// the AES block cipher algorithm works on 16 byte bloca ks, no more, no less
var text = "ABlockIs16Bytes!";
var textAsBytes = aesjs.utils.utf8.toBytes(text)
console.log(textAsBytes);
// [65, 66, 108, 111, 99, 107, 73, 115, 49, 54, 66, 121, 116, 101, 115, 33]

// create an instance of the block cipher algorithm
var key = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3];
var aes = new aesjs.AES(key);

// encrypt...
var encryptedBytes = aes.encrypt(textAsBytes);
console.log(encryptedBytes);
// [136, 15, 199, 174, 118, 133, 233, 177, 143, 47, 42, 211, 96, 55, 107, 109] 

// To print or store the binary data, you may convert it to hex
var encryptedHex = aesjs.utils.hex.fromBytes(encryptedBytes);
console.log(encryptedHex);
// "880fc7ae7685e9b18f2f2ad360376b6d"

// When ready to decrypt the hex string, convert it back to bytes
var encryptedBytes = aesjs.utils.hex.toBytes(encryptedHex);

// decrypt...
var decryptedBytes = aes.decrypt(encryptedBytes);
console.log(decryptedBytes);
// [65, 66, 108, 111, 99, 107, 73, 115, 49, 54, 66, 121, 116, 101, 115, 33]


// decode the bytes back into our original text
var decryptedText = aesjs.utils.utf8.fromBytes(decryptedBytes);
console.log(decryptedText);
// "ABlockIs16Bytes!"

Notes

What is a Key

This seems to be a point of confusion for many people new to using encryption. You can think of the key as the "password". However, these algorithms require the "password" to be a specific length.

With AES, there are three possible key lengths, 128-bit (16 bytes), 192-bit (24 bytes) or 256-bit (32 bytes). When you create an AES object, the key size is automatically detected, so it is important to pass in a key of the correct length.

Often, you wish to provide a password of arbitrary length, for example, something easy to remember or write down. In these cases, you must come up with a way to transform the password into a key of a specific length. A Password-Based Key Derivation Function (PBKDF) is an algorithm designed for this exact purpose.

Here is an example, using the popular (possibly obsolete?) pbkdf2:

var pbkdf2 = require('pbkdf2');

var key_128 = pbkdf2.pbkdf2Sync('password', 'salt', 1, 128 / 8, 'sha512');
var key_192 = pbkdf2.pbkdf2Sync('password', 'salt', 1, 192 / 8, 'sha512');
var key_256 = pbkdf2.pbkdf2Sync('password', 'salt', 1, 256 / 8, 'sha512');

Another possibility, is to use a hashing function, such as SHA256 to hash the password, but this method is vulnerable to Rainbow Attacks, unless you use a salt.

Performance

Todo...

Tests

A test suite has been generated (test/test-vectors.json) from a known correct implementation, pycrypto. To generate new test vectors, run python generate-tests.py.

To run the node.js test suite:

npm test

To run the web browser tests, open the test/test.html file in your browser.

FAQ

How do I get a question I have added?

E-mail me at aes-js@ricmoo.com with any questions, suggestions, comments, et cetera.

Donations

Obviously, it's all licensed under the MIT license, so use it as you wish; but if you'd like to buy me a coffee, I won't complain. =)

  • Bitcoin - 1K1Ax9t6uJmjE4X5xcoVuyVTsiLrYRqe2P
  • Ethereum - 0x70bDC274028F3f391E398dF8e3977De64FEcBf04

NPM DownloadsLast 30 Days