encrypt-rsa 3.3.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +217 -154
  2. package/build/node/node/convertKetToBase64.d.ts +6 -0
  3. package/build/{functions → node/node}/convertKetToBase64.js +2 -7
  4. package/build/node/node/crypto.d.ts +6 -0
  5. package/build/node/node/crypto.js +98 -0
  6. package/build/node/node/index.d.ts +17 -0
  7. package/build/node/node/index.js +61 -0
  8. package/build/node/shared/helpers.d.ts +32 -0
  9. package/build/node/shared/helpers.js +101 -0
  10. package/build/{utils → node/shared}/types.d.ts +13 -0
  11. package/build/web/shared/helpers.d.ts +32 -0
  12. package/build/web/shared/helpers.js +101 -0
  13. package/build/web/shared/types.d.ts +68 -0
  14. package/build/web/shared/types.js +2 -0
  15. package/build/web/web/convertKetToBase64.d.ts +6 -0
  16. package/build/web/web/convertKetToBase64.js +13 -0
  17. package/build/web/web/crypto.d.ts +6 -0
  18. package/build/web/web/crypto.js +165 -0
  19. package/build/web/web/index.d.ts +17 -0
  20. package/build/web/web/index.js +77 -0
  21. package/package.json +24 -8
  22. package/build/functions/convertKetToBase64.d.ts +0 -11
  23. package/build/functions/createPrivateAndPublicKeys.d.ts +0 -17
  24. package/build/functions/createPrivateAndPublicKeys.js +0 -61
  25. package/build/functions/decrypt.d.ts +0 -19
  26. package/build/functions/decrypt.js +0 -53
  27. package/build/functions/decryptStringWithRsaPrivateKey.d.ts +0 -18
  28. package/build/functions/decryptStringWithRsaPrivateKey.js +0 -52
  29. package/build/functions/encrypt.d.ts +0 -19
  30. package/build/functions/encrypt.js +0 -53
  31. package/build/functions/encryptStringWithRsaPublicKey.d.ts +0 -19
  32. package/build/functions/encryptStringWithRsaPublicKey.js +0 -53
  33. package/build/functions/index.d.ts +0 -10
  34. package/build/functions/index.js +0 -35
  35. package/build/index.d.ts +0 -92
  36. package/build/index.js +0 -115
  37. package/build/utils/helpers.d.ts +0 -16
  38. package/build/utils/helpers.js +0 -35
  39. /package/build/{utils → node/shared}/types.js +0 -0
package/README.md CHANGED
@@ -1,237 +1,300 @@
1
1
  # NodeRSA
2
2
 
3
- **NodeRSA** is a library that provides easy-to-use methods for RSA encryption and decryption. It allows generating RSA key pairs, encrypting, and decrypting strings with RSA public and private keys. This library is ideal for secure data transmission, authentication systems, and any application requiring cryptographic security.
3
+ **NodeRSA** is a library that provides easy-to-use methods for RSA encryption and decryption. It supports **Node.js** and **browser** (web) with the same API. Generate RSA key pairs, encrypt and decrypt strings with public and private keys. Ideal for secure data transmission, authentication systems, and any application requiring cryptographic security.
4
4
 
5
5
  ## Installation
6
+
6
7
  ```bash
7
8
  npm install encrypt-rsa
8
- // OR
9
+ # OR
9
10
  yarn add encrypt-rsa
10
11
  ```
11
12
 
