API Reference

Complete reference for all JSEncrypt methods and properties.

Table of contents

  1. Constructor
    1. new JSEncrypt(options?)
      1. Parameters
      2. Example
  2. Key Management
    1. setKey(key)
      1. Parameters
      2. Example
    2. setPrivateKey(key)
      1. Parameters
      2. Returns
      3. Example
    3. setPublicKey(key)
      1. Parameters
      2. Returns
      3. Example
    4. getPrivateKey()
      1. Returns
      2. Example
    5. getPublicKey()
      1. Returns
      2. Example
    6. getKey(callback?)
      1. Parameters
      2. Returns
      3. Example
  3. Encryption/Decryption
    1. encrypt(text)
      1. Parameters
      2. Returns
      3. Example
      4. Notes
    2. decrypt(text)
      1. Parameters
      2. Returns
      3. Example
      4. Notes
  4. Signing/Verification
    1. sign(text, digestMethod, digestEncoding)
      1. Parameters
      2. Returns
      3. Example
    2. verify(text, signature, digestMethod)
      1. Parameters
      2. Returns
      3. Example
  5. Utility Methods
    1. getKeySize()
      1. Returns
      2. Example
    2. getMaxMessageSize()
      1. Returns
      2. Example
  6. Error Handling
    1. Best Practices
  7. Type Definitions

Constructor

new JSEncrypt(options?)

Creates a new JSEncrypt instance.

Parameters

ParameterTypeDefaultDescription
optionsObject{}Configuration options
options.default_key_sizenumber1024Default key size for key generation

Example

// Default constructor
const crypt = new JSEncrypt();

// With custom key size
const crypt = new JSEncrypt({ default_key_size: 2048 });

Key Management

setKey(key)

Alias

Sets either a private or public key. This is an alias for both setPrivateKey() and setPublicKey().

Parameters

ParameterTypeDescription
keystringPEM-formatted RSA key

Example

// Can be used with either key type
crypt.setKey(privateKeyPem);
crypt.setKey(publicKeyPem);

setPrivateKey(key)

Sets the private key for decryption operations.

Parameters

ParameterTypeDescription
keystringPEM-formatted RSA private key

Returns

void

Example

const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEjWT9u
...
-----END RSA PRIVATE KEY-----`;

crypt.setPrivateKey(privateKey);

setPublicKey(key)

Sets the public key for encryption operations.

Parameters

ParameterTypeDescription
keystringPEM-formatted RSA public key

Returns

void

Example

const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem
...
-----END PUBLIC KEY-----`;

crypt.setPublicKey(publicKey);

getPrivateKey()

Returns the current private key in PEM format.

Returns

string - PEM-formatted private key

Example

const privateKey = crypt.getPrivateKey();
console.log(privateKey);

getPublicKey()

Returns the current public key in PEM format. If only a private key is set, this will derive and return the corresponding public key.

Returns

string - PEM-formatted public key

Example

// After setting a private key
crypt.setPrivateKey(privateKey);
const publicKey = crypt.getPublicKey(); // Derived from private key

getKey(callback?)

Generates a new RSA key pair.

Parameters

ParameterTypeDescription
callbackfunctionOptional callback for async generation

Returns

  • If callback provided: void (result passed to callback)
  • If no callback: Object with key property

Example

// Synchronous generation
const result = crypt.getKey();
console.log('Generated key');

// Asynchronous generation
crypt.getKey(() => {
  console.log('Key generated asynchronously');
  const privateKey = crypt.getPrivateKey();
  const publicKey = crypt.getPublicKey();
});

Encryption/Decryption

encrypt(text)

Encrypts the given text using the current public key.

Parameters

ParameterTypeDescription
textstringText to encrypt

Returns

string | false - Base64-encoded encrypted text, or false if encryption fails

Example

crypt.setPublicKey(publicKey);
const encrypted = crypt.encrypt('Hello, World!');

if (encrypted) {
  console.log('Encrypted:', encrypted);
} else {
  console.log('Encryption failed');
}

Notes

  • Requires a public key to be set
  • Input length is limited by key size (see Key Size Limitations)
  • Returns false if no key is set or encryption fails

decrypt(text)

Decrypts the given encrypted text using the current private key.

Parameters

ParameterTypeDescription
textstringBase64-encoded encrypted text

Returns

string | false - Decrypted text, or false if decryption fails

Example

crypt.setPrivateKey(privateKey);
const decrypted = crypt.decrypt(encryptedText);

if (decrypted) {
  console.log('Decrypted:', decrypted);
} else {
  console.log('Decryption failed');
}

Notes

  • Requires a private key to be set
  • Returns false if no key is set, wrong key is used, or decryption fails

Signing/Verification

sign(text, digestMethod, digestEncoding)

Signs the given text using the private key.

Parameters

ParameterTypeDefaultDescription
textstring-Text to sign
digestMethodstring'sha256'Hash algorithm
digestEncodingstring'base64'Encoding for the signature

Returns

string | false - Signature, or false if signing fails

Example

crypt.setPrivateKey(privateKey);
const signature = crypt.sign('message to sign');
console.log('Signature:', signature);

verify(text, signature, digestMethod)

Verifies a signature using the public key.

Parameters

ParameterTypeDefaultDescription
textstring-Original text
signaturestring-Signature to verify
digestMethodstring'sha256'Hash algorithm

Returns

boolean - true if signature is valid, false otherwise

Example

crypt.setPublicKey(publicKey);
const isValid = crypt.verify('message to sign', signature);
console.log('Signature valid:', isValid);

Utility Methods

getKeySize()

Returns the size of the current key in bits.

Returns

number - Key size in bits

Example

crypt.setPrivateKey(privateKey);
const keySize = crypt.getKeySize();
console.log('Key size:', keySize, 'bits');

getMaxMessageSize()

Returns the maximum message size that can be encrypted with the current key.

Returns

number - Maximum message size in bytes

Example

crypt.setPublicKey(publicKey);
const maxSize = crypt.getMaxMessageSize();
console.log('Max message size:', maxSize, 'bytes');

Error Handling

All methods return false when they fail. Common failure scenarios:

  • No key set: Attempting encryption/decryption without setting appropriate keys
  • Invalid key format: Malformed PEM keys
  • Message too long: Exceeding key size limitations
  • Wrong key: Using incorrect key for decryption
  • Corruption: Tampered encrypted data

Best Practices

Always check return values:

const encrypted = crypt.encrypt(message);
if (!encrypted) {
  throw new Error('Encryption failed');
}

const decrypted = crypt.decrypt(encrypted);
if (!decrypted) {
  throw new Error('Decryption failed');
}

Type Definitions

For TypeScript users, JSEncrypt includes type definitions:

interface JSEncryptOptions {
  default_key_size?: number;
}

declare class JSEncrypt {
  constructor(options?: JSEncryptOptions);
  
  setKey(key: string): void;
  setPrivateKey(key: string): void;
  setPublicKey(key: string): void;
  getPrivateKey(): string;
  getPublicKey(): string;
  getKey(callback?: () => void): any;
  
  encrypt(text: string): string | false;
  decrypt(text: string): string | false;
  
  sign(text: string, digestMethod?: string, digestEncoding?: string): string | false;
  verify(text: string, signature: string, digestMethod?: string): boolean;
  
  getKeySize(): number;
  getMaxMessageSize(): number;
}