aescryptor-ts
v1.0.0
Published
Zero-dependency, production-ready AES-256-GCM encryption and decryption library for Web Browsers, Node.js, and TypeScript.
Maintainers
Readme
aescryptor-ts
A lightweight, zero-dependency, production-ready AES-256-GCM encryption & decryption library for modern web applications and Node.js.
aescryptor-ts brings Android-like (AESCryptorLib) intuitive encryption semantics to JavaScript and TypeScript. Built natively on the Web Crypto API (crypto.subtle), it offers standard high-level cryptographic primitives without external dependencies or heavy bundle bloat.
Features
- Zero External Dependencies: Built entirely on standard, native Web Crypto API (
crypto.subtle). - AES-256-GCM Encryption: Authenticated encryption providing confidentiality and tamper detection via 128-bit authentication tags.
- PBKDF2 Key Derivation: Automatically derives 256-bit encryption keys from arbitrary password strings using PBKDF2 (100,000+ iterations, SHA-256).
- Secure Random IVs & Salts: Generates cryptographic random 96-bit IVs and 128-bit salts per encryption operation.
- Framework Agnostic: Works out of the box with Vanilla JS, TypeScript, React, Vue, Angular, Svelte, Next.js, Nuxt, Vite, and Node.js (v15+).
- Strict TypeScript First: Exports full
.d.tsdeclaration maps and enforces strict type safety (strict: true). - Compact Portable Payloads: Serializes encrypted payloads into compact versioned strings (
$aescryptor$v1$...) supporting Base64 or Hex encodings. - Comprehensive Error Handling: Custom error hierarchy for instant diagnostic clarity.
Installation
npm install aescryptor-tsOr using Yarn / pnpm:
yarn add aescryptor-ts
pnpm add aescryptor-tsQuick Start
import { AESCryptor } from 'aescryptor-ts';
const secretKey = 'MySuperSecretPassword!';
const plainText = 'Sensitive user credit card or token';
// Encrypt
const encryptedPayload = await AESCryptor.encrypt(plainText, secretKey);
console.log('Encrypted:', encryptedPayload);
// Outputs: "$aescryptor$v1$base64Salt$base64Iv$base64Ciphertext"
// Decrypt
const originalText = await AESCryptor.decrypt(encryptedPayload, secretKey);
console.log('Decrypted:', originalText);
// Outputs: "Sensitive user credit card or token"API Reference
AESCryptor.encrypt(data, secretKey, options?)
Encrypts text, byte arrays, or objects into an authenticated AES-256-GCM payload string.
- Parameters:
data(string | Uint8Array | Record<string, unknown>): The plain data to encrypt.secretKey(string): The password or secret key string.options(EncryptionOptions, optional):format('base64' | 'hex', default:'base64'): Output encoding format.iterations(number, default:100000): PBKDF2 iteration count.saltLength(number, default:16): Salt size in bytes.ivLength(number, default:12): IV size in bytes (AES-GCM standard is 12 bytes / 96 bits).
- Returns:
Promise<string>— The formatted payload string ($aescryptor$v1$...). - Exceptions:
InvalidKeyError: IfsecretKeyis empty or not a string.EncryptionError: If encryption fails.
const payload = await AESCryptor.encrypt('Hello World', 'Key123', { format: 'hex' });AESCryptor.decrypt(encryptedPayload, secretKey, options?)
Decrypts an encrypted payload string back into a plain text UTF-8 string.
- Parameters:
encryptedPayload(string): The formatted payload string.secretKey(string): The secret key used during encryption.options(DecryptionOptions, optional):iterations(number, default:100000): Expected PBKDF2 iterations.
- Returns:
Promise<string>— Decrypted UTF-8 string. - Exceptions:
InvalidKeyError: IfsecretKeyis missing.InvalidPayloadError: If payload format is malformed.DecryptionError: If password is wrong or ciphertext has been tampered with.
const decryptedText = await AESCryptor.decrypt(payload, 'Key123');AESCryptor.encryptJSON(data, secretKey, options?)
Convenience helper for serializing and encrypting JavaScript objects/arrays.
- Parameters:
data: T,secretKey: string,options?: EncryptionOptions - Returns:
Promise<string> - Exceptions:
InvalidKeyError,EncryptionError
const payload = await AESCryptor.encryptJSON({ userId: 42, role: 'admin' }, 'Key123');AESCryptor.decryptJSON(encryptedPayload, secretKey, options?)
Decrypts payload and parses result as a typed JSON object.
- Parameters:
encryptedPayload: string,secretKey: string,options?: DecryptionOptions - Returns:
Promise<T> - Exceptions:
InvalidKeyError,InvalidPayloadError,DecryptionError
interface UserProfile { userId: number; role: string }
const user = await AESCryptor.decryptJSON<UserProfile>(payload, 'Key123');AESCryptor.generateKey(lengthInBits?)
Generates a cryptographically random hex string suitable for secret key storage.
- Parameters:
lengthInBits(128 | 192 | 256, default:256) - Returns:
string(Hex string)
const randomKey = AESCryptor.generateKey(256);new AESCryptor(secretKey?, config?)
Creates an instance of AESCryptor bound to a default secret key or configuration.
const cryptor = new AESCryptor('DefaultPassword123');
const cipher = await cryptor.encrypt('Data');
const plain = await cryptor.decrypt(cipher);Browser Usage
In standard modern browsers (Chrome, Firefox, Safari, Edge), AESCryptor works natively via standard ES Modules or bundlers (Vite, Webpack, Parcel):
<script type="module">
import { AESCryptor } from './node_modules/aescryptor-ts/dist/index.mjs';
const encrypted = await AESCryptor.encrypt('Browser secret', 'Key123');
console.log(encrypted);
</script>React Usage
Securely encrypt state or LocalStorage data inside React components:
import React, { useState } from 'react';
import { AESCryptor } from 'aescryptor-ts';
export const SecureComponent = () => {
const [text, setText] = useState('');
const [cipher, setCipher] = useState('');
const onSave = async () => {
const encrypted = await AESCryptor.encrypt(text, 'UserSecretKey');
localStorage.setItem('secure_data', encrypted);
setCipher(encrypted);
};
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={onSave}>Encrypt & Store</button>
</div>
);
};Vue Usage
Using Vue 3 Composition API:
<script setup lang="ts">
import { ref } from 'vue';
import { AESCryptor } from 'aescryptor-ts';
const message = ref('Vue Private Note');
const encryptedResult = ref('');
async function encryptNote() {
encryptedResult.value = await AESCryptor.encrypt(message.value, 'VueMasterKey');
}
</script>Angular Usage
Encapsulate aescryptor-ts inside an Angular Service:
import { Injectable } from '@angular/core';
import { AESCryptor } from 'aescryptor-ts';
@Injectable({ providedIn: 'root' })
export class SecurityService {
private key = 'AngularSecretKey';
async encryptPayload(data: unknown): Promise<string> {
return AESCryptor.encryptJSON(data, this.key);
}
async decryptPayload<T>(payload: string): Promise<T> {
return AESCryptor.decryptJSON<T>(payload, this.key);
}
}Node.js Usage
Supported in Node.js >= 15.0.0 (where Web Crypto API is standard):
// ESM
import { AESCryptor } from 'aescryptor-ts';
// CommonJS
const { AESCryptor } = require('aescryptor-ts');
async function run() {
const payload = await AESCryptor.encrypt('Node Server Secret', 'NodeKey123');
const plain = await AESCryptor.decrypt(payload, 'NodeKey123');
console.log('Decrypted in Node:', plain);
}
run();TypeScript Support
Written strictly in TypeScript. Exported types include:
EncodingFormatEncryptionOptionsDecryptionOptionsAESCryptorConfigEncryptedPayloadComponents- Custom error types (
AESCryptorError,InvalidKeyError,InvalidPayloadError,EncryptionError,DecryptionError)
Compatibility
| Environment | Supported Version |
| :--- | :--- |
| Modern Browsers | Chrome 37+, Firefox 34+, Safari 11+, Edge 79+ |
| Node.js | >= 15.0.0 (Native globalThis.crypto.subtle) |
| TypeScript | >= 4.5.0 |
| Bundlers | Vite, Webpack, Rollup, esbuild, Next.js, Nuxt |
Performance & Benchmarks
- Zero Dependency Overhead:
0 KBexternal dependency weight. Minified & gzipped bundle size is < 2.5 KB. - Hardware Accelerated: Uses browser/OS native C++ crypto backends (OpenSSL / BoringSSL / OS Keychain primitives) via
crypto.subtle. - Async Execution: Non-blocking asynchronous execution over Event Loop.
Security Model
- AES-GCM (Galois/Counter Mode): Provides confidentiality and authenticity. Any modification of ciphertext or salt/IV triggers authentication tag validation failure, raising
DecryptionError. - PBKDF2 SHA-256: Key derivation stretches user passwords against brute-force attacks using 100,000 iterations by default.
- No Insecure Cryptography: Built purely on standard W3C Web Cryptography specifications.
License
MIT License © 2026