13
+ ## Breaking changes (vs 3.x)
14
+
15
+ If you are upgrading from **3.x**, this release includes breaking changes. You should bump to **4.0.0** when publishing:
16
+
17
+ 1. **Async API** – All crypto methods now return **Promises** (sync → async). You must use `await` or `.then()`.
18
+ - **Before (3.x):** `const encrypted = nodeRSA.encryptStringWithRsaPublicKey({ text, publicKey });`
19
+ - **After (4.x):** `const encrypted = await nodeRSA.encryptStringWithRsaPublicKey({ text, publicKey });`
20
+ 2. **Entry points** – The package now has separate Node and Web builds. `main`/`module`/`types` point to the Node build; the `browser` field and conditional `exports` point to the Web build. If you required a specific path (e.g. `encrypt-rsa/build/index.js`), update to the new entry points or use the package root `encrypt-rsa`.
21
+ 3. **Buffer methods** – `decryptBufferWithRsaPrivateKey` now returns `Promise<Uint8Array>` (type). In Node the runtime value is still a `Buffer` (extends `Uint8Array`). Prefer `Uint8Array` in types; avoid relying on `instanceof Buffer` in shared code.
22
+
23
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
24
+
25
+ ## Node and Web (browser)
26
+
27
+ One package, two environments:
28
+
29
+ - **Node.js**: Uses the built-in `crypto` module. All crypto methods return **Promises** (async API).
30
+ - **Browser**: Uses the Web Crypto API. Same async API; bundlers resolve the web build via `exports` / `browser` field.
31
+
32
+ You use the same import; the correct implementation is chosen at build/runtime:
33
+
34
+ ```ts
35
+ import NodeRSA from 'encrypt-rsa';
36
+ ```
37
+
38
+ - In Node (or when your bundler targets Node), you get the Node build.
39
+ - When your bundler targets the browser, you get the web build.
40
+
41
+ **Browser note:** In the browser build, `encrypt(privateKey)` and `decrypt(publicKey)` are not supported (Web Crypto does not support that flow) and will throw. Use `encryptStringWithRsaPublicKey` / `decryptStringWithRsaPrivateKey` for encryption and decryption.
42
+
43
+ ### Same interface (Node and Web)
44
+
45
+ Both the Node and Web builds expose the **same class and method signatures** (they implement the shared `INodeRSA` interface). You write the same code; only the resolved implementation changes:
46
+
47
+ - **Same class:** `NodeRSA`
48
+ - **Same constructor:** `(publicKey?: string, privateKey?: string, modulusLength?: number)`
49
+ - **Same methods:** `encryptStringWithRsaPublicKey`, `decryptStringWithRsaPrivateKey`, `encrypt`, `decrypt`, `createPrivateAndPublicKeys`, `encryptBufferWithRsaPublicKey`, `decryptBufferWithRsaPrivateKey`
50
+ - **Same parameter and return types:** All crypto methods return `Promise<...>`; buffer methods use `Uint8Array` (in Node, `Buffer` extends `Uint8Array` so it works as well).
51
+
52
+ See [docs/FEATURE_PARITY.md](docs/FEATURE_PARITY.md) for a feature-by-feature comparison of Node vs Web (including the browser limitation for `encrypt`/`decrypt` with private/public key).
53
+
12
54
  ## Usage
13
- **Importing the Library**
55
+
56
+ ### Example: Node.js
14
57
 
15
58
  ```ts
59
+ // Node (CommonJS or ESM)
16
60
  import NodeRSA from 'encrypt-rsa';
61
+
62
+ const nodeRSA = new NodeRSA();
63
+ const { publicKey, privateKey } = await nodeRSA.createPrivateAndPublicKeys(2048);
64
+
65
+ const encrypted = await nodeRSA.encryptStringWithRsaPublicKey({
66
+ text: 'Secret message',
67
+ publicKey,
68
+ });
69
+ console.log('Encrypted:', encrypted);
70
+
71
+ const decrypted = await nodeRSA.decryptStringWithRsaPrivateKey({
72
+ text: encrypted,
73
+ privateKey,
74
+ });
75
+ console.log('Decrypted:', decrypted);
76
+ ```
77
+
78
+ ### Example: Browser (Web)
79
+
80
+ ```ts
81
+ // Browser (ESM or bundled) – same API
82
+ import NodeRSA from 'encrypt-rsa';
83
+
84
+ const nodeRSA = new NodeRSA();
85
+ const { publicKey, privateKey } = await nodeRSA.createPrivateAndPublicKeys(2048);
86
+
87
+ const encrypted = await nodeRSA.encryptStringWithRsaPublicKey({
88
+ text: 'Secret message',
89
+ publicKey,
90
+ });
91
+ console.log('Encrypted:', encrypted);
92
+
93
+ const decrypted = await nodeRSA.decryptStringWithRsaPrivateKey({
94
+ text: encrypted,
95
+ privateKey,
96
+ });
97
+ console.log('Decrypted:', decrypted);
17
98
  ```
18
99
 
19
- ## Creating an Instance
100
+ When your bundler targets the browser, it resolves the web build; the code above is unchanged.
20
101
 
21
- You can create an instance of the NodeRSA class with optional public and private keys and modulus length.
102
+ ### Creating an instance
22
103
 
23
104
  ```ts
24
- const nodeRSA = new NodeRSA(publicKey, privateKey, modulusLength);
105
+ const nodeRSA = new NodeRSA(publicKey?, privateKey?, modulusLength?);
25
106
  ```
26
107
 
27
- ## Generating RSA Key Pairs
28
- To generate a new pair of RSA keys:
108
+ ### Generating RSA key pairs
109
+
110
+ All crypto methods return **Promises**. Use `await` or `.then()`:
29
111
 
