A Javascript library to perform OpenSSL RSA Encryption, Decryption, and Key Generation.
npx @tessl/cli install tessl/npm-jsencrypt@3.5.00
# JSEncrypt
1
2
JSEncrypt 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.
3
4
## Package Information
5
6
- **Package Name**: jsencrypt
7
- **Package Type**: npm
8
- **Language**: JavaScript/TypeScript
9
- **Installation**: `npm install jsencrypt`
10
11
## Core Imports
12
13
```javascript
14
import { JSEncrypt } from "jsencrypt";
15
```
16
17
For advanced usage with direct key management:
18
19
```javascript
20
import { JSEncrypt, JSEncryptRSAKey } from "jsencrypt";
21
```
22
23
For default import:
24
25
```javascript
26
import JSEncrypt from "jsencrypt";
27
```
28
29
For CommonJS:
30
31
```javascript
32
const JSEncrypt = require("jsencrypt");
33
```
34
35
For browser global:
36
37
```html
38
<script src="https://cdn.jsdelivr.net/npm/jsencrypt/bin/jsencrypt.min.js"></script>
39
<script>
40
const crypt = new JSEncrypt();
41
</script>
42
```
43
44
## Basic Usage
45
46
```javascript
47
import { JSEncrypt } from "jsencrypt";
48
49
// Create JSEncrypt instance
50
const crypt = new JSEncrypt();
51
52
// Generate a new key pair (or set existing keys)
53
const privateKey = crypt.getPrivateKey();
54
const publicKey = crypt.getPublicKey();
55
56
// Encrypt data with public key
57
const originalText = "Hello, World!";
58
const encrypted = crypt.encrypt(originalText);
59
60
// Decrypt data with private key
61
const decrypted = crypt.decrypt(encrypted);
62
63
console.log("Original:", originalText);
64
console.log("Decrypted:", decrypted);
65
console.log("Match:", originalText === decrypted); // true
66
```
67
68
## Architecture
69
70
JSEncrypt is built around several key components:
71
72
- **JSEncrypt Class**: Main interface providing RSA operations with automatic key management
73
- **Internal Key System**: JSEncryptRSAKey class handling PEM parsing and key format conversions (not directly exported)
74
- **Configuration System**: Options-based initialization supporting different key sizes and logging
75
- **OpenSSL Compatibility**: Direct support for PEM-formatted keys generated with OpenSSL
76
77
## Capabilities
78
79
### JSEncrypt Class
80
81
The main class providing RSA encryption, decryption, key generation, and digital signature functionality.
82
83
```typescript { .api }
84
/**
85
* Main JSEncrypt class for RSA operations
86
* @param options - Configuration options for the JSEncrypt instance
87
*/
88
declare class JSEncrypt {
89
constructor(options?: IJSEncryptOptions);
90
91
/** Library version string */
92
static version: string;
93
94
/** Sets RSA key (public or private) from PEM string */
95
setKey(key?: string): void;
96
97
/** Sets private key (proxy for setKey) */
98
setPrivateKey(privkey: string): void;
99
100
/** Sets public key (proxy for setKey) */
101
setPublicKey(pubkey: string): void;
102
103
/** Gets current key object, optionally with async callback */
104
getKey(cb?: () => void): JSEncryptRSAKey;
105
106
/** Returns PEM private key with headers */
107
getPrivateKey(): string;
108
109
/** Returns base64 private key without headers */
110
getPrivateKeyB64(): string;
111
112
/** Returns PEM public key with headers */
113
getPublicKey(): string;
114
115
/** Returns base64 public key without headers */
116
getPublicKeyB64(): string;
117
118
/** Encrypts string using public key, returns base64 or false on failure */
119
encrypt(str: string): string | false;
120
121
/** Decrypts base64 string using private key, returns plaintext or false on failure */
122
decrypt(str: string): string | false;
123
124
/** Encrypts with OAEP padding and SHA-256 hash */
125
encryptOAEP(str: string): string | false;
126
127
/** Signs string with custom hash algorithm */
128
sign(str: string, digestMethod?: (str: string) => string, digestName?: string): string | false;
129
130
/** Signs string using SHA-256 hash algorithm */
131
signSha256(str: string): string | false;
132
133
/** Verifies signature with custom hash algorithm */
134
verify(str: string, signature: string, digestMethod?: (str: string) => string): boolean;
135
136
/** Verifies SHA-256 signature */
137
verifySha256(str: string, signature: string): boolean;
138
}
139
140
interface IJSEncryptOptions {
141
/** Pre-initialized key object */
142
key?: JSEncryptRSAKey;
143
/** Key size in bits as string, parsed to number internally (default: "1024") */
144
default_key_size?: string;
145
/** Public exponent in hex (default: "010001") */
146
default_public_exponent?: string;
147
/** Enable logging (default: false) */
148
log?: boolean;
149
}
150
151
```
152
153
**Key Management Examples:**
154
155
```javascript
156
// Generate new keys with different sizes
157
const crypt512 = new JSEncrypt({ default_key_size: "512" }); // Fast but less secure
158
const crypt1024 = new JSEncrypt({ default_key_size: "1024" }); // Default
159
const crypt2048 = new JSEncrypt({ default_key_size: "2048" }); // Recommended for production
160
const crypt4096 = new JSEncrypt({ default_key_size: "4096" }); // High security
161
162
// Set existing OpenSSL keys
163
const crypt = new JSEncrypt();
164
crypt.setPrivateKey(`-----BEGIN RSA PRIVATE KEY-----
165
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEjWT9u...
166
-----END RSA PRIVATE KEY-----`);
167
168
// Or set public key only for encryption
169
crypt.setPublicKey(`-----BEGIN PUBLIC KEY-----
170
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4f5wg5l2hKsTeNem...
171
-----END PUBLIC KEY-----`);
172
```
173
174
**Asynchronous Key Generation:**
175
176
```javascript
177
// Generate keys asynchronously for better performance
178
const crypt = new JSEncrypt({ default_key_size: "2048" });
179
180
crypt.getKey(() => {
181
const privateKey = crypt.getPrivateKey();
182
const publicKey = crypt.getPublicKey();
183
184
console.log("Private key generated:", privateKey.length);
185
console.log("Public key generated:", publicKey.length);
186
187
// Now ready for encryption/decryption
188
const encrypted = crypt.encrypt("Hello, World!");
189
const decrypted = crypt.decrypt(encrypted);
190
});
191
```
192
193
**Digital Signatures:**
194
195
```javascript
196
const crypt = new JSEncrypt();
197
crypt.setPrivateKey(privateKey);
198
199
// Sign data with SHA-256
200
const data = "Important message";
201
const signature = crypt.signSha256(data);
202
203
// Verify signature
204
const verifyCrypt = new JSEncrypt();
205
verifyCrypt.setPublicKey(publicKey);
206
const isValid = verifyCrypt.verifySha256(data, signature);
207
208
console.log("Signature valid:", isValid);
209
```
210
211
**OAEP Padding:**
212
213
```javascript
214
const crypt = new JSEncrypt();
215
crypt.setPublicKey(publicKey);
216
217
// Encrypt with OAEP padding and SHA-256 hash
218
const encrypted = crypt.encryptOAEP("Secure message");
219
```
220
221
### JSEncryptRSAKey Class
222
223
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.
224
225
```typescript { .api }
226
/**
227
* Direct RSA key management class with PEM parsing and format conversion
228
* @param key - Optional PEM/DER encoded key string or key parameters object
229
*/
230
declare class JSEncryptRSAKey {
231
constructor(key?: string);
232
233
/** Parse PEM or DER encoded RSA key string, returns true on success */
234
parseKey(pem: string): boolean;
235
236
/** Get private key as PEM format with headers */
237
getPrivateKey(): string;
238
239
/** Get public key as PEM format with headers */
240
getPublicKey(): string;
241
242
/** Get private key as base64 without headers */
243
getPrivateBaseKeyB64(): string;
244
245
/** Get public key as base64 without headers */
246
getPublicBaseKeyB64(): string;
247
248
/** Parse RSA parameters from object with n, e, d, p, q, dmp1, dmq1, coeff properties */
249
parsePropertiesFrom(obj: any): void;
250
251
/** Check if object has public key properties (n, e) */
252
static hasPublicKeyProperty(obj: object): boolean;
253
254
/** Check if object has all private key properties */
255
static hasPrivateKeyProperty(obj: object): boolean;
256
}
257
```
258
259
**Direct Key Usage Examples:**
260
261
```javascript
262
import { JSEncryptRSAKey } from "jsencrypt";
263
264
// Create key object from PEM string
265
const keyObject = new JSEncryptRSAKey(`-----BEGIN RSA PRIVATE KEY-----
266
MIIEowIBAAKCAQEA4f5wg5l2hKsTeNem/V41fGnJm6gOdrj8ym3rFkEjWT9u...
267
-----END RSA PRIVATE KEY-----`);
268
269
// Get different key formats
270
const pemPrivate = keyObject.getPrivateKey(); // PEM with headers
271
const b64Private = keyObject.getPrivateBaseKeyB64(); // Base64 without headers
272
const pemPublic = keyObject.getPublicKey(); // PEM with headers
273
const b64Public = keyObject.getPublicBaseKeyB64(); // Base64 without headers
274
275
// Parse key from object parameters
276
const keyParams = {
277
n: "some_modulus_hex",
278
e: 65537,
279
d: "private_exponent_hex",
280
p: "prime1_hex",
281
q: "prime2_hex",
282
dmp1: "exponent1_hex",
283
dmq1: "exponent2_hex",
284
coeff: "coefficient_hex"
285
};
286
287
const keyFromParams = new JSEncryptRSAKey();
288
keyFromParams.parsePropertiesFrom(keyParams);
289
290
// Validate key object structure
291
if (JSEncryptRSAKey.hasPrivateKeyProperty(keyParams)) {
292
console.log("Object contains full private key parameters");
293
}
294
```
295
296
### Internal Key Management
297
298
JSEncrypt uses the JSEncryptRSAKey class internally for key operations. You can access the internal key object through JSEncrypt methods:
299
300
```javascript
301
import { JSEncrypt } from "jsencrypt";
302
303
const crypt = new JSEncrypt();
304
305
// Access the internal key object (returns JSEncryptRSAKey instance)
306
const keyObject = crypt.getKey();
307
308
// Get different key formats through JSEncrypt methods
309
const pemPrivate = crypt.getPrivateKey(); // PEM with headers
310
const b64Private = crypt.getPrivateKeyB64(); // Base64 without headers
311
const pemPublic = crypt.getPublicKey(); // PEM with headers
312
const b64Public = crypt.getPublicKeyB64(); // Base64 without headers
313
```
314
315
## Error Handling
316
317
All encryption, decryption, and signing methods return `false` on failure instead of throwing exceptions:
318
319
```javascript
320
const crypt = new JSEncrypt();
321
322
const encrypted = crypt.encrypt("test"); // returns false if no public key set
323
if (encrypted === false) {
324
console.error("Encryption failed - check that public key is set");
325
}
326
327
const decrypted = crypt.decrypt("invalid_base64"); // returns false on invalid input
328
if (decrypted === false) {
329
console.error("Decryption failed - check input format and private key");
330
}
331
```
332
333
## Browser Compatibility
334
335
JSEncrypt works in all modern browsers and supports:
336
337
- Chrome >= 30
338
- Firefox >= 63
339
- Safari >= 11
340
- Edge >= 79
341
- Internet Explorer 11
342
- Node.js (all versions)
343
344
## Security Considerations
345
346
- **Key Generation**: For production applications, prefer OpenSSL-generated keys over JavaScript key generation for better entropy
347
- **Key Sizes**: Use minimum 2048-bit keys for production (default 1024-bit is only suitable for testing)
348
- **Private Key Security**: Never expose private keys in client-side code or logs
349
- **HTTPS**: Always use HTTPS when transmitting encrypted data or public keys