nestjs-cryptography 2.2.2 → 3.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 (64) hide show
  1. package/README.md +147 -0
  2. package/dist/cryptography.service.d.ts +21 -23
  3. package/dist/cryptography.service.js +82 -82
  4. package/dist/interfaces/cryptography-options.interface.d.ts +1 -1
  5. package/dist/interfaces/generic-options.interface.d.ts +5 -0
  6. package/dist/interfaces/generic-options.interface.js +2 -0
  7. package/dist/interfaces/index.d.ts +1 -0
  8. package/dist/interfaces/index.js +1 -0
  9. package/package.json +16 -15
  10. package/wiki/README.md +41 -0
  11. package/wiki/babel.config.js +3 -0
  12. package/wiki/docs/Internals/_category_.json +7 -0
  13. package/wiki/docs/Internals/create-safe-random-data.mdx +41 -0
  14. package/wiki/docs/Internals/create-secure-hmac.mdx +31 -0
  15. package/wiki/docs/Internals/symmetric-data-encrypt.mdx +103 -0
  16. package/wiki/docs/Internals/symmetric-secure-data-encrypt.mdx +161 -0
  17. package/wiki/docs/api-reference/_category_.json +7 -0
  18. package/wiki/docs/api-reference/settings.mdx +199 -0
  19. package/wiki/docs/guides/_category_.json +7 -0
  20. package/wiki/docs/guides/generics.mdx +170 -0
  21. package/wiki/docs/guides/hashing.mdx +258 -0
  22. package/wiki/docs/guides/hmac.mdx +271 -0
  23. package/wiki/docs/guides/key-derivation.mdx +101 -0
  24. package/wiki/docs/guides/password-hashing.mdx +136 -0
  25. package/wiki/docs/guides/symmetric-encryption.mdx +272 -0
  26. package/wiki/docs/intro.mdx +148 -0
  27. package/wiki/docusaurus.config.ts +138 -0
  28. package/wiki/package.json +48 -0
  29. package/wiki/sidebars.ts +20 -0
  30. package/wiki/src/common/timing-attack.mdx +3 -0
  31. package/wiki/src/common/tips.mdx +18 -0
  32. package/wiki/src/components/GenerateHexButton/index.tsx +35 -0
  33. package/wiki/src/components/GenerateHexButton/styles.module.css +10 -0
  34. package/wiki/src/components/GenericLabel/index.tsx +19 -0
  35. package/wiki/src/components/HomepageFeatures/index.tsx +70 -0
  36. package/wiki/src/components/HomepageFeatures/styles.module.css +11 -0
  37. package/wiki/src/components/RecommendedLabel/index.tsx +19 -0
  38. package/wiki/src/components/RequiredLabel/index.tsx +12 -0
  39. package/wiki/src/css/custom.css +30 -0
  40. package/wiki/src/pages/index.module.css +23 -0
  41. package/wiki/src/pages/index.tsx +43 -0
  42. package/wiki/src/pages/markdown-page.md +7 -0
  43. package/wiki/static/.nojekyll +0 -0
  44. package/wiki/static/img/gear_api.png +0 -0
  45. package/wiki/static/img/logo.svg +1 -0
  46. package/wiki/static/img/nestjs_favicon.ico +0 -0
  47. package/wiki/static/img/node_crypto.png +0 -0
  48. package/wiki/static/img/phc_logo.png +0 -0
  49. package/wiki/static/img/profile.png +0 -0
  50. package/wiki/versioned_docs/version-2.x/Internals/_category_.json +8 -0
  51. package/wiki/versioned_docs/version-2.x/Internals/create-secure-hmac.mdx +30 -0
  52. package/wiki/versioned_docs/version-2.x/Internals/symmetric-secure-data-encrypt.mdx +160 -0
  53. package/wiki/versioned_docs/version-2.x/api-reference/_category_.json +8 -0
  54. package/wiki/versioned_docs/version-2.x/api-reference/settings.mdx +197 -0
  55. package/wiki/versioned_docs/version-2.x/guides/_category_.json +7 -0
  56. package/wiki/versioned_docs/version-2.x/guides/generics.mdx +133 -0
  57. package/wiki/versioned_docs/version-2.x/guides/hashing.mdx +229 -0
  58. package/wiki/versioned_docs/version-2.x/guides/hmac.mdx +198 -0
  59. package/wiki/versioned_docs/version-2.x/guides/key-derivation.mdx +98 -0
  60. package/wiki/versioned_docs/version-2.x/guides/password-hashing.mdx +132 -0
  61. package/wiki/versioned_docs/version-2.x/guides/symmetric-encryption.mdx +107 -0
  62. package/wiki/versioned_docs/version-2.x/intro.mdx +148 -0
  63. package/wiki/versioned_sidebars/version-2.x-sidebars.json +8 -0
  64. package/wiki/versions.json +3 -0