30
112
  ```ts
31
- const { publicKey, privateKey } = nodeRSA.createPrivateAndPublicKeys(modulusLength);
113
+ const { publicKey, privateKey } = await nodeRSA.createPrivateAndPublicKeys(modulusLength);
32
114
  console.log('Public Key:', publicKey);
33
115
  console.log('Private Key:', privateKey);
34
116
  ```
35
117
 
36
- ## Encrypting and Decrypting Strings
37
- ### Encrypting with RSA Public Key
118
+ ### Encrypting and decrypting strings
119
+
120
+ #### Encrypt with public key, decrypt with private key
121
+
38
122
  ```ts
39
- const text = "Hello, World!";
40
- const encryptedString = nodeRSA.encryptStringWithRsaPublicKey({ text, publicKey });
123
+ const text = 'Hello, World!';
124
+ const encryptedString = await nodeRSA.encryptStringWithRsaPublicKey({ text, publicKey });
41
125
  console.log('Encrypted:', encryptedString);
42
- ```
43
126
 
44
- ### Decrypting with RSA Private Key
45
- ```ts
46
- const decryptedString = nodeRSA.decryptStringWithRsaPrivateKey({ text: encryptedString, privateKey });
127
+ const decryptedString = await nodeRSA.decryptStringWithRsaPrivateKey({
128
+ text: encryptedString,
129
+ privateKey,
130
+ });
47
131
  console.log('Decrypted:', decryptedString);
48
132
  ```
49
133
 
50
- ### Encrypting with RSA Private Key
134
+ #### Encrypt with private key, decrypt with public key (Node only)
135
+
136
+ In the **browser build**, these methods throw. In **Node**, they work:
137
+
51
138
  ```ts
52
- const text = "Hello, World!";
53
- const encryptedString = nodeRSA.encrypt({ text, privateKey });
139
+ const encryptedString = await nodeRSA.encrypt({ text, privateKey });
54
140
  console.log('Encrypted with Private Key:', encryptedString);
141
+
142
+ const decryptedString = await nodeRSA.decrypt({ text: encryptedString, publicKey });
143
+ console.log('Decrypted with Public Key:', decryptedString);
55
144
  ```
56
145
 
57
- ### Decrypting with RSA Public Key
146
+ ### Buffer encryption (same interface: `Uint8Array`)
147
+
148
+ Both Node and Web use **`Uint8Array`** in the method signature. In Node, `Buffer` extends `Uint8Array`, so you can pass a `Buffer` as well. Return type is `Promise<Uint8Array>` in both environments.
149
+
58
150
  ```ts
59
- const decryptedString = nodeRSA.decrypt({ text: encryptedString, publicKey });
60
- console.log('Decrypted with Public Key:', decryptedString);
151
+ // Node
152
+ const buffer = Buffer.from('This is some binary data');
153
+
154
+ // Browser (or shared code)
155
+ const buffer = new TextEncoder().encode('This is some binary data');
156
+
157
+ const encryptedBuffer = await nodeRSA.encryptBufferWithRsaPublicKey(buffer, publicKey);
158
+ const decryptedBuffer = await nodeRSA.decryptBufferWithRsaPrivateKey(
159
+ encryptedBuffer,
160
+ privateKey
161
+ );
162
+
163
+ // Node: decryptedBuffer is Buffer
164
+ // Browser: decryptedBuffer is Uint8Array
165
+ console.log(
166
+ decryptedBuffer instanceof Uint8Array
167
+ ? new TextDecoder().decode(decryptedBuffer)
168
+ : decryptedBuffer.toString()
169
+ );
61
170
  ```
62
171
 
63
172
  ## API
64
- ### NodeRSA Class
65
173
 
66
- ### Constructor
174
+ ### NodeRSA class
175
+
176
+ #### Constructor
177
+
67
178
  ```ts
68
179
  constructor(publicKey?: string, privateKey?: string, modulusLength?: number)
69
180
  ```
