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
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Shared helpers that work in both Node and browser (no Buffer or Node crypto).
3
+ * Uses atob/btoa (Node 16+ and browser) and TextEncoder/TextDecoder.
4
+ */
5
+ /**
6
+ * Decodes base64 to Uint8Array (environment-agnostic).
7
+ */
8
+ export declare function base64ToBytes(base64: string): Uint8Array;
9
+ /**
10
+ * Converts PEM string to binary (Uint8Array) for Web Crypto importKey.
11
+ */
12
+ export declare function pemToBinary(pem: string): Uint8Array;
13
+ /**
14
+ * Wraps binary in PEM headers (SPKI for public, PKCS#8 for private).
15
+ */
16
+ export declare function binaryToPem(binary: Uint8Array, type: 'public' | 'private'): string;
17
+ /**
18
+ * Decodes a base64-encoded string into a UTF-8 string.
19
+ *
20
+ * @param {string} str - The base64-encoded string to decode.
21
+ * @returns {string} The decoded UTF-8 string.
22
+ * @throws {Error} If the input string cannot be decoded.
23
+ */
24
+ export declare const decode: (str: string) => string;
25
+ /**
26
+ * Encodes a UTF-8 string into a base64-encoded string.
27
+ *
28
+ * @param {string} str - The UTF-8 string to encode.
29
+ * @returns {string} The base64-encoded string.
30
+ * @throws {Error} If the input string cannot be encoded.
31
+ */
32
+ export declare const encode: (str: string) => string;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ /**
3
+ * Shared helpers that work in both Node and browser (no Buffer or Node crypto).
4
+ * Uses atob/btoa (Node 16+ and browser) and TextEncoder/TextDecoder.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.encode = exports.decode = exports.binaryToPem = exports.pemToBinary = exports.base64ToBytes = void 0;
8
+ /**
9
+ * Encodes a UTF-8 string to base64 (environment-agnostic).
10
+ */
11
+ function bytesToBase64(bytes) {
12
+ var binary = '';
13
+ for (var i = 0; i < bytes.length; i++) {
14
+ binary += String.fromCharCode(bytes[i]);
15
+ }
16
+ return btoa(binary);
17
+ }
18
+ /**
19
+ * Decodes base64 to Uint8Array (environment-agnostic).
20
+ */
21
+ function base64ToBytes(base64) {
22
+ var binary = atob(base64);
23
+ var bytes = new Uint8Array(binary.length);
24
+ for (var i = 0; i < binary.length; i++) {
25
+ bytes[i] = binary.charCodeAt(i);
26
+ }
27
+ return bytes;
28
+ }
29
+ exports.base64ToBytes = base64ToBytes;
30
+ var PEM_PUBLIC_HEADER = '-----BEGIN PUBLIC KEY-----';
31
+ var PEM_PUBLIC_FOOTER = '-----END PUBLIC KEY-----';
32
+ var PEM_PRIVATE_HEADER = '-----BEGIN PRIVATE KEY-----';
33
+ var PEM_PRIVATE_FOOTER = '-----END PRIVATE KEY-----';
34
+ /**
35
+ * Extracts base64 body from a PEM string (removes headers and newlines).
36
+ */
37
+ function pemToBase64(pem) {
38
+ return pem
39
+ .replace(/-----BEGIN [^-]+-----/g, '')
40
+ .replace(/-----END [^-]+-----/g, '')
41
+ .replace(/\s/g, '');
42
+ }
43
+ /**
44
+ * Converts PEM string to binary (Uint8Array) for Web Crypto importKey.
45
+ */
46
+ function pemToBinary(pem) {
47
+ return base64ToBytes(pemToBase64(pem));
48
+ }
49
+ exports.pemToBinary = pemToBinary;
50
+ /**
51
+ * Wraps binary in PEM headers (SPKI for public, PKCS#8 for private).
52
+ */
53
+ function binaryToPem(binary, type) {
54
+ var b64 = '';
55
+ for (var i = 0; i < binary.length; i++) {
56
+ b64 += String.fromCharCode(binary[i]);
57
+ }
58
+ var base64 = btoa(b64);
59
+ var header = type === 'public' ? PEM_PUBLIC_HEADER : PEM_PRIVATE_HEADER;
60
+ var footer = type === 'public' ? PEM_PUBLIC_FOOTER : PEM_PRIVATE_FOOTER;
61
+ var lines = [];
62
+ for (var i = 0; i < base64.length; i += 64) {
63
+ lines.push(base64.slice(i, i + 64));
64
+ }
65
+ return "".concat(header, "\n").concat(lines.join('\n'), "\n").concat(footer);
66
+ }
67
+ exports.binaryToPem = binaryToPem;
68
+ /**
69
+ * Decodes a base64-encoded string into a UTF-8 string.
70
+ *
71
+ * @param {string} str - The base64-encoded string to decode.
72
+ * @returns {string} The decoded UTF-8 string.
73
+ * @throws {Error} If the input string cannot be decoded.
74
+ */
75
+ var decode = function (str) {
76
+ try {
77
+ var bytes = base64ToBytes(str);
78
+ return new TextDecoder().decode(bytes);
79
+ }
80
+ catch (error) {
81
+ throw new Error('Failed to decode base64 string');
82
+ }
83
+ };
84
+ exports.decode = decode;
85
+ /**
86
+ * Encodes a UTF-8 string into a base64-encoded string.
87
+ *
88
+ * @param {string} str - The UTF-8 string to encode.
89
+ * @returns {string} The base64-encoded string.
90
+ * @throws {Error} If the input string cannot be encoded.
91
+ */
92
+ var encode = function (str) {
93
+ try {
94
+ var bytes = new TextEncoder().encode(str);
95
+ return bytesToBase64(bytes);
96
+ }
97
+ catch (error) {
98
+ throw new Error('Failed to encode string to base64');
99
+ }
100
+ };
101
+ exports.encode = encode;
@@ -53,3 +53,16 @@ export type parametersOfDecryptPublic = {
53
53
  text: string;
54
54
  publicKey?: string;
55
55
  };
