simple-crypto-utils 1.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 (225) hide show
  1. package/dist/crypto/decrypt.d.ts +1 -0
  2. package/dist/crypto/decrypt.d.ts.map +1 -0
  3. package/dist/crypto/decrypt.js +2 -0
  4. package/dist/crypto/decrypt.js.map +1 -0
  5. package/dist/crypto/encrypt.d.ts +1 -0
  6. package/dist/crypto/encrypt.d.ts.map +1 -0
  7. package/dist/crypto/encrypt.js +2 -0
  8. package/dist/crypto/encrypt.js.map +1 -0
  9. package/dist/crypto/signMessage.d.ts +1 -0
  10. package/dist/crypto/signMessage.d.ts.map +1 -0
  11. package/dist/crypto/signMessage.js +2 -0
  12. package/dist/crypto/signMessage.js.map +1 -0
  13. package/dist/crypto/verifyMessage.d.ts +1 -0
  14. package/dist/crypto/verifyMessage.d.ts.map +1 -0
  15. package/dist/crypto/verifyMessage.js +2 -0
  16. package/dist/crypto/verifyMessage.js.map +1 -0
  17. package/dist/crypto-asymmetricaly/file/decryptFile.d.ts +2 -0
  18. package/dist/crypto-asymmetricaly/file/decryptFile.d.ts.map +1 -0
  19. package/dist/crypto-asymmetricaly/file/decryptFile.js +93 -0
  20. package/dist/crypto-asymmetricaly/file/decryptFile.js.map +1 -0
  21. package/dist/crypto-asymmetricaly/file/encryptFile.d.ts +3 -0
  22. package/dist/crypto-asymmetricaly/file/encryptFile.d.ts.map +1 -0
  23. package/dist/crypto-asymmetricaly/file/encryptFile.js +110 -0
  24. package/dist/crypto-asymmetricaly/file/encryptFile.js.map +1 -0
  25. package/dist/crypto-asymmetricaly/index.d.ts +5 -0
  26. package/dist/crypto-asymmetricaly/index.d.ts.map +1 -0
  27. package/dist/crypto-asymmetricaly/index.js +5 -0
  28. package/dist/crypto-asymmetricaly/index.js.map +1 -0
  29. package/dist/crypto-asymmetricaly/keys/generateRSA.d.ts +5 -0
  30. package/dist/crypto-asymmetricaly/keys/generateRSA.d.ts.map +1 -0
  31. package/dist/crypto-asymmetricaly/keys/generateRSA.js +24 -0
  32. package/dist/crypto-asymmetricaly/keys/generateRSA.js.map +1 -0
  33. package/dist/crypto-asymmetricaly/rsa/unwrapKey.d.ts +1 -0
  34. package/dist/crypto-asymmetricaly/rsa/unwrapKey.d.ts.map +1 -0
  35. package/dist/crypto-asymmetricaly/rsa/unwrapKey.js +2 -0
  36. package/dist/crypto-asymmetricaly/rsa/unwrapKey.js.map +1 -0
  37. package/dist/crypto-asymmetricaly/rsa/wrapKey.d.ts +1 -0
  38. package/dist/crypto-asymmetricaly/rsa/wrapKey.d.ts.map +1 -0
  39. package/dist/crypto-asymmetricaly/rsa/wrapKey.js +2 -0
  40. package/dist/crypto-asymmetricaly/rsa/wrapKey.js.map +1 -0
  41. package/dist/crypto-asymmetricaly/string/decryptString.d.ts +2 -0
  42. package/dist/crypto-asymmetricaly/string/decryptString.d.ts.map +1 -0
  43. package/dist/crypto-asymmetricaly/string/decryptString.js +47 -0
  44. package/dist/crypto-asymmetricaly/string/decryptString.js.map +1 -0
  45. package/dist/crypto-asymmetricaly/string/encryptString.d.ts +7 -0
  46. package/dist/crypto-asymmetricaly/string/encryptString.d.ts.map +1 -0
  47. package/dist/crypto-asymmetricaly/string/encryptString.js +26 -0
  48. package/dist/crypto-asymmetricaly/string/encryptString.js.map +1 -0
  49. package/dist/crypto-asymmetricaly/string/generateAES.d.ts +5 -0
  50. package/dist/crypto-asymmetricaly/string/generateAES.d.ts.map +1 -0
  51. package/dist/crypto-asymmetricaly/string/generateAES.js +7 -0
  52. package/dist/crypto-asymmetricaly/string/generateAES.js.map +1 -0
  53. package/dist/crypto-symmetricaly/decrypt.d.ts +2 -0
  54. package/dist/crypto-symmetricaly/decrypt.d.ts.map +1 -0
  55. package/dist/crypto-symmetricaly/decrypt.js +14 -0
  56. package/dist/crypto-symmetricaly/decrypt.js.map +1 -0
  57. package/dist/crypto-symmetricaly/encrypt.d.ts +2 -0
  58. package/dist/crypto-symmetricaly/encrypt.d.ts.map +1 -0
  59. package/dist/crypto-symmetricaly/encrypt.js +16 -0
  60. package/dist/crypto-symmetricaly/encrypt.js.map +1 -0
  61. package/dist/crypto-symmetricaly/index.d.ts +3 -0
  62. package/dist/crypto-symmetricaly/index.d.ts.map +1 -0
  63. package/dist/crypto-symmetricaly/index.js +3 -0
  64. package/dist/crypto-symmetricaly/index.js.map +1 -0
  65. package/dist/crypto-symmetricaly/signMessage.d.ts +1 -0
  66. package/dist/crypto-symmetricaly/signMessage.d.ts.map +1 -0
  67. package/dist/crypto-symmetricaly/signMessage.js +2 -0
  68. package/dist/crypto-symmetricaly/signMessage.js.map +1 -0
  69. package/dist/crypto-symmetricaly/verifyMessage.d.ts +1 -0
  70. package/dist/crypto-symmetricaly/verifyMessage.d.ts.map +1 -0
  71. package/dist/crypto-symmetricaly/verifyMessage.js +2 -0
  72. package/dist/crypto-symmetricaly/verifyMessage.js.map +1 -0
  73. package/dist/hash/hash.d.ts +2 -0
  74. package/dist/hash/hash.d.ts.map +1 -0
  75. package/dist/hash/hash.js +7 -0
  76. package/dist/hash/hash.js.map +1 -0
  77. package/dist/hash/hashHmac.d.ts +2 -0
  78. package/dist/hash/hashHmac.d.ts.map +1 -0
  79. package/dist/hash/hashHmac.js +5 -0
  80. package/dist/hash/hashHmac.js.map +1 -0
  81. package/dist/hash/index.d.ts +4 -0
  82. package/dist/hash/index.d.ts.map +1 -0
  83. package/dist/hash/index.js +4 -0
  84. package/dist/hash/index.js.map +1 -0
  85. package/dist/hash/verifyHmac.d.ts +2 -0
  86. package/dist/hash/verifyHmac.d.ts.map +1 -0
  87. package/dist/hash/verifyHmac.js +10 -0
  88. package/dist/hash/verifyHmac.js.map +1 -0
  89. package/dist/index.cjs +1569 -0
  90. package/dist/index.d.cts +350 -0
  91. package/dist/index.d.ts +350 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +1546 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/otp/TOTP.d.ts +10 -0
  96. package/dist/otp/TOTP.d.ts.map +1 -0
  97. package/dist/otp/TOTP.js +33 -0
  98. package/dist/otp/TOTP.js.map +1 -0
  99. package/dist/otp/generate.d.ts +2 -0
  100. package/dist/otp/generate.d.ts.map +1 -0
  101. package/dist/otp/generate.js +7 -0
  102. package/dist/otp/generate.js.map +1 -0
  103. package/dist/otp/generateOTP.d.ts +1 -0
  104. package/dist/otp/generateOTP.d.ts.map +1 -0
  105. package/dist/otp/generateOTP.js +2 -0
  106. package/dist/otp/generateOTP.js.map +1 -0
  107. package/dist/otp/hash.d.ts +2 -0
  108. package/dist/otp/hash.d.ts.map +1 -0
  109. package/dist/otp/hash.js +5 -0
  110. package/dist/otp/hash.js.map +1 -0
  111. package/dist/otp/index.d.ts +3 -0
  112. package/dist/otp/index.d.ts.map +1 -0
  113. package/dist/otp/index.js +3 -0
  114. package/dist/otp/index.js.map +1 -0
  115. package/dist/otp/verifyOTP.d.ts +1 -0
  116. package/dist/otp/verifyOTP.d.ts.map +1 -0
  117. package/dist/otp/verifyOTP.js +2 -0
  118. package/dist/otp/verifyOTP.js.map +1 -0
  119. package/dist/password/generate.d.ts +15 -0
  120. package/dist/password/generate.d.ts.map +1 -0
  121. package/dist/password/generate.js +44 -0
  122. package/dist/password/generate.js.map +1 -0
  123. package/dist/password/generatePassword.d.ts +2 -0
  124. package/dist/password/generatePassword.d.ts.map +1 -0
  125. package/dist/password/generatePassword.js +10 -0
  126. package/dist/password/generatePassword.js.map +1 -0
  127. package/dist/password/hash.d.ts +2 -0
  128. package/dist/password/hash.d.ts.map +1 -0
  129. package/dist/password/hash.js +12 -0
  130. package/dist/password/hash.js.map +1 -0
  131. package/dist/password/hashPassword.d.ts +1 -0
  132. package/dist/password/hashPassword.d.ts.map +1 -0
  133. package/dist/password/hashPassword.js +2 -0
  134. package/dist/password/hashPassword.js.map +1 -0
  135. package/dist/password/index.d.ts +4 -0
  136. package/dist/password/index.d.ts.map +1 -0
  137. package/dist/password/index.js +4 -0
  138. package/dist/password/index.js.map +1 -0
  139. package/dist/password/validatePassword.d.ts +1 -0
  140. package/dist/password/validatePassword.d.ts.map +1 -0
  141. package/dist/password/validatePassword.js +2 -0
  142. package/dist/password/validatePassword.js.map +1 -0
  143. package/dist/password/verify.d.ts +2 -0
  144. package/dist/password/verify.d.ts.map +1 -0
  145. package/dist/password/verify.js +33 -0
  146. package/dist/password/verify.js.map +1 -0
  147. package/dist/password/verifyPassword.d.ts +1 -0
  148. package/dist/password/verifyPassword.d.ts.map +1 -0
  149. package/dist/password/verifyPassword.js +2 -0
  150. package/dist/password/verifyPassword.js.map +1 -0
  151. package/dist/signature/index.d.ts +46 -0
  152. package/dist/signature/index.d.ts.map +1 -0
  153. package/dist/signature/index.js +51 -0
  154. package/dist/signature/index.js.map +1 -0
  155. package/dist/signature/serialize.d.ts +4 -0
  156. package/dist/signature/serialize.d.ts.map +1 -0
  157. package/dist/signature/serialize.js +33 -0
  158. package/dist/signature/serialize.js.map +1 -0
  159. package/dist/signature/sign.d.ts +3 -0
  160. package/dist/signature/sign.d.ts.map +1 -0
  161. package/dist/signature/sign.js +26 -0
  162. package/dist/signature/sign.js.map +1 -0
  163. package/dist/signature/types.d.ts +16 -0
  164. package/dist/signature/types.d.ts.map +1 -0
  165. package/dist/signature/types.js +2 -0
  166. package/dist/signature/types.js.map +1 -0
  167. package/dist/signature/verify.d.ts +3 -0
  168. package/dist/signature/verify.d.ts.map +1 -0
  169. package/dist/signature/verify.js +26 -0
  170. package/dist/signature/verify.js.map +1 -0
  171. package/dist/test-minimal.d.ts +1 -0
  172. package/dist/test-minimal.d.ts.map +1 -0
  173. package/dist/test-minimal.js +4 -0
  174. package/dist/test-minimal.js.map +1 -0
  175. package/dist/test.d.ts +2 -0
  176. package/dist/test.d.ts.map +1 -0
  177. package/dist/test.js +33 -0
  178. package/dist/test.js.map +1 -0
  179. package/dist/token/generateRandomToken.d.ts +1 -0
  180. package/dist/token/generateRandomToken.d.ts.map +1 -0
  181. package/dist/token/generateRandomToken.js +2 -0
  182. package/dist/token/generateRandomToken.js.map +1 -0
  183. package/dist/token/generateUUID.d.ts +1 -0
  184. package/dist/token/generateUUID.d.ts.map +1 -0
  185. package/dist/token/generateUUID.js +2 -0
  186. package/dist/token/generateUUID.js.map +1 -0
  187. package/dist/token/hashToken.d.ts +1 -0
  188. package/dist/token/hashToken.d.ts.map +1 -0
  189. package/dist/token/hashToken.js +2 -0
  190. package/dist/token/hashToken.js.map +1 -0
  191. package/dist/utlis/constants.d.ts +4 -0
  192. package/dist/utlis/constants.d.ts.map +1 -0
  193. package/dist/utlis/constants.js +4 -0
  194. package/dist/utlis/constants.js.map +1 -0
  195. package/dist/utlis/entropyScore.d.ts +1 -0
  196. package/dist/utlis/entropyScore.d.ts.map +1 -0
  197. package/dist/utlis/entropyScore.js +2 -0
  198. package/dist/utlis/entropyScore.js.map +1 -0
  199. package/dist/utlis/generateRandomBytes.d.ts +2 -0
  200. package/dist/utlis/generateRandomBytes.d.ts.map +1 -0
  201. package/dist/utlis/generateRandomBytes.js +9 -0
  202. package/dist/utlis/generateRandomBytes.js.map +1 -0
  203. package/dist/utlis/maskSensitive.d.ts +1 -0
  204. package/dist/utlis/maskSensitive.d.ts.map +1 -0
  205. package/dist/utlis/maskSensitive.js +2 -0
  206. package/dist/utlis/maskSensitive.js.map +1 -0
  207. package/dist/utlis/safeCompare.d.ts +1 -0
  208. package/dist/utlis/safeCompare.d.ts.map +1 -0
  209. package/dist/utlis/safeCompare.js +2 -0
  210. package/dist/utlis/safeCompare.js.map +1 -0
  211. package/dist/uuid/generate.d.ts +2 -0
  212. package/dist/uuid/generate.d.ts.map +1 -0
  213. package/dist/uuid/generate.js +5 -0
  214. package/dist/uuid/generate.js.map +1 -0
  215. package/dist/uuid/hashToken.d.ts +1 -0
  216. package/dist/uuid/hashToken.d.ts.map +1 -0
  217. package/dist/uuid/hashToken.js +6 -0
  218. package/dist/uuid/hashToken.js.map +1 -0
  219. package/dist/uuid/index.d.ts +2 -0
  220. package/dist/uuid/index.d.ts.map +1 -0
  221. package/dist/uuid/index.js +2 -0
  222. package/dist/uuid/index.js.map +1 -0
  223. package/license +18 -0
  224. package/package.json +74 -0
  225. package/readme.md +697 -0