70
- - `publicKey`: Optional. The RSA public key.
71
- - `privateKey`: Optional. The RSA private key.
72
- - `modulusLength`: Optional. The modulus length for the RSA key pair (default is 2048).
73
-
74
- ### Methods
75
- 1. `createPrivateAndPublicKeys(modulusLength: number = this.modulusLength): returnCreateKeys`
76
- - Generates a new pair of RSA keys.
77
- - `modulusLength`: Optional. The modulus length for the RSA key pair (default is the instance's modulus length).
78
- - Returns an object containing the `publicKey` and `privateKey`.
79
- 2. `encryptStringWithRsaPublicKey(args: parametersOfEncrypt): string`
80
- - Encrypts a string with the given RSA public key.
81
- - `args`: Object containing `text` and optionally `publicKey`.
82
- - Returns the encrypted string in base64 format.
83
-
84
- 3. `decryptStringWithRsaPrivateKey(args: parametersOfDecrypt): string`
85
- - Decrypts a string with the given RSA private key.
86
- - `args`: Object containing `text` and optionally `privateKey`.
87
- - Returns the decrypted string.
88
-
89
- 4. `encrypt(args: parametersOfEncryptPrivate): string`
90
- - Encrypts a string with the given RSA private key.
91
- - `args`: Object containing `text` and optionally `privateKey`.
92
- - Returns the encrypted string in base64 format.
93
- -
94
- 5. `decrypt(args: parametersOfDecryptPublic): string`
95
- - Decrypts a string with the given RSA public key.
96
- - `args`: Object containing `text` and optionally `publicKey`.
97
- - Returns the decrypted string.
98
-
99
- ### Types
100
- 1. parametersOfEncrypt
101
- ```ts
102
- {
103
- text: string;
104
- publicKey?: string;
105
- }
106
- ```
107
- 2. parametersOfDecrypt
108
- ```ts
109
- {
110
- text: string;
111
- privateKey?: string;
112
- }
113
- ```
114
- 3. parametersOfEncryptPrivate
115
- ```ts
116
- {
117
- text: string;
118
- privateKey?: string;
119
- }
120
- ```
121
- 4. parametersOfDecryptPublic
122
- ```ts
123
- {
124
- text: string;
125
- publicKey?: string;
126
- }
127
- ```
128
- 5. returnCreateKeys
129
- ```ts
130
- {
131
- publicKey: string;
132
- privateKey: string;
133
- }
134
- ```
135
181
 
136
- ### Utilities
137
- 1. `convertKetToBase64(key: string): string`
138
- Converts a given key to base64 format.
182
+ - `publicKey`: Optional. RSA public key (PEM).
183
+ - `privateKey`: Optional. RSA private key (PEM).
184
+ - `modulusLength`: Optional. Modulus length in bits (default 2048).
139
185
 
140
- ### Helper Functions
141
- 1. `encode`
142
- Encodes a string to base64.
186
+ #### Methods (all crypto methods return `Promise<...>`)
143
187
 
144
- 2. `decode`
145
- Decodes a base64 string.
188
+ | Method | Returns | Description |
189
+ |--------|---------|-------------|
190
+ | `createPrivateAndPublicKeys(modulusLength?)` | `Promise<{ publicKey, privateKey }>` | Generate RSA key pair (PEM). |
191
+ | `encryptStringWithRsaPublicKey(args)` | `Promise<string>` | Encrypt with public key. |
192
+ | `decryptStringWithRsaPrivateKey(args)` | `Promise<string>` | Decrypt with private key. |
193
+ | `encrypt(args)` | `Promise<string>` | Encrypt with private key. **Node only.** |
194
+ | `decrypt(args)` | `Promise<string>` | Decrypt with public key. **Node only.** |
195
+ | `encryptBufferWithRsaPublicKey(buffer, publicKey?)` | `Promise<string>` | Encrypt buffer; returns base64 string. |
196
+ | `decryptBufferWithRsaPrivateKey(encryptedText, privateKey?)` | `Promise<Uint8Array>` | Decrypt to buffer (same type in Node and Web). |
146
197
 
147
- ### Use Cases
198
+ #### Parameter types
148
199
 
149
- #### Secure Data Transmission
200
+ - `parametersOfEncrypt`: `{ text: string; publicKey?: string }`
201
+ - `parametersOfDecrypt`: `{ text: string; privateKey?: string }`
202
+ - `parametersOfEncryptPrivate`: `{ text: string; privateKey?: string }`
203
+ - `parametersOfDecryptPublic`: `{ text: string; publicKey?: string }`
204
+ - `returnCreateKeys`: `{ publicKey: string; privateKey: string }`
150
205
 
151
- NodeRSA can be used to securely transmit sensitive data over insecure channels. Encrypt data with the recipient's public key before sending it. Only the recipient can decrypt the data with their private key.
206
+ ### Algorithm and key format
152
207
 
208
+ - **RSA-OAEP** with **SHA-1** for encrypt/decrypt with public/private key (cross-compatible between Node and browser).
209
+ - Keys are **PEM** (SPKI for public, PKCS#8 for private). Keys generated on one side work on the other.
210
+
211
+ ## Use cases
212
+
213
+ ### Secure data transmission
153
214
 
154
215
  ```ts
155
216
  // Sender
156
- const encryptedMessage = nodeRSA.encryptStringWithRsaPublicKey({ text: "Sensitive data", publicKey: recipientPublicKey });
157
- // Send `encryptedMessage` to the recipient
217
+ const encryptedMessage = await nodeRSA.encryptStringWithRsaPublicKey({
218
+ text: 'Sensitive data',
219
+ publicKey: recipientPublicKey,
220
+ });
221
+ // Send encryptedMessage to the recipient
158
222
 
159
223
  // Recipient
160
- const decryptedMessage = nodeRSA.decryptStringWithRsaPrivateKey({ text: encryptedMessage, privateKey: recipientPrivateKey });
224
+ const decryptedMessage = await nodeRSA.decryptStringWithRsaPrivateKey({
225
+ text: encryptedMessage,
226
+ privateKey: recipientPrivateKey,
227
+ });
161
228
  console.log('Decrypted Message:', decryptedMessage);
162
229
  ```
163
230
 
164
- #### Authentication Systems
165
- NodeRSA can be used in authentication systems to encrypt credentials and sensitive information.
166
-
231
+ ### Authentication
167
232
 
168
233
  ```ts
169
- // Encrypting user credentials
170
- const encryptedCredentials = nodeRSA.encryptStringWithRsaPublicKey({ text: "username:password", publicKey: serverPublicKey });
171
-
172
- // Decrypting credentials on the server
173
- const decryptedCredentials = nodeRSA.decryptStringWithRsaPrivateKey({ text: encryptedCredentials, privateKey: serverPrivateKey });
234
+ const encryptedCredentials = await nodeRSA.encryptStringWithRsaPublicKey({
235
+ text: 'username:password',
236
+ publicKey: serverPublicKey,
237
+ });
238
+
239
+ const decryptedCredentials = await nodeRSA.decryptStringWithRsaPrivateKey({
240
+ text: encryptedCredentials,
241
+ privateKey: serverPrivateKey,
242
+ });
174
243
  console.log('Decrypted Credentials:', decryptedCredentials);
175
244
  ```
176
245
 
177
- ### Buffer Encryption/Decryption Methods:
246
+ ## Testing
178
247
 
179
- 1. `encryptBufferWithRsaPublicKey`: Converts a buffer to Base64 and then encrypts the Base64 string.
180
- 2. `decryptBufferWithRsaPrivateKey`: Decrypts the Base64 string and converts it back to a buffer.
248
+ The project includes tests for both the **Node** and **web** builds:
181
249
 
182
- #### Example Usage
183
- ```ts
184
- const nodeRSA = new NodeRSA();
250
+ - **Node tests** (`tests/functionalty.node.spec.ts`): Run against the Node build; cover all methods including encrypt/decrypt with private/public key and buffer operations.
251
+ - **Web tests** (`tests/functionalty.web.spec.ts`): Run against the web build; require `crypto.subtle` (Node 19+ or a browser). Skipped automatically when Web Crypto is not available.
185
252
 
186
- // Generate keys
187
- const { publicKey, privateKey } = nodeRSA.createPrivateAndPublicKeys();
253
+ ```bash
254
+ npm test
255
+ ```
188
256
 
189
- // Example buffer
190
- const buffer = Buffer.from('This is some binary data');
257
+ Both suites run with `npm test`. Web tests are skipped when `crypto.subtle` is not available (e.g. Node below 19).
258
+
259
+ ## Documentation
191
260
 
192
- // Encrypt the buffer
193
- const encryptedBuffer = nodeRSA.encryptBufferWithRsaPublicKey(buffer, publicKey);
194
- console.log('Encrypted Buffer:', encryptedBuffer);
261
+ API documentation is generated with [Compodoc](https://compodoc.app). To generate the docs (from the Node build source):
195
262
 
196
- // Decrypt back to buffer
197
- const decryptedBuffer = nodeRSA.decryptBufferWithRsaPrivateKey(encryptedBuffer, privateKey);
198
- console.log('Decrypted Buffer:', decryptedBuffer.toString()); // should log: 'This is some binary data'
263
+ ```bash
264
+ npm run docs
265
+ ```
266
+
267
+ Generated files are written to the `docs/` folder. To serve them locally:
268
+
269
+ ```bash
270
+ npm run docs:serve
199
271
  ```
200
272
 
273
+ The docs reflect the **NodeRSA** class and its async API (Node and web share the same interface).
201
274
 
202
- #### Digital Signatures
275
+ ## Releasing
203
276
 
204
- Although not directly covered by the current implementation, RSA can also be used for creating and verifying digital signatures to ensure data integrity and authenticity.
277
+ - **Changelog from commits:** Run `npm run changelog` to update [CHANGELOG.md](./CHANGELOG.md) from conventional commits since the last tag (`feat:`, `fix:`, `BREAKING CHANGE:`, etc.).
278
+ - **Full release:** Run `npm run release -- --release-as major|minor|patch` to bump version, update the changelog, commit, and tag. Push to `master` to trigger the publish workflow (see [.github/workflows/publish.yml](./.github/workflows/publish.yml)).
205
279
 
280
+ **Publish via GitHub Actions (on merge to `master`):**
281
+
282
+ 1. **Secret:** In the repo go to **Settings → Secrets and variables → Actions** and add **NPM_TOKEN** (npm automation token with “Publish” permission).
283
+ 2. **Trigger:** Merging (or pushing) to the **master** branch runs the workflow: install → test → build → publish. The [JS-DevTools/npm-publish](https://github.com/JS-DevTools/npm-publish) action publishes only if the version in `package.json` is **greater** than the latest on npm; otherwise the job succeeds but skips publishing.
284
+ 3. **Optional:** To make installs reproducible in CI, commit `package-lock.json` (remove it from `.gitignore`) and change the workflow step from `npm install` to `npm ci`.
206
285
 
207
286
  ## Contribution
208
- We welcome contributions to the NodeRSA library! If you'd like to contribute, please follow these steps:
209
287
 
210
288
  1. Fork the repository on GitHub.
211
- 2. Clone your forked repository to your local machine.
212
- ```bash
213
- git clone git@github.com:miladezzat/encrypt-rsa.git
214
- ```
215
- 3. Create a new branch for your feature or bugfix.
216
- ```bash
217
- git checkout -b feature/your-feature-name
218
- ```
219
- 4. Make your changes to the codebase.
220
- 5. Commit your changes with a clear and descriptive commit message.
221
- ```bash
222
- git commit -m "Description of your feature or fix"
223
- ```
224
- 6. Push your changes to your forked repository.
225
- ```bash
226
- git push origin feature/your-feature-name
227
- ```
228
- 7. Create a pull request on the original repository. Be sure to include a detailed description of your changes and the problem they solve.
289
+ 2. Clone your fork: `git clone git@github.com:miladezzat/encrypt-rsa.git`
290
+ 3. Create a branch: `git checkout -b feature/your-feature-name`
291
+ 4. Make your changes, then commit with a clear message.
292
+ 5. Push to your fork and open a pull request with a description of your changes.
229
293
 
230
- ## Code of Conduct
231
- Please note that this project is released with a [Contributor Code of Conduct](./CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.
294
+ ## Code of conduct
232
295
 
296
+ This project is released with a [Contributor Code of Conduct](./CODE_OF_CONDUCT.md). By participating you agree to abide by its terms.
233
297
 
234
- ## Reporting Issues
235
- If you encounter any issues, please report them using the GitHub issue tracker. Include details about the problem and your environment (OS, Node.js version, etc.).
298
+ ## Reporting issues
236
299
 
237
- Thank you for contributing to NodeRSA!
300
+ Please report issues via the [GitHub issue tracker](https://github.com/miladezzat/encrypt-rsa/issues). Include details about the problem and your environment (OS, Node.js version, bundler, etc.).
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Converts an RSA key to a base64-encoded string.
3
+ * Removes leading spaces from each line, then base64-encodes.
4
+ */
5
+ export declare function convertKetToBase64(key: string): string;
6
+ export default convertKetToBase64;
@@ -1,15 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.convertKetToBase64 = void 0;
4
- var helpers_1 = require("../utils/helpers");
4
+ var helpers_1 = require("../shared/helpers");
5
5
  /**
6
6
  * Converts an RSA key to a base64-encoded string.
7
- *
8
- * This function removes any leading spaces from each line of the key and then
9
- * encodes it to base64 format.
10
- *
11
- * @param {string} key - The RSA key to be converted to base64. It may contain leading spaces in each line.
12
- * @returns {string} The base64-encoded version of the RSA key.
7
+ * Removes leading spaces from each line, then base64-encodes.
13
8
  */
14
9
  function convertKetToBase64(key) {
15
10
  return (0, helpers_1.encode)(key.replace(/^ +/gm, ''));
@@ -0,0 +1,6 @@
1
+ import type { parametersOfDecrypt, parametersOfDecryptPublic, parametersOfEncrypt, parametersOfEncryptPrivate, returnCreateKeys } from '../shared/types';
2
+ export declare function encryptStringWithRsaPublicKey(args: parametersOfEncrypt): string;
3
+ export declare function decryptStringWithRsaPrivateKey(args: parametersOfDecrypt): string;
4
+ export declare function encryptPrivate(args: parametersOfEncryptPrivate): string;
5
+ export declare function decryptPublic(args: parametersOfDecryptPublic): string;
6
+ export declare function createPrivateAndPublicKeys(modulusLength?: number): returnCreateKeys;
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ var desc = Object.getOwnPropertyDescriptor(m, k);
16
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17
+ desc = { enumerable: true, get: function() { return m[k]; } };
18
+ }
19
+ Object.defineProperty(o, k2, desc);
20
+ }) : (function(o, m, k, k2) {
21
+ if (k2 === undefined) k2 = k;
22
+ o[k2] = m[k];
23
+ }));
24
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
26
+ }) : function(o, v) {
27
+ o["default"] = v;
28
+ });
29
+ var __importStar = (this && this.__importStar) || function (mod) {
30
+ if (mod && mod.__esModule) return mod;
31
+ var result = {};
32
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33
+ __setModuleDefault(result, mod);
34
+ return result;
35
+ };
36
+ Object.defineProperty(exports, "__esModule", { value: true });
37
+ exports.createPrivateAndPublicKeys = exports.decryptPublic = exports.encryptPrivate = exports.decryptStringWithRsaPrivateKey = exports.encryptStringWithRsaPublicKey = void 0;
38
+ /**
39
+ * Node-specific crypto implementation using Node's crypto module and Buffer.
40
+ * Uses RSA-OAEP with SHA-1 for cross-compatibility with Web Crypto.
41
+ */
42
+ var crypto = __importStar(require("crypto"));
43
+ var helpers_1 = require("../shared/helpers");
44
+ var OAEP_OPTIONS = {
45
+ padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
46
+ oaepHash: 'sha1',
47
+ };
48
+ function encryptStringWithRsaPublicKey(args) {
49
+ var text = args.text, publicKey = args.publicKey;
50
+ var publicKeyDecoded = (0, helpers_1.decode)(publicKey);
51
+ var buffer = Buffer.from(text);
52
+ var encrypted = crypto.publicEncrypt(__assign({ key: publicKeyDecoded }, OAEP_OPTIONS), buffer);
53
+ return encrypted.toString('base64');
54
+ }
55
+ exports.encryptStringWithRsaPublicKey = encryptStringWithRsaPublicKey;
56
+ function decryptStringWithRsaPrivateKey(args) {
57
+ var text = args.text, privateKey = args.privateKey;
58
+ var privateKeyDecoded = (0, helpers_1.decode)(privateKey);
59
+ var buffer = Buffer.from(text, 'base64');
60
+ var decrypted = crypto.privateDecrypt(__assign({ key: privateKeyDecoded }, OAEP_OPTIONS), buffer);
61
+ return decrypted.toString('utf8');
62
+ }
63
+ exports.decryptStringWithRsaPrivateKey = decryptStringWithRsaPrivateKey;
64
+ function encryptPrivate(args) {
65
+ var text = args.text, privateKey = args.privateKey;
66
+ var privateKeyDecoded = (0, helpers_1.decode)(privateKey);
67
+ var buffer = Buffer.from(text);
68
+ var encrypted = crypto.privateEncrypt(privateKeyDecoded, buffer);
69
+ return encrypted.toString('base64');
70
+ }
71
+ exports.encryptPrivate = encryptPrivate;
72
+ function decryptPublic(args) {
73
+ var text = args.text, publicKey = args.publicKey;
74
+ var publicKeyDecoded = (0, helpers_1.decode)(publicKey);
75
+ var buffer = Buffer.from(text, 'base64');
76
+ var decrypted = crypto.publicDecrypt(publicKeyDecoded, buffer);
77
+ return decrypted.toString('utf8');
78
+ }
79
+ exports.decryptPublic = decryptPublic;
80
+ function createPrivateAndPublicKeys(modulusLength) {
81
+ if (modulusLength === void 0) { modulusLength = 2048; }
82
+ if (typeof crypto.generateKeyPairSync === 'function') {
83
+ var _a = crypto.generateKeyPairSync('rsa', {
84
+ modulusLength: modulusLength,
85
+ publicKeyEncoding: {
86
+ type: 'spki',
87
+ format: 'pem',
88
+ },
89
+ privateKeyEncoding: {
90
+ type: 'pkcs8',
91
+ format: 'pem',
92
+ },
93
+ }), privateKey = _a.privateKey, publicKey = _a.publicKey;
94
+ return { publicKey: publicKey, privateKey: privateKey };
95
+ }
96
+ return { privateKey: '', publicKey: '' };
97
+ }
98
+ exports.createPrivateAndPublicKeys = createPrivateAndPublicKeys;
@@ -0,0 +1,17 @@
1
+ import type { parametersOfDecrypt, parametersOfDecryptPublic, parametersOfEncrypt, parametersOfEncryptPrivate, returnCreateKeys, INodeRSA } from '../shared/types';
2
+ export type { returnCreateKeys, parametersOfEncrypt, parametersOfDecrypt, parametersOfEncryptPrivate, parametersOfDecryptPublic, INodeRSA, } from '../shared/types';
3
+ declare class NodeRSA implements INodeRSA {
4
+ private publicKey;
5
+ private privateKey;
6
+ private modulusLength;
7
+ private keyBase64;
8
+ constructor(publicKey?: string, privateKey?: string, modulusLength?: number);
9
+ encryptStringWithRsaPublicKey(args: parametersOfEncrypt): Promise<string>;
10
+ decryptStringWithRsaPrivateKey(args: parametersOfDecrypt): Promise<string>;
11
+ encrypt(args: parametersOfEncryptPrivate): Promise<string>;
12
+ decrypt(args: parametersOfDecryptPublic): Promise<string>;
13
+ createPrivateAndPublicKeys(modulusLength?: number): Promise<returnCreateKeys>;
14
+ encryptBufferWithRsaPublicKey(buffer: Uint8Array, publicKey?: string): Promise<string>;
15
+ decryptBufferWithRsaPrivateKey(encryptedText: string, privateKey?: string): Promise<Uint8Array>;
16
+ }
17
+ export default NodeRSA;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Node build: NodeRSA with async API (Option A).
19
+ * Same interface as web build; wraps sync Node crypto in Promise.resolve.
20
+ */
21
+ var convertKetToBase64_1 = __importDefault(require("./convertKetToBase64"));
22
+ var crypto_1 = require("./crypto");
23
+ var NodeRSA = /** @class */ (function () {
24
+ function NodeRSA(publicKey, privateKey, modulusLength) {
25
+ this.keyBase64 = 'base64';
26
+ this.publicKey = publicKey;
27
+ this.privateKey = privateKey;
28
+ this.modulusLength = modulusLength !== null && modulusLength !== void 0 ? modulusLength : 2048;
29
+ }
30
+ NodeRSA.prototype.encryptStringWithRsaPublicKey = function (args) {
31
+ var _a = args.publicKey, publicKey = _a === void 0 ? this.publicKey : _a;
32
+ return Promise.resolve((0, crypto_1.encryptStringWithRsaPublicKey)(__assign(__assign({}, args), { publicKey: (0, convertKetToBase64_1.default)(publicKey) })));
33
+ };
34
+ NodeRSA.prototype.decryptStringWithRsaPrivateKey = function (args) {
35
+ var _a = args.privateKey, privateKey = _a === void 0 ? this.privateKey : _a;
36
+ return Promise.resolve((0, crypto_1.decryptStringWithRsaPrivateKey)(__assign(__assign({}, args), { privateKey: (0, convertKetToBase64_1.default)(privateKey) })));
37
+ };
38
+ NodeRSA.prototype.encrypt = function (args) {
39
+ var _a = args.privateKey, privateKey = _a === void 0 ? this.privateKey : _a;
40
+ return Promise.resolve((0, crypto_1.encryptPrivate)(__assign(__assign({}, args), { privateKey: (0, convertKetToBase64_1.default)(privateKey) })));
41
+ };
42
+ NodeRSA.prototype.decrypt = function (args) {
43
+ var _a = args.publicKey, publicKey = _a === void 0 ? this.publicKey : _a;
44
+ return Promise.resolve((0, crypto_1.decryptPublic)(__assign(__assign({}, args), { publicKey: (0, convertKetToBase64_1.default)(publicKey) })));
45
+ };
46
+ NodeRSA.prototype.createPrivateAndPublicKeys = function (modulusLength) {
47
+ if (modulusLength === void 0) { modulusLength = this.modulusLength; }
48
+ return Promise.resolve((0, crypto_1.createPrivateAndPublicKeys)(modulusLength));
49
+ };
50
+ NodeRSA.prototype.encryptBufferWithRsaPublicKey = function (buffer, publicKey) {
51
+ var buf = Buffer.isBuffer(buffer) ? buffer : Buffer.from(buffer);
52
+ var base64String = buf.toString(this.keyBase64);
53
+ return this.encryptStringWithRsaPublicKey({ text: base64String, publicKey: publicKey });
54
+ };
55
+ NodeRSA.prototype.decryptBufferWithRsaPrivateKey = function (encryptedText, privateKey) {
56
+ var _this = this;
57
+ return this.decryptStringWithRsaPrivateKey({ text: encryptedText, privateKey: privateKey }).then(function (decryptedBase64) { return Buffer.from(decryptedBase64, _this.keyBase64); });
58
+ };
59
+ return NodeRSA;
60
+ }());
61
+ exports.default = NodeRSA;