56
+ /**
57
+ * Shared public interface for NodeRSA (Node and Web builds).
58
+ * Both implementations use the same method names, parameter types, and return types.
59
+ */
60
+ export interface INodeRSA {
61
+ encryptStringWithRsaPublicKey(args: parametersOfEncrypt): Promise<string>;
62
+ decryptStringWithRsaPrivateKey(args: parametersOfDecrypt): Promise<string>;
63
+ encrypt(args: parametersOfEncryptPrivate): Promise<string>;
64
+ decrypt(args: parametersOfDecryptPublic): Promise<string>;
65
+ createPrivateAndPublicKeys(modulusLength?: number): Promise<returnCreateKeys>;
66
+ encryptBufferWithRsaPublicKey(buffer: Uint8Array, publicKey?: string): Promise<string>;
67
+ decryptBufferWithRsaPrivateKey(encryptedText: string, privateKey?: string): Promise<Uint8Array>;
68
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Shared helpers that work in both Node and browser (no Buffer or Node crypto).
3
+ * Uses atob/btoa (Node 16+ and browser) and TextEncoder/TextDecoder.
4
+ */
5
+ /**
6
+ * Decodes base64 to Uint8Array (environment-agnostic).
7
+ */
8
+ export declare function base64ToBytes(base64: string): Uint8Array;
9
+ /**
10
+ * Converts PEM string to binary (Uint8Array) for Web Crypto importKey.
11
+ */
12
+ export declare function pemToBinary(pem: string): Uint8Array;
13
+ /**
14
+ * Wraps binary in PEM headers (SPKI for public, PKCS#8 for private).
15
+ */
16
+ export declare function binaryToPem(binary: Uint8Array, type: 'public' | 'private'): string;
17
+ /**
18
+ * Decodes a base64-encoded string into a UTF-8 string.
19
+ *
20
+ * @param {string} str - The base64-encoded string to decode.
21
+ * @returns {string} The decoded UTF-8 string.
22
+ * @throws {Error} If the input string cannot be decoded.
23
+ */
24
+ export declare const decode: (str: string) => string;
25
+ /**
26
+ * Encodes a UTF-8 string into a base64-encoded string.
27
+ *
28
+ * @param {string} str - The UTF-8 string to encode.
29
+ * @returns {string} The base64-encoded string.
30
+ * @throws {Error} If the input string cannot be encoded.
31
+ */
32
+ export declare const encode: (str: string) => string;
@@ -0,0 +1,101 @@
1
+ "use strict";
2
+ /**
3
+ * Shared helpers that work in both Node and browser (no Buffer or Node crypto).
4
+ * Uses atob/btoa (Node 16+ and browser) and TextEncoder/TextDecoder.
5
+ */
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.encode = exports.decode = exports.binaryToPem = exports.pemToBinary = exports.base64ToBytes = void 0;
8
+ /**
9
+ * Encodes a UTF-8 string to base64 (environment-agnostic).
10
+ */
11
+ function bytesToBase64(bytes) {
12
+ var binary = '';
13
+ for (var i = 0; i < bytes.length; i++) {
14
+ binary += String.fromCharCode(bytes[i]);
15
+ }
16
+ return btoa(binary);
17
+ }
18
+ /**
19
+ * Decodes base64 to Uint8Array (environment-agnostic).
20
+ */
21
+ function base64ToBytes(base64) {
22
+ var binary = atob(base64);
23
+ var bytes = new Uint8Array(binary.length);
24
+ for (var i = 0; i < binary.length; i++) {
25
+ bytes[i] = binary.charCodeAt(i);
26
+ }
27
+ return bytes;
28
+ }
29
+ exports.base64ToBytes = base64ToBytes;
30
+ var PEM_PUBLIC_HEADER = '-----BEGIN PUBLIC KEY-----';
31
+ var PEM_PUBLIC_FOOTER = '-----END PUBLIC KEY-----';
32
+ var PEM_PRIVATE_HEADER = '-----BEGIN PRIVATE KEY-----';
33
+ var PEM_PRIVATE_FOOTER = '-----END PRIVATE KEY-----';
34
+ /**
35
+ * Extracts base64 body from a PEM string (removes headers and newlines).
36
+ */
37
+ function pemToBase64(pem) {
38
+ return pem
39
+ .replace(/-----BEGIN [^-]+-----/g, '')
40
+ .replace(/-----END [^-]+-----/g, '')
41
+ .replace(/\s/g, '');
42
+ }
43
+ /**
44
+ * Converts PEM string to binary (Uint8Array) for Web Crypto importKey.
45
+ */
46
+ function pemToBinary(pem) {
47
+ return base64ToBytes(pemToBase64(pem));
48
+ }
49
+ exports.pemToBinary = pemToBinary;
50
+ /**
51
+ * Wraps binary in PEM headers (SPKI for public, PKCS#8 for private).
52
+ */
53
+ function binaryToPem(binary, type) {
54
+ var b64 = '';
55
+ for (var i = 0; i < binary.length; i++) {
56
+ b64 += String.fromCharCode(binary[i]);
57
+ }
58
+ var base64 = btoa(b64);
59
+ var header = type === 'public' ? PEM_PUBLIC_HEADER : PEM_PRIVATE_HEADER;
60
+ var footer = type === 'public' ? PEM_PUBLIC_FOOTER : PEM_PRIVATE_FOOTER;
61
+ var lines = [];
62
+ for (var i = 0; i < base64.length; i += 64) {
63
+ lines.push(base64.slice(i, i + 64));
64
+ }
65
+ return "".concat(header, "\n").concat(lines.join('\n'), "\n").concat(footer);
66
+ }
67
+ exports.binaryToPem = binaryToPem;
68
+ /**
69
+ * Decodes a base64-encoded string into a UTF-8 string.
70
+ *
71
+ * @param {string} str - The base64-encoded string to decode.
72
+ * @returns {string} The decoded UTF-8 string.
73
+ * @throws {Error} If the input string cannot be decoded.
74
+ */
75
+ var decode = function (str) {
76
+ try {
77
+ var bytes = base64ToBytes(str);
78
+ return new TextDecoder().decode(bytes);
79
+ }
80
+ catch (error) {
81
+ throw new Error('Failed to decode base64 string');
82
+ }
83
+ };
84
+ exports.decode = decode;
85
+ /**
86
+ * Encodes a UTF-8 string into a base64-encoded string.
87
+ *
88
+ * @param {string} str - The UTF-8 string to encode.
89
+ * @returns {string} The base64-encoded string.
90
+ * @throws {Error} If the input string cannot be encoded.
91
+ */
92
+ var encode = function (str) {
93
+ try {
94
+ var bytes = new TextEncoder().encode(str);
95
+ return bytesToBase64(bytes);
96
+ }
97
+ catch (error) {
98
+ throw new Error('Failed to encode string to base64');
99
+ }
100
+ };
101
+ exports.encode = encode;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Type representing the return value of a function that creates RSA keys.
3
+ *
4
+ * @typedef {Object} returnCreateKeys
5
+ * @property {string} privateKey - The generated RSA private key.
6
+ * @property {string} publicKey - The generated RSA public key.
7
+ */
8
+ export type returnCreateKeys = {
9
+ privateKey: string;
10
+ publicKey: string;
11
+ };
12
+ /**
13
+ * Type representing the parameters required to encrypt text using a public key.
14
+ *
15
+ * @typedef {Object} parametersOfEncrypt
16
+ * @property {string} text - The plain text to be encrypted.
17
+ * @property {string} [publicKey] - Optional RSA public key for encryption. If not provided, a default key may be used.
18
+ */
19
+ export type parametersOfEncrypt = {
20
+ text: string;
21
+ publicKey?: string;
22
+ };
23
+ /**
24
+ * Type representing the parameters required to decrypt text using a private key.
25
+ *
26
+ * @typedef {Object} parametersOfDecrypt
27
+ * @property {string} text - The base64-encoded string to be decrypted.
28
+ * @property {string} [privateKey] - Optional RSA private key for decryption. If not provided, a default key may be used.
29
+ */
30
+ export type parametersOfDecrypt = {
31
+ text: string;
32
+ privateKey?: string;
33
+ };
34
+ /**
35
+ * Type representing the parameters required to encrypt text using a private key.
36
+ *
37
+ * @typedef {Object} parametersOfEncryptPrivate
38
+ * @property {string} text - The plain text to be encrypted.
39
+ * @property {string} [privateKey] - Optional RSA private key for encryption. If not provided, a default key may be used.
40
+ */
41
+ export type parametersOfEncryptPrivate = {
42
+ text: string;
43
+ privateKey?: string;
44
+ };
45
+ /**
46
+ * Type representing the parameters required to decrypt text using a public key.
47
+ *
48
+ * @typedef {Object} parametersOfDecryptPublic
49
+ * @property {string} text - The base64-encoded string to be decrypted.
50
+ * @property {string} [publicKey] - Optional RSA public key for decryption. If not provided, a default key may be used.
51
+ */
52
+ export type parametersOfDecryptPublic = {
53
+ text: string;
54
+ publicKey?: string;
55
+ };
56
+ /**
57
+ * Shared public interface for NodeRSA (Node and Web builds).
58
+ * Both implementations use the same method names, parameter types, and return types.
59
+ */
60
+ export interface INodeRSA {
61
+ encryptStringWithRsaPublicKey(args: parametersOfEncrypt): Promise<string>;
62
+ decryptStringWithRsaPrivateKey(args: parametersOfDecrypt): Promise<string>;
63
+ encrypt(args: parametersOfEncryptPrivate): Promise<string>;
64
+ decrypt(args: parametersOfDecryptPublic): Promise<string>;
65
+ createPrivateAndPublicKeys(modulusLength?: number): Promise<returnCreateKeys>;
66
+ encryptBufferWithRsaPublicKey(buffer: Uint8Array, publicKey?: string): Promise<string>;
67
+ decryptBufferWithRsaPrivateKey(encryptedText: string, privateKey?: string): Promise<Uint8Array>;
68
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -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;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.convertKetToBase64 = void 0;
4
+ var helpers_1 = require("../shared/helpers");
5
+ /**
6
+ * Converts an RSA key to a base64-encoded string.
7
+ * Removes leading spaces from each line, then base64-encodes.
8
+ */
9
+ function convertKetToBase64(key) {
10
+ return (0, helpers_1.encode)(key.replace(/^ +/gm, ''));
11
+ }
12
+ exports.convertKetToBase64 = convertKetToBase64;
13
+ exports.default = convertKetToBase64;
@@ -0,0 +1,6 @@
1
+ import type { parametersOfDecrypt, parametersOfDecryptPublic, parametersOfEncrypt, parametersOfEncryptPrivate, returnCreateKeys } from '../shared/types';
2
+ export declare function encryptStringWithRsaPublicKey(args: parametersOfEncrypt): Promise<string>;
3
+ export declare function decryptStringWithRsaPrivateKey(args: parametersOfDecrypt): Promise<string>;
4
+ export declare function encryptPrivate(_args: parametersOfEncryptPrivate): Promise<string>;
5
+ export declare function decryptPublic(_args: parametersOfDecryptPublic): Promise<string>;
6
+ export declare function createPrivateAndPublicKeys(modulusLength?: number): Promise<returnCreateKeys>;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __generator = (this && this.__generator) || function (thisArg, body) {
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
+ function verb(n) { return function (v) { return step([n, v]); }; }
15
+ function step(op) {
16
+ if (f) throw new TypeError("Generator is already executing.");
17
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
+ if (y = 0, t) op = [op[0] & 2, t.value];
20
+ switch (op[0]) {
21
+ case 0: case 1: t = op; break;
22
+ case 4: _.label++; return { value: op[1], done: false };
23
+ case 5: _.label++; y = op[1]; op = [0]; continue;
24
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
+ default:
26
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
+ if (t[2]) _.ops.pop();
31
+ _.trys.pop(); continue;
32
+ }
33
+ op = body.call(thisArg, _);
34
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
+ }
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.createPrivateAndPublicKeys = exports.decryptPublic = exports.encryptPrivate = exports.decryptStringWithRsaPrivateKey = exports.encryptStringWithRsaPublicKey = void 0;
40
+ /**
41
+ * Web build: Web Crypto API (RSA-OAEP with SHA-1).
42
+ * PEM import/export, encrypt/decrypt with public/private, generateKey.
43
+ * encrypt(private)/decrypt(public) not supported in Web Crypto; throws in browser.
44
+ */
45
+ var helpers_1 = require("../shared/helpers");
46
+ var helpers_2 = require("../shared/helpers");
47
+ function getCrypto() {
48
+ if (typeof globalThis !== 'undefined' && globalThis.crypto && globalThis.crypto.subtle) {
49
+ return globalThis.crypto;
50
+ }
51
+ throw new Error('Web Crypto API (crypto.subtle) is not available');
52
+ }
53
+ function importPublicKey(pem) {
54
+ return __awaiter(this, void 0, void 0, function () {
55
+ var pemDecoded, binary;
56
+ return __generator(this, function (_a) {
57
+ pemDecoded = (0, helpers_1.decode)(pem);
58
+ binary = (0, helpers_2.pemToBinary)(pemDecoded);
59
+ return [2 /*return*/, getCrypto().subtle.importKey('spki', binary, { name: 'RSA-OAEP', hash: 'SHA-1' }, false, ['encrypt'])];
60
+ });
61
+ });
62
+ }
63
+ function importPrivateKey(pem) {
64
+ return __awaiter(this, void 0, void 0, function () {
65
+ var pemDecoded, binary;
66
+ return __generator(this, function (_a) {
67
+ pemDecoded = (0, helpers_1.decode)(pem);
68
+ binary = (0, helpers_2.pemToBinary)(pemDecoded);
69
+ return [2 /*return*/, getCrypto().subtle.importKey('pkcs8', binary, { name: 'RSA-OAEP', hash: 'SHA-1' }, false, ['decrypt'])];
70
+ });
71
+ });
72
+ }
73
+ function encryptStringWithRsaPublicKey(args) {
74
+ return __awaiter(this, void 0, void 0, function () {
75
+ var text, publicKey, key, data, encrypted, bytes, binary, i;
76
+ return __generator(this, function (_a) {
77
+ switch (_a.label) {
78
+ case 0:
79
+ text = args.text, publicKey = args.publicKey;
80
+ return [4 /*yield*/, importPublicKey(publicKey)];
81
+ case 1:
82
+ key = _a.sent();
83
+ data = new TextEncoder().encode(text);
84
+ return [4 /*yield*/, getCrypto().subtle.encrypt({ name: 'RSA-OAEP' }, key, data)];
85
+ case 2:
86
+ encrypted = _a.sent();
87
+ bytes = new Uint8Array(encrypted);
88
+ binary = '';
89
+ for (i = 0; i < bytes.length; i++) {
90
+ binary += String.fromCharCode(bytes[i]);
91
+ }
92
+ return [2 /*return*/, btoa(binary)];
93
+ }
94
+ });
95
+ });
96
+ }
97
+ exports.encryptStringWithRsaPublicKey = encryptStringWithRsaPublicKey;
98
+ function decryptStringWithRsaPrivateKey(args) {
99
+ return __awaiter(this, void 0, void 0, function () {
100
+ var text, privateKey, key, binary, bytes, i, decrypted;
101
+ return __generator(this, function (_a) {
102
+ switch (_a.label) {
103
+ case 0:
104
+ text = args.text, privateKey = args.privateKey;
105
+ return [4 /*yield*/, importPrivateKey(privateKey)];
106
+ case 1:
107
+ key = _a.sent();
108
+ binary = atob(text);
109
+ bytes = new Uint8Array(binary.length);
110
+ for (i = 0; i < binary.length; i++) {
111
+ bytes[i] = binary.charCodeAt(i);
112
+ }
113
+ return [4 /*yield*/, getCrypto().subtle.decrypt({ name: 'RSA-OAEP' }, key, bytes)];
114
+ case 2:
115
+ decrypted = _a.sent();
116
+ return [2 /*return*/, new TextDecoder().decode(decrypted)];
117
+ }
118
+ });
119
+ });
120
+ }
121
+ exports.decryptStringWithRsaPrivateKey = decryptStringWithRsaPrivateKey;
122
+ function encryptPrivate(_args) {
123
+ return __awaiter(this, void 0, void 0, function () {
124
+ return __generator(this, function (_a) {
125
+ throw new Error('Encrypt with private key is not supported in the browser build. Use encryptStringWithRsaPublicKey for encryption.');
126
+ });
127
+ });
128
+ }
129
+ exports.encryptPrivate = encryptPrivate;
130
+ function decryptPublic(_args) {
131
+ return __awaiter(this, void 0, void 0, function () {
132
+ return __generator(this, function (_a) {
133
+ throw new Error('Decrypt with public key is not supported in the browser build. Use decryptStringWithRsaPrivateKey for decryption.');
134
+ });
135
+ });
136
+ }
137
+ exports.decryptPublic = decryptPublic;
138
+ function createPrivateAndPublicKeys(modulusLength) {
139
+ if (modulusLength === void 0) { modulusLength = 2048; }
140
+ return __awaiter(this, void 0, void 0, function () {
141
+ var keyPair, _a, publicDer, privateDer, publicKey, privateKey;
142
+ return __generator(this, function (_b) {
143
+ switch (_b.label) {
144
+ case 0: return [4 /*yield*/, getCrypto().subtle.generateKey({
145
+ name: 'RSA-OAEP',
146
+ modulusLength: modulusLength,
147
+ publicExponent: new Uint8Array([1, 0, 1]),
148
+ hash: 'SHA-1',
149
+ }, true, ['encrypt', 'decrypt'])];
150
+ case 1:
151
+ keyPair = _b.sent();
152
+ return [4 /*yield*/, Promise.all([
153
+ getCrypto().subtle.exportKey('spki', keyPair.publicKey),
154
+ getCrypto().subtle.exportKey('pkcs8', keyPair.privateKey),
155
+ ])];
156
+ case 2:
157
+ _a = _b.sent(), publicDer = _a[0], privateDer = _a[1];
158
+ publicKey = (0, helpers_2.binaryToPem)(new Uint8Array(publicDer), 'public');
159
+ privateKey = (0, helpers_2.binaryToPem)(new Uint8Array(privateDer), 'private');
160
+ return [2 /*return*/, { publicKey: publicKey, privateKey: privateKey }];
161
+ }
162
+ });
163
+ });
164
+ }
165
+ 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,77 @@
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
+ * Web build: NodeRSA using Web Crypto API (async).
19
+ * Same interface as Node build; uses crypto.subtle for RSA-OAEP.
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 (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 (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 (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 (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 (0, crypto_1.createPrivateAndPublicKeys)(modulusLength);
49
+ };
50
+ NodeRSA.prototype.encryptBufferWithRsaPublicKey = function (buffer, publicKey) {
51
+ if (this.keyBase64 !== 'base64') {
52
+ throw new Error('Only base64 encoding is supported');
53
+ }
54
+ var bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
55
+ var binary = '';
56
+ for (var i = 0; i < bytes.length; i++) {
57
+ binary += String.fromCharCode(bytes[i]);
58
+ }
59
+ var base64String = btoa(binary);
60
+ return this.encryptStringWithRsaPublicKey({ text: base64String, publicKey: publicKey });
61
+ };
62
+ NodeRSA.prototype.decryptBufferWithRsaPrivateKey = function (encryptedText, privateKey) {
63
+ if (this.keyBase64 !== 'base64') {
64
+ throw new Error('Only base64 encoding is supported');
65
+ }
66
+ return this.decryptStringWithRsaPrivateKey({ text: encryptedText, privateKey: privateKey }).then(function (decryptedBase64) {
67
+ var binary = atob(decryptedBase64);
68
+ var bytes = new Uint8Array(binary.length);
69
+ for (var i = 0; i < binary.length; i++) {
70
+ bytes[i] = binary.charCodeAt(i);
71
+ }
72
+ return bytes;
73
+ });
74
+ };
75
+ return NodeRSA;
76
+ }());
77
+ exports.default = NodeRSA;