@@ -0,0 +1,101 @@
1
+ ---
2
+ title: Key Derivation
3
+ sidebar_label: Key Derivation
4
+ sidebar_position: 2
5
+ description: Methods to use KDF (Key Derivation Function)
6
+ ---
7
+
8
+ import RequiredLabel from '@site/src/components/RequiredLabel';
9
+ import Tips from '@site/src/common/tips.mdx'
10
+
11
+
12
+ The upcoming section will delve into methods for generating cryptographically secure keys from user-provided passwords.
13
+ This process is crucial because raw passwords are often not secure enough for cryptographic purposes
14
+ due to their relatively low entropy. By using a key derivation function, we can transform these passwords
15
+ into secure keys that are suitable for encryption, hashing, or other cryptographic operations.
16
+
17
+ We will be using **Argon2** for this purpose, which is one of the most secure and modern key derivation functions available.
18
+ Argon2 is specifically designed to resist attacks such as brute force and side-channel attacks
19
+ by incorporating memory-hard and CPU-intensive computations. This makes it an ideal choice for
20
+ converting user passwords into robust cryptographic keys.
21
+
22
+
23
+
24
+ ## Derive a key
25
+
26
+ Method to derive a user supplied key into a cryptographically secure one.
27
+
28
+ ### `deriveMasterKey`
29
+
30
+
31
+ ```typescript
32
+ public deriveMasterKey (
33
+ masterKey: string | Buffer,
34
+ salt: Buffer,
35
+ length: number,
36
+ ): Promise<Buffer>;
37
+ ```
38
+
39
+
40
+ #### **Parameters:**
41
+
42
+ | Name | Type | Default | Description |
43
+ |--------------------------------|------------------|----------------------------|-----------------------------------------------------|
44
+ | **masterKey** <RequiredLabel/> | string \| Buffer | false | String or buffer of the key to derive |
45
+ | **salt** <RequiredLabel/> | Buffer | false | Salt to increase the security of the key derivation |
46
+ | **length** | number | [`kdf.outputKeyLength`][3] | The desired derived output key length |
47
+
48
+
49
+ #### **Module Parameters:**
50
+
51
+ :::info
52
+
53
+ Internally, this method uses certain parameters that are defined at the module level during initialization,
54
+ as we have seen [previously][2]. The internal parameters used and their corresponding configuration keys are as follows:
55
+
56
+ - **hashLength**: Specifies the length of the resulting derived key.
57
+ If this option is not provided, then it is set via [`kdf.outputKeyLength`][3]
58
+ and determines the size of the final hash in bytes.
59
+
60
+ - **type**: Defines the variant of Argon2 to use (_argon2i_, _argon2d_, or _argon2id_).
61
+ This is configured using [`kdf.argon2Type`][4].
62
+
63
+ - **memoryCost**: Sets the amount of memory (in KB) that the algorithm will use during the hashing process.
64
+ This value is determined by [`kdf.memoryCost`][5] and plays a critical role in resisting brute-force attacks.
65
+
66
+ - **timeCost**: Specifies the number of iterations or the amount of computational work Argon2 will perform.
67
+ It is defined via [`kdf.timeCost`][6] to ensure a balance between security and performance.
68
+
69
+ :::
70
+
71
+
72
+ #### **Outputs:**
73
+
74
+ As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
75
+
76
+
77
+ #### **Usage:**
78
+ ```typescript
79
+ async deriveSecureKeyFromMasterKey(
80
+ key: string,
81
+ ): Promise<string> {
82
+ const keyBuffer = Buffer.from(key, 'utf-8');
83
+ const salt = this.cryptographyService.generateSymmetricKey(128);
84
+ const derivedKey = await this.cryptographyService.deriveMasterKey(keyBuffer, salt.export(), 256)
85
+ return derivedKey.toString('hex')
86
+ }
87
+ ```
88
+
89
+
90
+
91
+
92
+ <Tips />
93
+
94
+
95
+
96
+ [1]: https://nodejs.org/api/buffer.html
97
+ [2]: ../intro#configuration
98
+ [3]: ../api-reference/settings#outputkeylength
99
+ [4]: ../api-reference/settings#argon2type
100
+ [5]: ../api-reference/settings#memorycost
101
+ [6]: ../api-reference/settings#timecost
@@ -0,0 +1,136 @@
1
+ ---
2
+ title: Password Hashing
3
+ sidebar_label: Password Hashing
4
+ sidebar_position: 4
5
+ description: Methods to securely hash passwords (Argon2)
6
+ ---
7
+
8
+ import RequiredLabel from '@site/src/components/RequiredLabel';
9
+ import RecommendedLabel from '@site/src/components/RecommendedLabel';
10
+ import GenericLabel from '@site/src/components/GenericLabel';
11
+ import Tips from '@site/src/common/tips.mdx'
12
+ import TimingAttack from '@site/src/common/timing-attack.mdx'
13
+
14
+ In this section, we will explore how to securely hash passwords using [Argon2][2],
15
+ one of the most advanced and secure password-hashing algorithms available today.
16
+ Developed as a winner of the [Password Hashing Competition (PHC)][1], Argon2 is designed to protect against brute-force attacks,
17
+ both by consuming significant computational resources and by utilizing memory-hard functions.
18
+ This makes it a preferred choice for modern security practices.
19
+
20
+
21
+
22
+ ## Create Argon2 hash
23
+
24
+ Method to create a hash of a text/password using Argon2 algorithm.
25
+
26
+ ### `createArgonHashFromPassword`
27
+
28
+ ```typescript
29
+ public createArgonHashFromPassword (
30
+ data: string | Buffer,
31
+ ): string;
32
+ ```
33
+
34
+
35
+ **Parameters:**
36
+
37
+ | Name | Type | Default | Description |
38
+ |---------------------------|------------------|---------|------------------|
39
+ | **data** <RequiredLabel/> | string \| Buffer | | Password to hash |
40
+
41
+
42
+ **Module Parameters:**
43
+
44
+ :::info
45
+
46
+ Internally, this method uses certain parameters that are defined at the module level during initialization,
47
+ as we have seen [previously][4]. The internal parameters used and their corresponding configuration keys are as follows:
48
+
49
+ - **hashLength**: Specifies the length of the resulting hash.
50
+ This is set via [`hashing.password.outputKeyLength`][5] and determines the size of the final hash in bytes.
51
+
52
+ - **type**: Defines the variant of Argon2 to use (_argon2i_, _argon2d_, or _argon2id_).
53
+ This is configured using [`hashing.password.argon2Type`][6].
54
+
55
+ - **memoryCost**: Sets the amount of memory (in KB) that the algorithm will use during the hashing process.
56
+ This value is determined by [`hashing.password.memoryCost`][7] and plays a critical role in resisting brute-force attacks.
57
+
58
+ - **timeCost**: Specifies the number of iterations or the amount of computational work Argon2 will perform.
59
+ It is defined via [`hashing.password.timeCost`][8] to ensure a balance between security and performance.
60
+
61
+ :::
62
+
63
+
64
+ **Outputs:**
65
+
66
+ As output, it will return a string of type: `$argon2i$v=19$m=4096,t=3,p=1$c2g56.....jk7A`
67
+
68
+ > Where the options `argon2i`, `v=19`, `m=4096`, `t=3` and `p=1` may vary
69
+ depending on the [options][3] supplied to CryptographyModule when it has been [configured][4].
70
+
71
+
72
+ **Usage:**
73
+ ```typescript
74
+ async secureUserPassword(
75
+ plainPassword: string,
76
+ ): Promise<string> {
77
+ const _buffer = Buffer.from(plainPassword, 'utf-8');
78
+ const hashedPassword = await this.cryptographyService.createArgonHashFromPassword(_buffer);
79
+ return hashedPassword.toString();
80
+ }
81
+ ```
82
+
83
+
84
+
85
+ ## Verify Argon2 hash
86
+
87
+ Method to verify if an existing Argon2 hash matches the desired text/password.
88
+
89
+ ### `verifyArgonHashFromPassword`
90
+
91
+ ```typescript
92
+ public verifyArgonHashFromPassword (
93
+ hash: string,
94
+ data: string | Buffer,
95
+ ): Promise<boolean>;
96
+ ```
97
+
98
+ **Parameters:**
99
+
100
+ | Name | Type | Default | Description |
101
+ |---------------------------|------------------|---------|-----------------------------|
102
+ | **hash** <RequiredLabel/> | string | | String of the existing hash |
103
+ | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to verify |
104
+
105
+ **Outputs:**
106
+
107
+ As output, it will return `true` if both matches, or `false` if not.
108
+
109
+
110
+ **Usage:**
111
+ ```typescript
112
+ async checkUserPassword(
113
+ plainPassword: string,
114
+ hashedPassword: string
115
+ ): Promise<boolean> {
116
+ const _buffer = Buffer.from(plainPassword, 'utf-8');
117
+ return await this.cryptographyService.verifyArgonHashFromPassword(hashedPassword, plainPassword)
118
+ }
119
+ ```
120
+
121
+
122
+ <Tips />
123
+
124
+
125
+
126
+
127
+ [1]: https://www.password-hashing.net
128
+ [2]: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
129
+
130
+ [3]: ../api-reference/settings
131
+ [4]: ../intro#configuration
132
+
133
+ [5]: ../api-reference/settings#outputkeylength-1
134
+ [6]: ../api-reference/settings#argon2type-1
135
+ [7]: ../api-reference/settings#memorycost-1
136
+ [8]: ../api-reference/settings#timecost-1
@@ -0,0 +1,272 @@
1
+ ---
2
+ title: Symmetric Encryption
3
+ sidebar_label: Symmetric Encryption
4
+ sidebar_position: 6
5
+ description: Methods to securely encrypt data (AES-256-GCM)
6
+ ---
7
+
8
+ import RequiredLabel from '@site/src/components/RequiredLabel';
9
+ import RecommendedLabel from '@site/src/components/RecommendedLabel';
10
+ import GenericLabel from '@site/src/components/GenericLabel';
11
+ import Tips from '@site/src/common/tips.mdx'
12
+ import TimingAttack from '@site/src/common/timing-attack.mdx'
13
+
14
+ In this section, we will discuss symmetric encryption and decryption using AES-256-GCM,focusing on best practices to ensure robust security.
15
+ AES-256-GCM is a widely used and highly secure cryptographic algorithm, but its strength depends heavily on proper implementation.
16
+ Key best practices include never reusing initialization vectors (IVs), as doing so can compromise the encryption's integrity.
17
+ It is also crucial to always derive a secure encryption key from the user-provided key using a strong key derivation function
18
+ like Argon2 or HKDF. In certain cases, it’s recommended to encapsulate the Data Encryption Key (DEK) by encrypting it separately,
19
+ providing an additional layer of security for sensitive operations.
20
+ Following these principles ensures that your symmetric encryption implementations remain secure and resilient against common cryptographic attacks.
21
+
22
+
23
+ ## Symmetric secure data encrypt
24
+
25
+ #### <RecommendedLabel />
26
+
27
+ Method to encrypt data using AES-256-GCM with a randomly generated Data Encryption Key (DEK).
28
+ It ensures security by generating unique IVs and salts using the [`createSafeRandomData`][4], securely deriving encryption keys,
29
+ and encrypting the DEK using a master key.
30
+ The final output is a concatenation of the encrypted DEK and the encrypted data,
31
+ ensuring both confidentiality and key encapsulation.
32
+
33
+ ### `symmetricSecureDataEncrypt`
34
+
35
+ ```typescript
36
+ public symmetricSecureDataEncrypt (
37
+ data: string | Buffer,
38
+ options?: GenericOptionsInterface,
39
+ ): Promise<Buffer>;
40
+ ```
41
+
42
+ **Parameters:**
43
+
44
+ | Name | Type | Default | Description |
45
+ |---------------------------|----------------------------|---------|------------------------------------------------------------------|
46
+ | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to encrypt |
47
+ | **options** | [GenericOptions](#options) | `{}` | Optional configuration object for input data encoding and output |
48
+
49
+ #### **Options:**
50
+
51
+ | Name | Type | Default | Description |
52
+ |-------------------|-----------------------|---------|-------------------------------------------------------------------|
53
+ | inputDataEncoding | [`BufferEncoding`][3] | | Specifies the encoding of the input data (e.g., 'hex', 'base64'). |
54
+
55
+ **Outputs:**
56
+
57
+ As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
58
+
59
+ :::info
60
+
61
+ The resulting buffer contains: `[CIPHERED_DEK + CIPHERED_DATA]`
62
+ - And **CIPHERED_DEK** buffer part contains: `[IV + SALT + AUTH_TAG + CIPHERED_DATA]`
63
+ - And **CIPHERED_DATA** buffer part contains: `[IV + SALT + AUTH_TAG + CIPHERED_DATA]`
64
+
65
+ [Click here to see more in deep how it works][6]
66
+
67
+ :::
68
+
69
+ #### **Usage:**
70
+ ```typescript
71
+ async exampleEncrypt(
72
+ data: string,
73
+ ): Promise<string> {
74
+ const encryptedData = await this.cryptographyService.symmetricSecureDataEncrypt(
75
+ data,
76
+ {
77
+ inputDataEncoding: 'utf-8',
78
+ },
79
+ );
80
+ return encryptedData.toString('hex')
81
+ }
82
+ ```
83
+
84
+
85
+ [//]: #--------------------#
86
+
87
+
88
+ ## Symmetric secure data decrypt
89
+
90
+ #### <RecommendedLabel />
91
+
92
+ Method to decrypt data that was encrypted using the method [`symmetricSecureDataEncrypt`][2]
93
+
94
+ :::warning
95
+
96
+ Remember that the previous data must have been encrypted using [`symmetricSecureDataEncrypt`][2] method.
97
+
98
+ :::
99
+
100
+
101
+ ### `symmetricSecureDataDecrypt`
102
+
103
+ ```typescript
104
+ public symmetricSecureDataDecrypt (
105
+ data: string | Buffer
106
+ ): Promise<Buffer>;
107
+ ```
108
+
109
+ **Parameters:**
110
+
111
+ | Name | Type | Default | Description |
112
+ |---------------------------|------------------------------|---------|------------------------------------------------------------------|
113
+ | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to decrypt |
114
+ | **options** | [GenericOptions](#options-1) | `{}` | Optional configuration object for input data encoding and output |
115
+
116
+ #### **Options:**
117
+
118
+ | Name | Type | Default | Description |
119
+ |-------------------|-----------------------|---------|-------------------------------------------------------------------|
120
+ | inputDataEncoding | [`BufferEncoding`][3] | | Specifies the encoding of the input data (e.g., 'hex', 'base64'). |
121
+
122
+ **Outputs:**
123
+
124
+ As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
125
+
126
+
127
+ #### **Usage:**
128
+ ```typescript
129
+ async exampleDecrypt(
130
+ data: string,
131
+ ): Promise<string> {
132
+ const decryptedData = await this.cryptographyService.symmetricSecureDataDecrypt(
133
+ data,
134
+ {
135
+ inputDataEncoding: 'hex',
136
+ },
137
+ );
138
+ return decryptedData.toString('utf-8')
139
+ }
140
+ ```
141
+
142
+
143
+ [//]: #--------------------#
144
+
145
+
146
+ ## Symmetric data encrypt
147
+
148
+ #### <GenericLabel />
149
+
150
+ Method to encrypt data using AES-256-GCM and using unique IVs and salts using the [`createSafeRandomData`][4],
151
+ and deriving the encryption key using Argon2 KDF.
152
+
153
+ This is the internal method used to encrypt the data and the DEK when using [`symmetricSecureDataEncrypt`](#symmetricsecuredataencrypt)
154
+
155
+ ### `symmetricDataEncrypt`
156
+
157
+ ```typescript
158
+ public symmetricDataEncrypt (
159
+ data: string | Buffer,
160
+ key: string | Buffer,
161
+ options?: GenericOptionsInterface,
162
+ ): Promise<Buffer>;
163
+ ```
164
+
165
+ **Parameters:**
166
+
167
+ | Name | Type | Default | Description |
168
+ |---------------------------|------------------------------|---------|------------------------------------------------------------------|
169
+ | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to encrypt |
170
+ | **key** <RequiredLabel/> | string \| Buffer | | String or buffer of the key to use |
171
+ | **options** | [GenericOptions](#options-2) | `{}` | Optional configuration object for input data encoding and output |
172
+
173
+ #### **Options:**
174
+
175
+ | Name | Type | Default | Description |
176
+ |-------------------|-----------------------|---------|-------------------------------------------------------------------|
177
+ | inputDataEncoding | [`BufferEncoding`][3] | | Specifies the encoding of the input data (e.g., 'hex', 'base64'). |
178
+ | inputKeyEncoding | [`BufferEncoding`][3] | | Specifies the encoding of the input key (e.g., 'hex', 'base64'). |
179
+
180
+ **Outputs:**
181
+
182
+ As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
183
+
184
+ :::info
185
+
186
+ The resulting buffer contains: `[IV + SALT + AUTH_TAG + CIPHERED_DATA]`
187
+
188
+ :::
189
+
190
+ #### **Usage:**
191
+ ```typescript
192
+ async exampleEncrypt(
193
+ data: string,
194
+ ): Promise<string> {
195
+ const encryptedData = await this.cryptographyService.symmetricDataEncrypt(
196
+ data,
197
+ 'secret_key',
198
+ {
199
+ inputDataEncoding: 'utf-8',
200
+ inputKeyEncoding: 'utf-8'
201
+ },
202
+ );
203
+ return encryptedData.toString('hex')
204
+ }
205
+ ```
206
+
207
+
208
+ [//]: #--------------------#
209
+
210
+
211
+ ## Symmetric data decrypt
212
+
213
+ #### <GenericLabel />
214
+
215
+ Method to decrypt data that was encrypted using the method [`symmetricDataEncrypt`][5]
216
+
217
+ ### `symmetricDataDecrypt`
218
+
219
+ ```typescript
220
+ public symmetricDataDecrypt (
221
+ data: string | Buffer,
222
+ key: string | Buffer,
223
+ options?: GenericOptionsInterface,
224
+ ): Promise<Buffer>;
225
+ ```
226
+
227
+ **Parameters:**
228
+
229
+ | Name | Type | Default | Description |
230
+ |---------------------------|------------------------------|---------|------------------------------------------------------------------|
231
+ | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to decrypt |
232
+ | **key** <RequiredLabel/> | string \| Buffer | | String or buffer of the key to use |
233
+ | **options** | [GenericOptions](#options-3) | `{}` | Optional configuration object for input data encoding and output |
234
+
235
+ #### **Options:**
236
+
237
+ | Name | Type | Default | Description |
238
+ |-------------------|-----------------------|---------|-------------------------------------------------------------------|
239
+ | inputDataEncoding | [`BufferEncoding`][3] | | Specifies the encoding of the input data (e.g., 'hex', 'base64'). |
240
+
241
+ **Outputs:**
242
+
243
+ As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
244
+
245
+ #### **Usage:**
246
+ ```typescript
247
+ async exampleDecrypt(
248
+ data: string,
249
+ ): Promise<string> {
250
+ const decryptedData = await this.cryptographyService.symmetricDataDecrypt(
251
+ data,
252
+ 'secret_key'
253
+ {
254
+ inputDataEncoding: 'hex',
255
+ inputKeyEncoding: 'utf-8',
256
+ },
257
+ );
258
+ return decryptedData.toString('utf-8')
259
+ }
260
+ ```
261
+
262
+ <Tips />
263
+
264
+
265
+
266
+
267
+ [1]: https://nodejs.org/api/buffer.html
268
+ [2]: #symmetricsecuredataencrypt
269
+ [3]: https://nodejs.org/api/buffer.html#buffers-and-character-encodings
270
+ [4]: generics#generate-secure-random-data
271
+ [5]: #symmetricdataencrypt
272
+ [6]: ../internals/symmetric-secure-data-encrypt
@@ -0,0 +1,148 @@
1
+ ---
2
+ sidebar_position: 1
3
+ title: Getting Started
4
+ sidebar_label: Getting Started
5
+ ---
6
+
7
+ import Tabs from '@theme/Tabs';
8
+ import TabItem from '@theme/TabItem';
9
+
10
+ ## Introduction
11
+
12
+ This library was created to address a common problem encountered when performing cryptographic operations in our projects.
13
+ It simplifies and streamlines the process, making it easier to implement secure and efficient cryptographic solutions.
14
+ Additionally, it helps avoid common mistakes,
15
+ such as the _**[reuse of initialization vectors][1]**_,
16
+ _**[reuse of encryption keys][2]**_,
17
+ or simple the use of _**[keys that are not cryptographically secure][3]**_.
18
+
19
+
20
+ Our library employs modern cryptographic standards to provide robust security and protect your data against advanced threats. We utilize a suite of trusted algorithms and practices recognized in the cryptographic community:
21
+
22
+ - **Argon2**: A cutting-edge key derivation function designed to resist GPU and ASIC attacks, making it highly effective against brute-force attempts. It offers configurable memory and time costs to balance performance and security.
23
+ - **SHA3**: The latest member of the Secure Hash Algorithm family, SHA3 provides enhanced security over its predecessors (SHA-1 and SHA-2) and is resilient against known cryptographic attacks.
24
+ - **AES-256-GCM**: Advanced Encryption Standard with a 256-bit key in Galois/Counter Mode ensures both data confidentiality and integrity. AES-256-GCM is widely used and trusted for its high level of security and performance.
25
+ - **SHAKE256**: A versatile extendable-output function (XOF) from the SHA-3 family, SHAKE256 allows for variable-length output, making it suitable for a variety of cryptographic applications like key generation and hashing.
26
+ - **HKDF-SHA3-256**: A HMAC-based Key Derivation Function using SHA3-256 as the underlying hash function. HKDF-SHA3-256 ensures secure and reliable derivation of cryptographic keys from a master secret.
27
+ - **HMAC-SHA3-256**: A mechanism for message authentication using SHA3-256. HMAC-SHA3-256 provides data integrity and authenticity by allowing verification that a message has not been altered.
28
+ - **Constant-Time Secret Comparisons**: To protect against timing attacks, our library implements constant-time algorithms for comparing secrets. This means the time taken to perform the comparison does not depend on the data being compared, preventing attackers from inferring information based on execution time.
29
+
30
+ ## Installation
31
+
32
+ This package are available on the [npm][4] registry.
33
+
34
+ <Tabs
35
+ groupId="language"
36
+ defaultValue="npm"
37
+ values={[
38
+ { label: 'Yarn', value: 'yarn', },
39
+ { label: 'NPM', value: 'npm', }
40
+ ]
41
+ }>
42
+ <TabItem value="yarn">
43
+ ```bash
44
+ yarn add nestjs-cryptography
45
+ ```
46
+ </TabItem>
47
+ <TabItem value="npm">
48
+ ```bash
49
+ npm install nestjs-cryptography
50
+ ```
51
+ </TabItem>
52
+ </Tabs>
53
+
54
+
55
+ ## Usage on Services
56
+ To access cryptography methods from our `CryptographyService`, you could inject it using standard constructor injection
57
+
58
+ ```typescript
59
+ import { Injectable } from '@nestjs/common';
60
+ import { CryptographyService } from 'nestjs-cryptography';
61
+
62
+ @Injectable()
63
+ export class SomeService {
64
+ constructor(
65
+ // Inject using constructor injection
66
+ private readonly cryptographyService: CryptographyService
67
+ ) {}
68
+
69
+ async someMethod(): Promise<string> {
70
+ // Access service methods
71
+ return this.cryptographyService.genUUID();
72
+ }
73
+ }
74
+ ```
75
+
76
+
77
+ ## Configuration
78
+
79
+ Once the installation is complete, the `CryptographyModule` can be configured as any other
80
+ Nest package with _`forRoot`_ or _`forRootAsync`_ methods.
81
+
82
+ You could see the complete available settings [here][5]
83
+
84
+ ```typescript title="app.module.ts"
85
+ import {
86
+ CryptographyModule,
87
+ CryptographyOptionsInterface,
88
+ } from 'nestjs-cryptography';
89
+
90
+ @Module({
91
+ imports: [
92
+ CryptographyModule.forRoot<CryptographyOptionsInterface>({
93
+ // The rest of the configuration
94
+ encryption: {
95
+ symmetric: {
96
+ masterKey: '5f7f...46bf'
97
+ }
98
+ }
99
+ }),
100
+ ],
101
+ })
102
+ export class AppModule {}
103
+ ```
104
+
105
+ :::info
106
+
107
+ Like other factory providers, our factory function can be async and can inject dependencies through inject.
108
+
109
+ For example, you mat want to get the configuration using the `ConfigurationModule`,
110
+ so to do this you would use the _`forRootAsync`_ method ⬇️⬇️⬇️.
111
+
112
+ :::
113
+
114
+ ```typescript title="app.module.ts"
115
+ import {
116
+ CryptographyModule,
117
+ CryptographyOptionsInterface,
118
+ } from 'nestjs-cryptography';
119
+
120
+ @Module({
121
+ imports: [
122
+ CryptographyModule.forRootAsync<CryptographyOptionsInterface>({
123
+ imports: [ConfigModule],
124
+ useFactory: async (configService: ConfigService) => ({
125
+ // The rest of the configuration
126
+ encryption: {
127
+ symmetric: {
128
+ masterKey: configService.get<string>('CRYPTOGRAPHY.MASTER_KEY')
129
+ }
130
+ }
131
+ }),
132
+ inject: [ConfigService],
133
+ }),
134
+ ],
135
+ })
136
+ export class AppModule {}
137
+ ```
138
+
139
+
140
+ The _`forRoot()`_ and _`forRootAsync`_ method takes an options object as an argument.
141
+ These options are passed through to the underlying cryptographic operations of the instance module.
142
+
143
+
144
+ [1]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#page=26
145
+ [2]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf#page=27
146
+ [3]: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-57pt1r5.pdf#page=112
147
+ [4]: https://www.npmjs.com/package/nestjs-cryptography
148
+ [5]: api-reference/settings