A Javascript library to perform OpenSSL RSA Encryption, Decryption, and Key Generation.
npx @tessl/cli install tessl/npm-jsencrypt@3.5.0JSEncrypt is a tiny (18.5kB gzipped), zero-dependency JavaScript library to perform both synchronous and asynchronous OpenSSL RSA Encryption, Decryption, and Key Generation in both the Browser and Node.js. Built on Tom Wu's proven jsbn cryptographic foundation, it provides enterprise-grade RSA encryption capabilities without the complexity and security concerns that come with heavy dependencies.
npm install jsencryptimport { JSEncrypt } from "jsencrypt";For advanced usage with direct key management:
import { JSEncrypt, JSEncryptRSAKey } from "jsencrypt";For default import:
import JSEncrypt from "jsencrypt";For CommonJS:
const JSEncrypt = require("jsencrypt");For browser global:
<script src="https://cdn.jsdelivr.net/npm/jsencrypt/bin/jsencrypt.min.js"></script>
<script>
const crypt = new JSEncrypt();
</script>import { JSEncrypt } from "jsencrypt";
// Create JSEncrypt instance
const crypt = new JSEncrypt();
// Generate a new key pair (or set existing keys)
const privateKey = crypt.getPrivateKey();
const publicKey = crypt.getPublicKey();
// Encrypt data with public key
const originalText = "Hello, World!";
const encrypted = crypt.encrypt(originalText);
// Decrypt data with private key
const decrypted = crypt.decrypt(encrypted);
console.log("Original:", originalText);
console.log("Decrypted:", decrypted);
console.log("Match:", originalText === decrypted); // trueJSEncrypt is built around several key components:
The main class providing RSA encryption, decryption, key generation, and digital signature functionality.
/**
* Main JSEncrypt class for RSA operations
* @param options - Configuration options for the JSEncrypt instance
*/
declare class JSEncrypt {
constructor(options?: IJSEncryptOptions);
/** Library version string */
static version: string;
/** Sets RSA key (public or private) from PEM string */
setKey(key?: string): void;
/** Sets private key (proxy for setKey) */
setPrivateKey(privkey: string): void;
/** Sets public key (proxy for setKey) */
setPublicKey(pubkey: string): void;
/** Gets current key object, optionally with async callback */
getKey(cb?: () => void): JSEncryptRSAKey;
/** Returns PEM private key with headers */
getPrivateKey(): string;
/** Returns base64 private key without headers */
getPrivateKeyB64(): string;
/** Returns PEM public key with headers */
getPublicKey(): string;
/** Returns base64 public key without headers */
getPublicKeyB64(): string;
/** Encrypts string using public key, returns base64 or false on failure */
encrypt(str: string): string | false;
/** Decrypts base64 string using private key, returns plaintext or false on failure */
decrypt(str: string): string | false;
/** Encrypts with OAEP padding and SHA-256 hash */
encryptOAEP(str: string): string | false;
/** Signs string with custom hash algorithm */
sign(str: string, digestMethod?: (str: string) => string, digestName?: string): string | false;
/** Signs string using SHA-256 hash algorithm */
signSha256(str: string): string | false;
/** Verifies signature with custom hash algorithm */
verify(str: string, signature: string, digestMethod?: (str: string) => string): boolean;
/** Verifies SHA-256 signature */
verifySha256(str: string, signature: string): boolean;
}
interface IJSEncryptOptions {
/** Pre-initialized key object */
key?: JSEncryptRSAKey;
/** Key size in bits as string, parsed to number internally (default: "1024") */
default_key_size?: string;
/** Public exponent in hex (default: "010001") */
default_public_exponent?: string;
/** Enable logging (default: false) */
log?: boolean;
}Key Management Examples:
// Generate new keys with different sizes
const crypt512 = new JSEncrypt({ default_key_size: "512" }); // Fast but less secure
const crypt1024 = new JSEncrypt({ default_key_size: "1024" }); // Default
const crypt2048 = new JSEncrypt({ default_key_size: "2048" }); // Recommended for production
const crypt4096 = new JSEncrypt({ default_key_size: "4096" }); // High security
// Set existing OpenSSL keys
const crypt = new JSEncrypt();
crypt.setPrivateKey(`-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEjWT9u...
-----END RSA PRIVATE KEY-----`);
// Or set public key only for encryption
crypt.setPublicKey(`-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem...
-----END PUBLIC KEY-----`);Asynchronous Key Generation:
// Generate keys asynchronously for better performance
const crypt = new JSEncrypt({ default_key_size: "2048" });
crypt.getKey(() => {
const privateKey = crypt.getPrivateKey();
const publicKey = crypt.getPublicKey();
console.log("Private key generated:", privateKey.length);
console.log("Public key generated:", publicKey.length);
// Now ready for encryption/decryption
const encrypted = crypt.encrypt("Hello, World!");
const decrypted = crypt.decrypt(encrypted);
});Digital Signatures:
const crypt = new JSEncrypt();
crypt.setPrivateKey(privateKey);
// Sign data with SHA-256
const data = "Important message";
const signature = crypt.signSha256(data);
// Verify signature
const verifyCrypt = new JSEncrypt();
verifyCrypt.setPublicKey(publicKey);
const isValid = verifyCrypt.verifySha256(data, signature);
console.log("Signature valid:", isValid);OAEP Padding:
const crypt = new JSEncrypt();
crypt.setPublicKey(publicKey);
// Encrypt with OAEP padding and SHA-256 hash
const encrypted = crypt.encryptOAEP("Secure message");The JSEncryptRSAKey class provides direct access to RSA key operations and advanced key management functionality. It can be imported and used independently for fine-grained control over key handling.
/**
* Direct RSA key management class with PEM parsing and format conversion
* @param key - Optional PEM/DER encoded key string or key parameters object
*/
declare class JSEncryptRSAKey {
constructor(key?: string);
/** Parse PEM or DER encoded RSA key string, returns true on success */
parseKey(pem: string): boolean;
/** Get private key as PEM format with headers */
getPrivateKey(): string;
/** Get public key as PEM format with headers */
getPublicKey(): string;
/** Get private key as base64 without headers */
getPrivateBaseKeyB64(): string;
/** Get public key as base64 without headers */
getPublicBaseKeyB64(): string;
/** Parse RSA parameters from object with n, e, d, p, q, dmp1, dmq1, coeff properties */
parsePropertiesFrom(obj: any): void;
/** Check if object has public key properties (n, e) */
static hasPublicKeyProperty(obj: object): boolean;
/** Check if object has all private key properties */
static hasPrivateKeyProperty(obj: object): boolean;
}Direct Key Usage Examples:
import { JSEncryptRSAKey } from "jsencrypt";
// Create key object from PEM string
const keyObject = new JSEncryptRSAKey(`-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEjWT9u...
-----END RSA PRIVATE KEY-----`);
// Get different key formats
const pemPrivate = keyObject.getPrivateKey(); // PEM with headers
const b64Private = keyObject.getPrivateBaseKeyB64(); // Base64 without headers
const pemPublic = keyObject.getPublicKey(); // PEM with headers
const b64Public = keyObject.getPublicBaseKeyB64(); // Base64 without headers
// Parse key from object parameters
const keyParams = {
n: "some_modulus_hex",
e: 65537,
d: "private_exponent_hex",
p: "prime1_hex",
q: "prime2_hex",
dmp1: "exponent1_hex",
dmq1: "exponent2_hex",
coeff: "coefficient_hex"
};
const keyFromParams = new JSEncryptRSAKey();
keyFromParams.parsePropertiesFrom(keyParams);
// Validate key object structure
if (JSEncryptRSAKey.hasPrivateKeyProperty(keyParams)) {
console.log("Object contains full private key parameters");
}JSEncrypt uses the JSEncryptRSAKey class internally for key operations. You can access the internal key object through JSEncrypt methods:
import { JSEncrypt } from "jsencrypt";
const crypt = new JSEncrypt();
// Access the internal key object (returns JSEncryptRSAKey instance)
const keyObject = crypt.getKey();
// Get different key formats through JSEncrypt methods
const pemPrivate = crypt.getPrivateKey(); // PEM with headers
const b64Private = crypt.getPrivateKeyB64(); // Base64 without headers
const pemPublic = crypt.getPublicKey(); // PEM with headers
const b64Public = crypt.getPublicKeyB64(); // Base64 without headersAll encryption, decryption, and signing methods return false on failure instead of throwing exceptions:
const crypt = new JSEncrypt();
const encrypted = crypt.encrypt("test"); // returns false if no public key set
if (encrypted === false) {
console.error("Encryption failed - check that public key is set");
}
const decrypted = crypt.decrypt("invalid_base64"); // returns false on invalid input
if (decrypted === false) {
console.error("Decryption failed - check input format and private key");
}JSEncrypt works in all modern browsers and supports: