Skip to content

Getting started ​

encrypt-rsa provides an asynchronous NodeRSA class for Node.js and browsers. The core package has no runtime dependencies and uses the cryptography provided by each platform.

Install and import ​

bash
npm install encrypt-rsa
ts
import NodeRSA, { isValidRSAPublicKey } from 'encrypt-rsa';
js
const { default: NodeRSA, isValidRSAPublicKey } = require('encrypt-rsa');

Conditional exports select native Node crypto in Node and Web Crypto in browser bundles. Node 22 and 24 are the CI targets. Browser cryptography requires HTTPS or localhost, Web Crypto, TextEncoder, TextDecoder, atob, and btoa.

Generate keys ​

ts
const rsa = new NodeRSA();
const { publicKey, privateKey } = await rsa.createPrivateAndPublicKeys(2048);

Public keys are PEM/SPKI (BEGIN PUBLIC KEY); private keys are PEM/PKCS#8 (BEGIN PRIVATE KEY). Either runtime can use keys generated by the other. Store the private key securely; distribute the public key through a trusted channel.

Constructor keys become defaults for subsequent calls:

ts
const rsaWithKeys = new NodeRSA(publicKey, privateKey);

Generating keys returns a pair; it does not update the instance. A key supplied to an operation overrides its constructor default.

Encrypt JSON ​

ts
const encrypted = await rsa.encryptJSON({
  value: { note: 'Hello, العربية 😀' },
  publicKey,
});

const note = await rsa.decryptJSON({
  text: encrypted,
  privateKey,
  parse: (value) => {
    if (!value || typeof value !== 'object' || Array.isArray(value)
        || typeof value.note !== 'string') {
      throw new Error('Invalid note');
    }
    return { note: value.note };
  },
});

The schema parser infers the result type and rejects invalid application data. Without it, decryptJSON returns JsonValue. JSON encryption uses AES-256-GCM and RSA-OAEP/SHA-256 in the authenticated v1 format. Defaults limit JSON to 1 MiB, encoded input to 2 MiB, and nesting to 128 levels. See JSON limits and supported values.

Choose an operation ​

GoalMethodsGuide
Short UTF-8 textencryptStringWithRsaPublicKey / decryptStringWithRsaPrivateKeyDirect RSA
Text beyond RSA capacityencryptLarge / decryptLargeHybrid encryption
Structured dataencryptJSON / decryptJSONJSON and AI integrations
A small binary valueencryptBufferWithRsaPublicKey / decryptBufferWithRsaPrivateKeyBinary methods
Authenticate exact textsign / verifyRSA-PSS signatures
Authenticate scoped, expiring messagessignMessage / verifyMessageSigned messages

Encrypt larger text ​

ts
const encrypted = await rsa.encryptLarge({
  text: 'Long text'.repeat(1000),
  publicKey,
  oaepHash: 'sha256',
});
const decrypted = await rsa.decryptLarge({ text: encrypted, privateKey });

Data is processed in memory; this is not a streaming file API. Direct RSA capacity depends on the UTF-8 byte length: a 2048-bit key accepts 190 bytes with SHA-256 or 214 bytes with SHA-1.

Existing ciphertext

Direct RSA and encryptLarge retain SHA-1 compatibility defaults. SHA-256 hybrid output selects v1 automatically. Upgrade all readers before enabling v1 writers; older versions cannot read it. Direct RSA ciphertext has no algorithm header, so encryptors and decryptors must explicitly agree on the same hash.

Browser without a bundler ​

The package contains a browser ESM build at build/web/index.mjs and a standalone global bundle at build/web/encrypt-rsa.global.js:

html
<script src="https://cdn.jsdelivr.net/npm/encrypt-rsa@6.1.0/build/web/encrypt-rsa.global.js"></script>
<script>
  const rsa = new encryptRSA.NodeRSA();
  // Call the same async class methods shown above.
</script>

Pin the package version when using a CDN. The browser example demonstrates key generation, hybrid encryption, and signatures.

Handle failures ​

Every class method returns a Promise, including failure paths. Handle rejected Promises for missing/invalid keys, oversized input, unsupported values, and authentication failures. verify resolves false for an invalid signature; verifyMessage rejects invalid, expired, or replayed messages. Node-only legacy private-key operations reject in browsers.

Continue with the API reference, runtime compatibility, or runnable examples.

Released under the MIT License.