tiny-essentials 1.2.1 β†’ 1.3.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.
@@ -1,202 +0,0 @@
1
- # ✨ Tiny Cert Crypto
2
-
3
- A lightweight πŸ” utility for managing, generating, and handling **X.509 certificates** and **RSA key pairs**.
4
- Built with flexibility in mind β€” runs seamlessly in both **Node.js** and **browser** environments! 🌍
5
-
6
- ---
7
-
8
- ## πŸ“¦ Features
9
-
10
- - πŸ› οΈ RSA key pair generation (**Node.js only**)
11
- - 🧾 Self-signed X.509 certificate creation
12
- - 🧬 Support for PEM-based πŸ”‘ public/private keys and certificates
13
- - 🧊 JSON encryption & decryption using Base64 encoding
14
- - πŸ•΅οΈ Metadata extraction from certificates (issuer, subject, validity, etc.)
15
- - πŸ“ Flexible key loading: from memory, local files (Node.js), or URLs (browser)
16
-
17
- ---
18
-
19
- ## πŸš€ Getting Started
20
-
21
- ### πŸ“š Constructor
22
-
23
- ```js
24
- const instance = new TinyCertCrypto({
25
- publicCertPath: 'cert.pem', // Path to public cert (Node.js)
26
- privateKeyPath: 'key.pem', // Path to private key (Node.js)
27
- publicCertBuffer: null, // String or Buffer in memory (Node.js/browser)
28
- privateKeyBuffer: null, // String or Buffer in memory (Node.js/browser)
29
- cryptoType: 'RSA-OAEP', // Encryption algorithm (default: 'RSA-OAEP')
30
- });
31
- ```
32
-
33
- > πŸ” In **browser environments**, at least `publicCertPath` or `publicCertBuffer` must be provided.
34
-
35
- ---
36
-
37
- ## πŸ§ͺ Core Methods
38
-
39
- ### πŸ”§ `async init()`
40
- Initializes the certificate and key system from files, memory buffers, or URLs.
41
-
42
- - Loads the public certificate/key.
43
- - Optionally loads the private key.
44
- - Detects whether you’re running in Node.js or the browser and adjusts behavior accordingly.
45
-
46
- ---
47
-
48
- ### πŸ“‘ `extractCertMetadata()`
49
- Returns parsed metadata from the loaded certificate.
50
-
51
- ```js
52
- {
53
- subject: { names: {}, shortNames: {}, raw: "CN=example.com,O=MyOrg" },
54
- issuer: { names: {}, shortNames: {}, raw: "CN=example.com,O=MyOrg" },
55
- serialNumber: '...',
56
- validFrom: Date,
57
- validTo: Date
58
- }
59
- ```
60
-
61
- ---
62
-
63
- ### πŸ›‘οΈ `encryptJson(jsonObject)`
64
- Encrypts a JavaScript object using the loaded **public key**, returning a **Base64-encoded string**.
65
-
66
- ```js
67
- const encrypted = instance.encryptJson({ hello: "world" });
68
- ```
69
-
70
- ---
71
-
72
- ### πŸ”“ `decryptToJson(base64String)`
73
- Decrypts a Base64 string using the **private key**, returning the original JSON object.
74
-
75
- ```js
76
- const json = instance.decryptToJson(encrypted);
77
- ```
78
-
79
- ---
80
-
81
- ### πŸ” `hasKeys()`
82
- Returns `true` if both `publicKey` and `privateKey` are loaded.
83
-
84
- ---
85
-
86
- ### πŸ“œ `hasCert()`
87
- Returns `true` if a certificate (`publicCert`) is loaded.
88
-
89
- ---
90
-
91
- ### ♻️ `reset()`
92
- Resets the internal state, clearing:
93
- - `publicKey`
94
- - `privateKey`
95
- - `publicCert`
96
- - `metadata`
97
- - `source`
98
-
99
- ---
100
-
101
- ### πŸ“¦ `fetchNodeForge()` & `getNodeForge()`
102
- Handles lazy-loading and reuse of the `node-forge` module.
103
-
104
- Use if you want to access Forge directly without importing it yourself:
105
-
106
- ```js
107
- const forge = await instance.fetchNodeForge();
108
- ```
109
-
110
- ---
111
-
112
- ## 🧠 Internals & Design
113
-
114
- - πŸ” Uses regular expressions to detect PEM types (`CERTIFICATE`, `PUBLIC KEY`, `PRIVATE KEY`)
115
- - πŸ§ͺ Automatically parses PEM buffers and files depending on the runtime
116
- - πŸ” Encrypts data with the selected algorithm (`RSA-OAEP`, etc.)
117
- - 🧬 X.509 certificate metadata extraction is done via `node-forge`
118
-
119
- ---
120
-
121
- ## 🧰 Requirements
122
-
123
- | Environment | Requirement |
124
- |-------------|--------------------|
125
- | Node.js | `node-forge` |
126
- | Browser | Works with native `fetch()` and `TextDecoder` |
127
-
128
- ---
129
-
130
- ## 😺 Example Use Case
131
-
132
- ```js
133
- const crypto = new TinyCertCrypto({ publicCertPath: 'cert.pem', privateKeyPath: 'key.pem' });
134
- await crypto.init();
135
-
136
- const data = { secret: 'I love ponies' };
137
- const encrypted = crypto.encryptJson(data);
138
- const decrypted = crypto.decryptToJson(encrypted);
139
-
140
- console.log(decrypted); // { secret: 'I love ponies' }
141
- ```
142
-
143
- ---
144
-
145
- ### 🧾 `async generateX509Cert(subjectFields, options = {})`
146
- Generates a new **RSA key pair** and a **self-signed X.509 certificate** using the provided subject information.
147
-
148
- πŸ” This is ideal for internal services, development environments, or cryptographic testing tools where a trusted CA is not required.
149
-
150
- ---
151
-
152
- **🧬 Parameters:**
153
-
154
- - `subjectFields` (`Object`) – Describes the identity fields that will be embedded into the certificate's subject and issuer:
155
- - Common fields include:
156
- - `CN`: Common Name (e.g. domain or hostname)
157
- - `O`: Organization Name
158
- - `OU`: Organizational Unit
159
- - `L`: Locality (City)
160
- - `ST`: State or Province
161
- - `C`: Country (2-letter code)
162
- - `emailAddress`: Optional email field
163
-
164
- - `options` (`Object`) – Optional configuration:
165
- - `keySize` (`number`) – RSA key size in bits (default: `2048`)
166
- - `validityInYears` (`number`) – Certificate validity period (default: `1`)
167
- - `randomBytesLength` (`number`) – Length of the serial number (default: `16`)
168
- - `digestAlgorithm` (`string`) – Digest algorithm used to sign the certificate (default: `'sha256'`)
169
- - `forgeInstance` (`object`) – Optionally inject a specific instance of `node-forge`
170
- - `cryptoType` (`string`) – Encryption scheme used for later operations (e.g., `'RSA-OAEP'`, `'RSAES-PKCS1-V1_5'`)
171
-
172
- ---
173
-
174
- **βœ… Returns:**
175
-
176
- An object containing all the generated artifacts:
177
-
178
- ```js
179
- {
180
- publicKey: '-----BEGIN PUBLIC KEY-----...',
181
- privateKey: '-----BEGIN PRIVATE KEY-----...',
182
- cert: '-----BEGIN CERTIFICATE-----...'
183
- }
184
- ```
185
-
186
- - `publicKey`: The newly generated **PEM-encoded RSA public key**
187
- - `privateKey`: The corresponding **PEM-encoded RSA private key**
188
- - `cert`: A **PEM-encoded X.509 certificate** that is **self-signed** with the private key and matches the provided subject
189
-
190
- ---
191
-
192
- **πŸ“Œ Notes:**
193
-
194
- - πŸ”„ The `subject` and `issuer` of the certificate are the same (self-signed).
195
- - ⏳ The certificate `validFrom` is set to the current date, and `validTo` is based on the `validityInYears` option.
196
- - πŸ”’ A secure random `serialNumber` is generated using `crypto.randomBytes`.
197
-
198
- ---
199
-
200
- **⚠️ Availability:**
201
-
202
- > This method is only available in **Node.js environments** due to its dependency on the native `crypto` module and synchronous file access via `fs`.
@@ -1,177 +0,0 @@
1
- # πŸ” Tiny Crypto
2
-
3
- **Tiny Crypto** is a flexible and browser-compatible encryption utility class built for AES-256-GCM encryption with full support for serialization and deserialization of complex JavaScript data types.
4
-
5
- Whether you're in Node.js or a browser, Tiny Crypto helps you easily encrypt/decrypt values, save/load configurations, and keep your secrets safe β€” all while supporting real-world usage like RegExp, Date, Buffer, and even DOM elements (in browsers only)!
6
-
7
- ---
8
-
9
- ## ✨ Features
10
-
11
- - πŸ”’ AES-256-GCM symmetric encryption
12
- - 🧠 Automatic serialization of complex types (Date, RegExp, Set, Map, etc.)
13
- - πŸ“€ Save and load keys/configs from files
14
- - 🌐 Works in both **Node.js** and **Browsers**
15
- - ⚠️ Type validation on decryption
16
- - πŸ’Ύ Smart support for file APIs (e.g. `FileReader` in browser, `fs` in Node)
17
-
18
- ---
19
-
20
- ## πŸš€ Getting Started
21
-
22
- ```js
23
- const crypto = new TinyCrypto();
24
-
25
- // Encrypt some data
26
- const { encrypted, iv, authTag } = crypto.encrypt({ hello: 'world' });
27
-
28
- // Decrypt it back
29
- const decrypted = crypto.decrypt({ encrypted, iv, authTag });
30
-
31
- console.log(decrypted); // { hello: 'world' }
32
- ```
33
-
34
- ---
35
-
36
- ## 🧠 Supported Data Types
37
-
38
- When you encrypt a value, its type is recorded and restored when decrypted.
39
-
40
- Supports:
41
-
42
- - `String`, `Number`, `Boolean`, `BigInt`, `Null`, `Undefined`
43
- - `Array`, `Object`, `Map`, `Set`, `Buffer`
44
- - `RegExp`, `Date`, `Symbol`
45
- - `HTMLElement` _(browser only)_
46
-
47
- Does NOT support:
48
-
49
- - `Function`, `Promise`, `WeakMap`, `WeakSet` β†’ ❌ Will throw!
50
-
51
- ---
52
-
53
- ## πŸ”§ API
54
-
55
- ### `constructor(options)`
56
-
57
- | Option | Type | Default | Description |
58
- | ---------------- | ------ | --------------- | --------------------------------- |
59
- | `algorithm` | string | `'aes-256-gcm'` | AES algorithm used for encryption |
60
- | `key` | Buffer | auto-generated | The secret key to use (32 bytes) |
61
- | `outputEncoding` | string | `'hex'` | Encoding used for outputs |
62
- | `inputEncoding` | string | `'utf8'` | Encoding used for plain data |
63
- | `authTagLength` | number | `16` | GCM auth tag length |
64
-
65
- ---
66
-
67
- ### `encrypt(data, iv?)`
68
-
69
- Encrypts a value and returns an object with `{ iv, encrypted, authTag }`.
70
-
71
- ```js
72
- const result = crypto.encrypt('Hello!');
73
- ```
74
-
75
- ---
76
-
77
- ### `decrypt({ iv, encrypted, authTag }, expectedType?)`
78
-
79
- Decrypts a previously encrypted value and returns the original data. You can optionally pass an `expectedType` to validate it.
80
-
81
- ```js
82
- const plain = crypto.decrypt(result, 'string');
83
- ```
84
-
85
- ---
86
-
87
- ### `getTypeFromEncrypted({ iv, encrypted, authTag })`
88
-
89
- Returns the type name of the encrypted data without fully decrypting it.
90
-
91
- ---
92
-
93
- ### `generateKey(length = 32)`
94
-
95
- Generates a secure random key. Default: 32 bytes (AES-256).
96
-
97
- ---
98
-
99
- ### `generateIV(length = 12)`
100
-
101
- Generates a secure random IV. Default: 12 bytes (GCM standard).
102
-
103
- ---
104
-
105
- ### `saveKeyToFile(filename = 'secret.key')`
106
-
107
- Saves the current key to a file (browser: prompts download).
108
-
109
- ---
110
-
111
- ### `loadKeyFromFile(file)`
112
-
113
- Loads a key from a file (browser: File object, Node: file path).
114
-
115
- ---
116
-
117
- ### `saveConfigToFile(filename = 'crypto-config.json')`
118
-
119
- Saves the current configuration as JSON.
120
-
121
- ---
122
-
123
- ### `loadConfigFromFile(file)`
124
-
125
- Loads configuration from a JSON file.
126
-
127
- ---
128
-
129
- ### `exportConfig()`
130
-
131
- Returns an object with the current settings:
132
-
133
- ```json
134
- {
135
- "algorithm": "aes-256-gcm",
136
- "outputEncoding": "hex",
137
- "inputEncoding": "utf8",
138
- "authTagLength": 16,
139
- "key": "..."
140
- }
141
- ```
142
-
143
- ---
144
-
145
- ### `importConfig(config)`
146
-
147
- Applies a configuration object. Throws if invalid types are provided.
148
-
149
- ---
150
-
151
- ## πŸ§ͺ Type Validation
152
-
153
- You can ensure the decrypted value matches the original type:
154
-
155
- ```js
156
- crypto.decrypt(result, 'map'); // βœ…
157
- crypto.decrypt(result, 'set'); // ❌ throws if type mismatch
158
- ```
159
-
160
- ---
161
-
162
- ## ❗ Errors You Might See
163
-
164
- - `Unsupported data type for encryption: Function`
165
- - `Type mismatch: expected Map, but got Set`
166
- - `Invalid config JSON file`
167
- - `HTMLElement deserialization is only supported in browsers`
168
-
169
- ---
170
-
171
- ## πŸ›‘οΈ Security Notice
172
-
173
- This utility is for learning and light usage. For production, ensure:
174
-
175
- - Proper key management (use secure vaults)
176
- - Safe IV reuse (IVs must be unique per encryption)
177
- - Your platform's crypto standards are followed