package/readme.md ADDED
@@ -0,0 +1,697 @@
1
+ # 🔐 Secure Crypto Toolkit
2
+
3
+ A comprehensive TypeScript cryptography toolkit for learning and understanding modern encryption, authentication, and security techniques. Implements multiple encryption modes, password utilities, OTP generation, and more with security best practices.
4
+
5
+ ## ⚠️ DISCLAIMER
6
+
7
+ **THIS LIBRARY IS PROVIDED FOR EDUCATIONAL AND PERSONAL USE ONLY.**
8
+
9
+ **THE AUTHOR(S) ACCEPT NO RESPONSIBILITY OR LIABILITY WHATSOEVER FOR:**
10
+
11
+ - Any security vulnerabilities or weaknesses in this code
12
+ - Data loss, corruption, or unauthorized access resulting from use of this library
13
+ - Any damages, direct or indirect, arising from the use of this software
14
+ - Compliance with security standards, regulations, or legal requirements
15
+ - Production use of this library in any context
16
+
17
+ **This library has NOT undergone professional security audits.** While it implements modern cryptographic practices, it may contain bugs, implementation flaws, or design weaknesses.
18
+
19
+ **For production systems handling sensitive data** (financial, healthcare, personal information, etc.), **you MUST use established, audited libraries:**
20
+
21
+ - `libsodium` / `sodium-native`
22
+ - `tweetnacl`
23
+ - Native Web Crypto API
24
+ - `bcrypt` / `argon2` for password hashing
25
+ - `otplib` for production OTP systems
26
+
27
+ **BY USING THIS SOFTWARE, YOU AGREE THAT:**
28
+
29
+ - You use it entirely at your own risk
30
+ - The author(s) have no obligation to provide support, updates, or security patches
31
+ - You are solely responsible for evaluating the security implications of using this code
32
+ - This library is intended for learning, experimentation, and low-risk personal projects only
33
+
34
+ ## 🎯 What You'll Learn
35
+
36
+ ### Encryption & Key Exchange
37
+
38
+ - **Symmetric encryption** (AES-256-GCM with password-based key derivation)
39
+ - **Asymmetric encryption** (RSA-OAEP envelope encryption)
40
+ - **Elliptic Curve Cryptography** (X25519 key exchange with ECDH)
41
+ - **Digital signatures** (Ed25519 for authentication)
42
+ - **Forward secrecy** (ephemeral keys)
43
+ - **Replay attack prevention** (timestamps)
44
+ - **Key derivation** (scrypt, HKDF)
45
+
46
+ ### Authentication & Identity
47
+
48
+ - **Secure password generation** (cryptographically random)
49
+ - **Password hashing and verification** (scrypt with automatic salt generation)
50
+ - **UUID generation** (v4, cryptographically random)
51
+ - **OTP generation** (HOTP and TOTP for 2FA)
52
+ - **HMAC-based authentication**
53
+
54
+ ### Utilities
55
+
56
+ - **Cryptographic hashing** (SHA-256, SHA-512, etc.)
57
+ - **HMAC operations** (keyed-hash message authentication)
58
+ - **Secure random number generation**
59
+
60
+ ### 🔐 See SECURITY.md for:
61
+
62
+ - Threat model
63
+ - Known limitations
64
+ - Security recommendations
65
+
66
+ ## 📦 Installation
67
+
68
+ ```bash
69
+ npm install simple-crypto-utils
70
+ ```
71
+
72
+ ## 🚀 Quick Start
73
+
74
+ ### 1. Password-Based Encryption (Symmetric)
75
+
76
+ ```typescript
77
+ import { encrypt, decrypt } from "simple-crypto-utils";
78
+
79
+ // Encrypt
80
+ const encrypted = await encrypt(
81
+ { type: "symmetric-password", password: "MyStr0ng!Pass123" },
82
+ "Secret message"
83
+ );
84
+
85
+ // Decrypt
86
+ const decrypted = await decrypt(
87
+ { type: "symmetric-password", password: "MyStr0ng!Pass123" },
88
+ encrypted.data
89
+ );
90
+
91
+ console.log(decrypted.data); // "Secret message"
92
+ ```
93
+
94
+ ### 2. Password Management
95
+
96
+ ```typescript
97
+ import {
98
+ generatePassword,
99
+ hashPassword,
100
+ verifyPassword,
101
+ } from "simple-crypto-utils";
102
+
103
+ // Generate secure password
104
+ const password = generatePassword(16); // "aB3$xK9@mPq2#R5z"
105
+
106
+ // Hash password for storage
107
+ const hashed = await hashPassword("user_password_123");
108
+ // Returns: "scrypt$16384$8$1$<salt>$<hash>"
109
+
110
+ // Verify password
111
+ const isValid = await verifyPassword("user_password_123", hashed);
112
+ console.log(isValid); // true
113
+ ```
114
+
115
+ ### 3. Two-Factor Authentication (OTP/TOTP)
116
+
117
+ ```typescript
118
+ import { generateOTP, generateTOTP } from "simple-crypto-utils";
119
+
120
+ // Generate one-time password (HOTP)
121
+ const otp = generateOTP(); // "123456"
122
+
123
+ // Generate time-based OTP (TOTP)
124
+ const secret = "BASE32ENCODEDSECRET";
125
+ const totp = generateTOTP(secret); // "654321" (changes every 30s)
126
+
127
+ // NOT YET IMPLEMENTED
128
+ // Verify TOTP with time window
129
+ const isValid = verifyTOTP(secret, "654321", { window: 1 });
130
+ console.log(isValid); // true if within time window
131
+ ```
132
+
133
+ ### 4. UUID Generation
134
+
135
+ ```typescript
136
+ import { generateUUID } from "simple-crypto-utils";
137
+
138
+ const id = generateUUID();
139
+ console.log(id); // "f47ac10b-58cc-4372-a567-0e02b2c3d479"
140
+ ```
141
+
142
+ ### 5. Hashing & HMAC
143
+
144
+ ```typescript
145
+ import { hash, hmac } from "simple-crypto-utils";
146
+
147
+ // Hash data
148
+ const dataHash = hash("sensitive data", "sha256");
149
+
150
+ // Create HMAC for authentication
151
+ const signature = hashHmac("message", "secret-key", "sha256");
152
+
153
+ // Verify HMAC
154
+ const signature = hashHmac(hashedMessage, "secret-key", "sha256");
155
+ ```
156
+
157
+ ### 6. Signature
158
+
159
+ ```typescript
160
+ // Using the class Key (recommend)
161
+ import { Key } from "simple-crypto-utils";
162
+
163
+ const keys = await Key.generate("sign");
164
+ console.log(keys);
165
+ // {publicKey:"Mc....", privateKey:"Mc....."}
166
+ ```
167
+
168
+ ### 7. Public Key Encryption (RSA Envelope)
169
+
170
+ ```typescript
171
+ import { encrypt, decrypt, generateRSAKeyPair } from "simple-crypto-utils";
172
+
173
+ // Generate keys
174
+ const { publicKey, privateKey } = generateRSAKeyPair();
175
+
176
+ // Encrypt for recipient
177
+ const encrypted = await encrypt(
178
+ { type: "sealEnvelope", recipientPublicKey: publicKey },
179
+ "Confidential data"
180
+ );
181
+
182
+ // Decrypt
183
+ const decrypted = await decrypt(
184
+ { type: "openEnvelope", recipientPrivateKey: privateKey },
185
+ encrypted.data
186
+ );
187
+ ```
188
+
189
+ ### 8. Secure Channel (ECDH with Forward Secrecy)
190
+
191
+ ```typescript
192
+ import { encrypt, decrypt, generateX25519KeyPair } from "simple-crypto-utils";
193
+
194
+ // Bob generates keys
195
+ const bob = generateX25519KeyPair();
196
+
197
+ // Alice sends to Bob
198
+ const encrypted = await encrypt(
199
+ { type: "secure-channel", recipientPublicKey: bob.publicKey },
200
+ "Private message"
201
+ );
202
+
203
+ // Bob decrypts
204
+ const decrypted = await decrypt(
205
+ { type: "secure-channel", recipientPrivateKey: bob.privateKey },
206
+ encrypted.data
207
+ );
208
+ ```
209
+
210
+ ### 9. Authenticated Channel (ECDH + Ed25519 Signatures)
211
+
212
+ ```typescript
213
+ import {
214
+ encrypt,
215
+ decrypt,
216
+ generateAuthenticatedKeySet,
217
+ } from "simple-crypto-utils";
218
+
219
+ // Generate keys for both parties
220
+ const alice = generateAuthenticatedKeySet();
221
+ const bob = generateAuthenticatedKeySet();
222
+
223
+ // Alice sends authenticated message to Bob
224
+ const encrypted = await encrypt(
225
+ {
226
+ type: "authenticated-channel",
227
+ recipientPublicKey: bob.encryption.publicKey,
228
+ senderPrivateKey: alice.signing.privateKey,
229
+ },
230
+ "Authenticated message"
231
+ );
232
+
233
+ // Bob verifies and decrypts
234
+ const decrypted = await decrypt(
235
+ {
236
+ type: "authenticated-channel",
237
+ recipientPrivateKey: bob.encryption.privateKey,
238
+ senderPublicKey: alice.signing.publicKey,
239
+ },
240
+ encrypted.data
241
+ );
242
+
243
+ console.log(decrypted.metadata.authenticated); // true
244
+ ```
245
+
246
+ ## 📁 File Encryption
247
+
248
+ All encryption modes support file encryption with streaming for memory efficiency:
249
+
250
+ ```typescript
251
+ import { encrypt, decrypt } from "simple-crypto-utils";
252
+
253
+ // Encrypt file
254
+ await encrypt(
255
+ { type: "symmetric-password", password: "SecurePass123!" },
256
+ undefined,
257
+ "./sensitive.pdf",
258
+ "./sensitive.pdf.enc"
259
+ );
260
+
261
+ // Decrypt file
262
+ await decrypt(
263
+ { type: "symmetric-password", password: "SecurePass123!" },
264
+ undefined,
265
+ "./sensitive.pdf.enc",
266
+ "./sensitive-decrypted.pdf"
267
+ );
268
+ ```
269
+
270
+ ## 🔒 Security Features
271
+
272
+ ### ✅ What This Library Provides
273
+
274
+ | Feature | Description |
275
+ | ----------------------- | ----------------------------------------------- |
276
+ | **Confidentiality** | AES-256-GCM encryption |
277
+ | **Integrity** | Authenticated encryption with GCM auth tags |
278
+ | **Forward Secrecy** | Ephemeral ECDH keys (secure-channel mode) |
279
+ | **Authentication** | Ed25519 signatures (authenticated-channel mode) |
280
+ | **Replay Protection** | Timestamp validation (optional) |
281
+ | **Key Validation** | Automatic verification of key types and formats |
282
+ | **Version Control** | Format versioning for backward compatibility |
283
+ | **Password Protection** | scrypt KDF with automatic salt generation |
284
+ | **Secure Random** | Cryptographically secure random generation |
285
+ | **Time-based Security** | TOTP with configurable time windows |
286
+
287
+ ### Security Properties by Feature
288
+
289
+ #### Encryption Modes
290
+
291
+ | Mode | Confidentiality | Integrity | Authentication | Forward Secrecy |
292
+ | ----------------------- | --------------- | --------- | -------------- | --------------- |
293
+ | `symmetric-password` | ✅ | ✅ | ❌ | N/A |
294
+ | `sealEnvelope` | ✅ | ✅ | ❌ | ❌ |
295
+ | `secure-channel` | ✅ | ✅ | ❌ | ✅ |
296
+ | `authenticated-channel` | ✅ | ✅ | ✅ | ✅ |
297
+
298
+ #### Authentication Features
299
+
300
+ | Feature | Algorithm | Use Case |
301
+ | ------------------- | --------- | ---------------------------- |
302
+ | Password Hashing | scrypt | User authentication |
303
+ | HOTP | HMAC-SHA1 | Counter-based 2FA |
304
+ | TOTP | HMAC-SHA1 | Time-based 2FA (Google Auth) |
305
+ | UUID | Random v4 | Unique identifiers |
306
+ | Password Generation | Random | Secure password creation |
307
+
308
+ ## 🛡️ Strict Mode
309
+
310
+ Enable strict mode for maximum security enforcement:
311
+
312
+ ```typescript
313
+ const encrypted = await encrypt(
314
+ {
315
+ type: "symmetric-password",
316
+ password: "pass",
317
+ strictMode: true, // Enforces strong passwords, all validations
318
+ },
319
+ "data"
320
+ );
321
+ ```
322
+
323
+ Strict mode enforces:
324
+
325
+ - Strong password requirements (uppercase, lowercase, numbers, special chars)
326
+ - Timestamp validation (prevents replay attacks)
327
+ - All security checks enabled
328
+
329
+ ## ⏱️ Replay Attack Prevention
330
+
331
+ Secure and authenticated channels include timestamps by default:
332
+
333
+ ```typescript
334
+ // Encrypt with timestamp (default)
335
+ const encrypted = await encrypt(
336
+ {
337
+ type: "secure-channel",
338
+ recipientPublicKey: pubKey,
339
+ includeTimestamp: true, // default
340
+ },
341
+ "time-sensitive data"
342
+ );
343
+
344
+ // Decrypt with validation (default: 5 minute window)
345
+ const decrypted = await decrypt(
346
+ {
347
+ type: "secure-channel",
348
+ recipientPrivateKey: privKey,
349
+ validateTimestamp: true, // default
350
+ },
351
+ encrypted.data
352
+ );
353
+ ```
354
+
355
+ ## 🔑 API Reference
356
+
357
+ ### Password Utilities
358
+
359
+ ```typescript
360
+ // Generate cryptographically secure password
361
+ generatePassword(length: number = 16, options?: {
362
+ uppercase?: boolean; // Default: true
363
+ lowercase?: boolean; // Default: true
364
+ numbers?: boolean; // Default: true
365
+ symbols?: boolean; // Default: true
366
+ }): string
367
+
368
+ // Hash password with scrypt
369
+ hashPassword(password: string, options?: {
370
+ N?: number; // CPU/memory cost (default: 16384)
371
+ r?: number; // Block size (default: 8)
372
+ p?: number; // Parallelization (default: 1)
373
+ keylen?: number; // Output length (default: 32)
374
+ }): Promise<string>
375
+
376
+ // Verify password against hash
377
+ verifyPassword(password: string, hash: string): Promise<boolean>
378
+ ```
379
+
380
+ ### OTP/TOTP
381
+
382
+ ```typescript
383
+ // Generate HMAC-based OTP
384
+ generateOTP(secret: string, counter: number, digits?: number): string
385
+
386
+ // Generate time-based OTP
387
+ generateTOTP(secret: string, options?: {
388
+ time?: number; // Unix timestamp (default: Date.now())
389
+ step?: number; // Time step in seconds (default: 30)
390
+ digits?: number; // OTP length (default: 6)
391
+ }): string
392
+
393
+ // Verify TOTP with time window
394
+ verifyTOTP(secret: string, token: string, options?: {
395
+ time?: number;
396
+ step?: number;
397
+ window?: number; // Allow ±N time steps (default: 1)
398
+ }): boolean
399
+ ```
400
+
401
+ ### Hashing & HMAC
402
+
403
+ ```typescript
404
+ // Hash data
405
+ hash(data: string, algorithm?: string): string // Default: sha256
406
+
407
+ // Generate HMAC
408
+ hmac(data: string, key: string, algorithm?: string): string // Default: sha256
409
+ ```
410
+
411
+ ### UUID
412
+
413
+ ```typescript
414
+ // Generate UUID v4
415
+ generateUUID(): string
416
+ ```
417
+
418
+ ### Encryption Options
419
+
420
+ _(See original documentation for encryption options)_
421
+
422
+ ## 🧪 Testing
423
+
424
+ ```bash
425
+ npm test # Run all tests
426
+ npm run test:security # Security-specific tests
427
+ npm run test:coverage # Coverage report
428
+ npm run test:password # Password utility tests
429
+ npm run test:otp # OTP/TOTP tests
430
+ ```
431
+
432
+ ## 🎓 Educational Notes
433
+
434
+ ### When to Use Each Feature?
435
+
436
+ ```
437
+ Encryption
438
+ ├─ symmetric-password: Personal file encryption, backups
439
+ ├─ sealEnvelope: Email encryption, legacy compatibility
440
+ ├─ secure-channel: Secure messaging, forward secrecy
441
+ └─ authenticated-channel: Critical communications, signed documents
442
+
443
+ Authentication
444
+ ├─ Password hashing: User account security
445
+ ├─ HOTP: Hardware tokens, API counters
446
+ ├─ TOTP: Mobile 2FA apps (Google Authenticator)
447
+ └─ HMAC: API signatures, webhook verification
448
+
449
+ Utilities
450
+ ├─ UUID: Database IDs, session tokens
451
+ ├─ Password generation: Temporary passwords, API keys
452
+ └─ Hashing: Data integrity, checksums
453
+ ```
454
+
455
+ ### Cryptographic Primitives Used
456
+
457
+ - **AES-256-GCM**: Authenticated encryption
458
+ - **scrypt**: Password-based key derivation (memory-hard)
459
+ - **RSA-OAEP**: Asymmetric encryption
460
+ - **X25519**: Elliptic curve Diffie-Hellman
461
+ - **Ed25519**: Digital signatures
462
+ - **HMAC-SHA1/SHA256**: Message authentication
463
+ - **HKDF**: Key derivation from shared secrets
464
+ - **CSPRNG**: Cryptographically secure random generation
465
+
466
+ ## 🐛 Common Issues
467
+
468
+ ### Password Issues
469
+
470
+ - **Weak password errors**: Use `strictMode: false` for testing or generate with `generatePassword()`
471
+ - **Hash verification fails**: Ensure you're using the same scrypt parameters
472
+
473
+ ### OTP Issues
474
+
475
+ - **TOTP mismatch**: Check system time synchronization (NTP)
476
+ - **Time window errors**: Increase `window` parameter for clock drift
477
+
478
+ ### Encryption Issues
479
+
480
+ - **Invalid key errors**: Ensure correct key type (RSA vs X25519 vs Ed25519)
481
+ - **Message expired errors**: Message older than 5 minutes or clocks not synchronized
482
+
483
+ ## 🛠️ Development
484
+
485
+ ### For Contributors
486
+
487
+ ```bash
488
+ # Clone repository
489
+ git clone https://github.com/yourusername/simple-crypto-utils.git
490
+ cd simple-crypto-utils
491
+
492
+ # Install dependencies
493
+ npm install
494
+
495
+ # Build
496
+ npm run build
497
+
498
+ # Run tests
499
+ npm test
500
+
501
+ # Run tests in watch mode
502
+ npm run test:watch
503
+
504
+ # Check coverage
505
+ npm run test:coverage
506
+ ```
507
+
508
+ ### Project Structure
509
+
510
+ ```
511
+ src/
512
+ |-- crypto/
513
+ | |-- encrypt.ts # Encryption logic
514
+ | |-- decrypt.ts # Decryption logic
515
+ | |-- index.ts # Export point and class Crypto
516
+ ├── hash/
517
+ | |-- hash.ts # Simple hashign
518
+ | |-- hashHmac.ts # Hashing using hmac
519
+ | |-- verifyHmac.ts # Verify hmac hash time safe
520
+ | |-- index.ts # Export point no class for the moment
521
+ ├── keys.ts
522
+ | |-- aes.ts # Generation random aes key & iv
523
+ | |-- authenticate.ts # Generation X25519 key pair & Ed25519 key pair
524
+ | |-- ecdh.ts # Generation X25519 key pair
525
+ | |-- ed25519.ts # Generation ED25519 key pair
526
+ | |-- rsa.ts # Generation RSA key pair
527
+ | |-- x25519.ts # Generation X25519 key pair
528
+ | |-- index.ts # Export point and class Key
529
+ ├── otp
530
+ | |-- otp.ts # Generation OTP (no hash or verify for the moment)
531
+ | |-- totp.ts # Generation TOTP (no verify for the moment)
532
+ | |-- index.ts # Export point no class for the moment
533
+ ├── password
534
+ | |-- generate.ts # Generation safe & random password
535
+ | |-- hash.ts # Hashing the password with scrypt
536
+ | |-- verify.ts # Verify the hashed password
537
+ | |-- index.ts # Export point no class for the moment
538
+ ├── signature
539
+ | |-- sign.ts # Sign logic
540
+ | |-- verify.ts # Verify logic
541
+ | |-- index.ts # Export point and class Signer
542
+ ├── index.ts # Public API
543
+ └── examples.ts # Examples functions
544
+ ```
545
+
546
+ ### Generate Test Keys
547
+
548
+ Create a script to generate keys for testing:
549
+
550
+ ```typescript
551
+ // generate-keys.js
552
+ import { Key } from "simple-crypto-utils";
553
+
554
+ const fs = require("fs");
555
+
556
+ // Create keys directory
557
+ if (!fs.existsSync("./keys")) {
558
+ fs.mkdirSync("./keys", { mode: 0o700 });
559
+ }
560
+
561
+ // Generate keys
562
+ const rsa = Key.generate("seal");
563
+ const x25519 = Key.generate("secure-channel");
564
+ const auth = Key.generate("sign");
565
+
566
+ // Save keys (restrict permissions)
567
+ fs.writeFileSync("./keys/rsa-public.key", rsa.publicKey);
568
+ fs.writeFileSync("./keys/rsa-private.key", rsa.privateKey, { mode: 0o600 });
569
+ fs.writeFileSync("./keys/x25519-public.key", x25519.publicKey);
570
+ fs.writeFileSync("./keys/x25519-private.key", x25519.privateKey, {
571
+ mode: 0o600,
572
+ });
573
+
574
+ console.log("✅ Keys generated in ./keys/");
575
+ ```
576
+
577
+ **Important:** Add to `.gitignore`:
578
+
579
+ ```
580
+ keys/
581
+ *.key
582
+ .env
583
+ ```
584
+
585
+ ### Environment Variables
586
+
587
+ For testing, create `.env` (don't commit):
588
+
589
+ ```bash
590
+ # Test credentials (NOT for production)
591
+ TEST_PASSWORD=TestPassword123!
592
+ TOTP_TEST_SECRET=JBSWY3DPEHPK3PXP
593
+
594
+ # Node environment
595
+ NODE_ENV=development
596
+ ```
597
+
598
+ ### Running Examples
599
+
600
+ ```bash
601
+ # Run example file
602
+ node dist/examples.js
603
+
604
+ # Or with ts-node
605
+ npx ts-node src/examples.ts
606
+ ```
607
+
608
+ ### Publishing
609
+
610
+ ```bash
611
+ # Login to npm
612
+ npm login
613
+
614
+ # Dry run
615
+ npm publish --dry-run
616
+
617
+ # Publish
618
+ npm publish
619
+ ```
620
+
621
+ ## 🤝 Contributing
622
+
623
+ This is an educational project. Contributions welcome:
624
+
625
+ - Bug fixes
626
+ - Additional cryptographic features
627
+ - Documentation improvements
628
+ - More test cases
629
+ - Security analysis reports
630
+
631
+ Please do NOT:
632
+
633
+ - Remove security checks
634
+ - Weaken cryptographic parameters
635
+ - Add backdoors or intentional vulnerabilities
636
+
637
+ ### Contributing Guidelines
638
+
639
+ 1. Fork the repository
640
+ 2. Create a feature branch (`git checkout -b feature/amazing`)
641
+ 3. Write tests for new features
642
+ 4. Ensure all tests pass (`npm test`)
643
+ 5. Update documentation
644
+ 6. Submit pull request
645
+
646
+ **Don't:**
647
+
648
+ - Remove security checks
649
+ - Weaken cryptographic parameters
650
+ - Add backdoors or vulnerabilities
651
+ - Commit private keys or secrets
652
+
653
+ ## 📝 License
654
+
655
+ MIT License
656
+
657
+ Copyright (c) [2026] [Alessio Galtelli]
658
+
659
+ Permission is hereby granted, free of charge, to any person obtaining a copy
660
+ of this software and associated documentation files (the "Software"), to deal
661
+ in the Software without restriction, including without limitation the rights
662
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
663
+ copies of the Software, and to permit persons to whom the Software is
664
+ furnished to do so, subject to the following conditions:
665
+
666
+ **THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
667
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
668
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
669
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
670
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
671
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
672
+ SOFTWARE.**
673
+
674
+ ## 🙏 Acknowledgments
675
+
676
+ Built with:
677
+
678
+ - Node.js `crypto` module (native cryptographic primitives)
679
+ - Inspired by libsodium, Signal Protocol, OWASP guidelines, and RFC specifications
680
+
681
+ Educational resources:
682
+
683
+ - [RFC 4226 (HOTP)](https://tools.ietf.org/html/rfc4226)
684
+ - [RFC 6238 (TOTP)](https://tools.ietf.org/html/rfc6238)
685
+ - [Signal Protocol Specification](https://signal.org/docs/)
686
+ - [NIST Guidelines on Cryptography](https://csrc.nist.gov/)
687
+
688
+ ## 📚 Further Reading
689
+
690
+ - [Cryptography Engineering (Book)](https://www.schneier.com/books/cryptography_engineering/)
691
+ - [OWASP Password Storage Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html)
692
+ - [OWASP Authentication Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html)
693
+ - [Soatok's Crypto Blog](https://soatok.blog/)
694
+
695
+ ---
696
+
697
+ **⚠️ FINAL REMINDER**: This library is for learning and experimentation. Cryptography is extremely difficult to implement correctly. For anything important, use professionally audited libraries. The authors accept absolutely no responsibility for any consequences of using this code.