nestjs-cryptography 3.0.0 → 3.1.1

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 (62) hide show
  1. package/SECURITY.md +14 -0
  2. package/dist/constants.d.ts +15 -0
  3. package/dist/constants.js +16 -1
  4. package/dist/cryptography.service.d.ts +3 -2
  5. package/dist/cryptography.service.js +101 -21
  6. package/dist/interfaces/cryptography-options.interface.d.ts +20 -16
  7. package/package.json +23 -16
  8. package/wiki/README.md +0 -41
  9. package/wiki/babel.config.js +0 -3
  10. package/wiki/docs/Internals/_category_.json +0 -7
  11. package/wiki/docs/Internals/create-safe-random-data.mdx +0 -41
  12. package/wiki/docs/Internals/create-secure-hmac.mdx +0 -31
  13. package/wiki/docs/Internals/symmetric-data-encrypt.mdx +0 -103
  14. package/wiki/docs/Internals/symmetric-secure-data-encrypt.mdx +0 -161
  15. package/wiki/docs/api-reference/_category_.json +0 -7
  16. package/wiki/docs/api-reference/settings.mdx +0 -199
  17. package/wiki/docs/guides/_category_.json +0 -7
  18. package/wiki/docs/guides/generics.mdx +0 -170
  19. package/wiki/docs/guides/hashing.mdx +0 -258
  20. package/wiki/docs/guides/hmac.mdx +0 -271
  21. package/wiki/docs/guides/key-derivation.mdx +0 -101
  22. package/wiki/docs/guides/password-hashing.mdx +0 -136
  23. package/wiki/docs/guides/symmetric-encryption.mdx +0 -272
  24. package/wiki/docs/intro.mdx +0 -148
  25. package/wiki/docusaurus.config.ts +0 -138
  26. package/wiki/package.json +0 -48
  27. package/wiki/sidebars.ts +0 -20
  28. package/wiki/src/common/timing-attack.mdx +0 -3
  29. package/wiki/src/common/tips.mdx +0 -18
  30. package/wiki/src/components/GenerateHexButton/index.tsx +0 -35
  31. package/wiki/src/components/GenerateHexButton/styles.module.css +0 -10
  32. package/wiki/src/components/GenericLabel/index.tsx +0 -19
  33. package/wiki/src/components/HomepageFeatures/index.tsx +0 -70
  34. package/wiki/src/components/HomepageFeatures/styles.module.css +0 -11
  35. package/wiki/src/components/RecommendedLabel/index.tsx +0 -19
  36. package/wiki/src/components/RequiredLabel/index.tsx +0 -12
  37. package/wiki/src/css/custom.css +0 -30
  38. package/wiki/src/pages/index.module.css +0 -23
  39. package/wiki/src/pages/index.tsx +0 -43
  40. package/wiki/src/pages/markdown-page.md +0 -7
  41. package/wiki/static/.nojekyll +0 -0
  42. package/wiki/static/img/gear_api.png +0 -0
  43. package/wiki/static/img/logo.svg +0 -1
  44. package/wiki/static/img/nestjs_favicon.ico +0 -0
  45. package/wiki/static/img/node_crypto.png +0 -0
  46. package/wiki/static/img/phc_logo.png +0 -0
  47. package/wiki/static/img/profile.png +0 -0
  48. package/wiki/versioned_docs/version-2.x/Internals/_category_.json +0 -8
  49. package/wiki/versioned_docs/version-2.x/Internals/create-secure-hmac.mdx +0 -30
  50. package/wiki/versioned_docs/version-2.x/Internals/symmetric-secure-data-encrypt.mdx +0 -160
  51. package/wiki/versioned_docs/version-2.x/api-reference/_category_.json +0 -8
  52. package/wiki/versioned_docs/version-2.x/api-reference/settings.mdx +0 -197
  53. package/wiki/versioned_docs/version-2.x/guides/_category_.json +0 -7
  54. package/wiki/versioned_docs/version-2.x/guides/generics.mdx +0 -133
  55. package/wiki/versioned_docs/version-2.x/guides/hashing.mdx +0 -229
  56. package/wiki/versioned_docs/version-2.x/guides/hmac.mdx +0 -198
  57. package/wiki/versioned_docs/version-2.x/guides/key-derivation.mdx +0 -98
  58. package/wiki/versioned_docs/version-2.x/guides/password-hashing.mdx +0 -132
  59. package/wiki/versioned_docs/version-2.x/guides/symmetric-encryption.mdx +0 -107
  60. package/wiki/versioned_docs/version-2.x/intro.mdx +0 -148
  61. package/wiki/versioned_sidebars/version-2.x-sidebars.json +0 -8
  62. package/wiki/versions.json +0 -3
@@ -1,198 +0,0 @@
1
- ---
2
- title: HMAC
3
- sidebar_label: HMAC
4
- sidebar_position: 5
5
- description: Methods to create generic and secure HMACs
6
- ---
7
-
8
- import RequiredLabel from '@site/src/components/RequiredLabel';
9
- import Tips from '@site/src/common/tips.mdx'
10
- import TimingAttack from '@site/src/common/timing-attack.mdx'
11
-
12
- In this section, we will dive into various methods for applying cryptographic [HMAC hash-based message authentication code][2]
13
- both generically and securely.
14
- We will cover best practices to ensure that the hmac process is robust against common vulnerabilities.
15
- Additionally, we will explore secure techniques for comparing hmac values,
16
- focusing on the use of time-safe comparison functions to prevent timing attacks.
17
- These methods are crucial for ensuring the integrity and security of sensitive data in cryptographic operations.
18
-
19
- ## Create a custom HMAC
20
-
21
- Method to create a hmac of a text where you could choose the desired digest algorithm to use `sha1, sha256, sha3-256,...`
22
-
23
- ### `createCustomHmac`
24
-
25
- ```typescript
26
- public createCustomHmac (
27
- algorithm: string,
28
- key: Buffer,
29
- data: string,
30
- ): Buffer;
31
- ```
32
-
33
- **Parameters:**
34
-
35
- | Name | Type | Default | Description |
36
- |--------------------------------|--------|---------|--------------------------------------------------------|
37
- | **algorithm** <RequiredLabel/> | string | | Digest algorithm to use (`sha1, sha256, sha3-256,...`) |
38
- | **key** <RequiredLabel/> | Buffer | | Secret key to use on the hmac |
39
- | **data** <RequiredLabel/> | string | | String to hmac |
40
-
41
- **Outputs:**
42
-
43
- As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
44
-
45
- #### **Usage:**
46
- ```typescript
47
- async exampleHmac(
48
- data: string,
49
- ): string {
50
- const key = this.cryptographyService.generateSymmetricKey(128);
51
- const hmacResult = this.cryptographyService.createCustomHmac('sha-512', key, data);
52
- return hmacResult.toString('hex')
53
- }
54
- ```
55
-
56
-
57
- [//]: #--------------------#
58
-
59
-
60
- ## Verify a custom HMAC
61
-
62
- Method to verify if an existing hmac matches the hmac of the desired text.
63
- You need choose the existing hmac algorithm type used `sha1, sha256, sha3-256,...`
64
-
65
- ### `verifyCustomHmac`
66
-
67
- ```typescript
68
- public verifyCustomHmac (
69
- algorithm: string,
70
- key: Buffer,
71
- data: string,
72
- oldHmac: string | Buffer,
73
- ): boolean;
74
- ```
75
-
76
- **Parameters:**
77
-
78
- | Name | Type | Default | Description |
79
- |--------------------------------|------------------|---------|--------------------------------------------------------|
80
- | **algorithm** <RequiredLabel/> | string | | Digest algorithm to use (`sha1, sha256, sha3-256,...`) |
81
- | **key** <RequiredLabel/> | Buffer | | Secret key to use on the hmac |
82
- | **data** <RequiredLabel/> | string | | String to hmac |
83
- | **oldHmac** <RequiredLabel/> | string \| Buffer | | Buffer or string of the existing hmac |
84
-
85
- **Outputs:**
86
-
87
- As output, it will return `true` if both matches, or `false` if not.
88
-
89
- <TimingAttack/>
90
-
91
- #### **Usage:**
92
- ```typescript
93
- async checkHmac(
94
- oldKey: string,
95
- existingHmac: string,
96
- data: string,
97
- ): boolean {
98
- const bufferExistingHmac = Buffer.from(existingHmac, 'hex');
99
- const bufferOldKey = Buffer.from(oldKey, 'hex');
100
- return this.cryptographyService.verifyCustomHmac('sha-512', bufferOldKey, data, bufferExistingHmac);
101
- }
102
- ```
103
-
104
-
105
- [//]: #--------------------#
106
-
107
-
108
- ## Create a secure HMAC
109
-
110
- Method to create an extra secure hmac of a text.
111
-
112
- In this case the `sha3-256` digest algorithm will be used.
113
-
114
- ### `createSecureHmac`
115
-
116
- ```typescript
117
- public createSecureHmac (
118
- data: string
119
- ): Buffer;
120
- ```
121
-
122
- **Parameters:**
123
-
124
- | Name | Type | Default | Description |
125
- |--------------------------------|--------|---------|-------------------------------------------------------------------------------------------------------------|
126
- | **data** <RequiredLabel/> | string | | String to hmac |
127
-
128
- **Outputs:**
129
-
130
- As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
131
-
132
- #### **Usage:**
133
- ```typescript
134
- async exampleSecureHmac(
135
- data: string,
136
- ): string {
137
- const hmacResult = this.cryptographyService.createSecureHmac(data);
138
- return hmacResult.toString('hex')
139
- }
140
- ```
141
-
142
-
143
- [//]: #--------------------#
144
-
145
-
146
- ## Verify a secure HMAC
147
-
148
- Method to verify if an existing hmac matches the hmac of the desired text.
149
- :::warning
150
- Remember that the previous hmac must have been generated using [`createSecureHmac`](hmac#createsecurehmac) method.
151
- :::
152
-
153
-
154
- ### `verifySecureHmac`
155
-
156
- ```typescript
157
- public verifySecureHmac (
158
- data: string,
159
- oldHmac: string | Buffer
160
- ): boolean;
161
- ```
162
-
163
- **Parameters:**
164
-
165
- | Name | Type | Default | Description |
166
- |------------------------------|------------------|---------|---------------------------------------|
167
- | **data** <RequiredLabel/> | string | | String to hmac |
168
- | **oldHmac** <RequiredLabel/> | Buffer \| string | | Buffer or string of the existing hmac |
169
-
170
- **Outputs:**
171
-
172
- As output, it will return `true` if both matches, or `false` if not.
173
-
174
- <TimingAttack/>
175
-
176
- #### **Usage:**
177
- ```typescript
178
- async exampleVerifySecureHmac(
179
- data: string,
180
- existingHmac: string,
181
- ): boolean {
182
- const bufferExistingHmac = Buffer.from(existingHmac, 'hex');
183
- return this.cryptographyService.verifySecureHmac(data, bufferExistingHmac);
184
- }
185
- ```
186
-
187
-
188
- [//]: #--------------------#
189
-
190
-
191
-
192
-
193
- <Tips />
194
-
195
-
196
-
197
- [1]: https://nodejs.org/api/buffer.html
198
- [2]: https://en.wikipedia.org/wiki/HMAC
@@ -1,98 +0,0 @@
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/> | boolean | false | MasterKey of password to derive |
45
- | **salt** <RequiredLabel/> | Buffer | false | Salt to increase the security of the key derivation |
46
- | **length** <RequiredLabel/> | number | false | The desired derived output key length |
47
-
48
-
49
- #### **Module Parameters:**
50
-
51
- :::info
52
- Internally, this method uses certain parameters that are defined at the module level during initialization,
53
- as we have seen [previously][2]. The internal parameters used and their corresponding configuration keys are as follows:
54
-
55
- - **hashLength**: Specifies the length of the resulting derived key.
56
- This is set via [`kdf.defaultOutputKeyLength`][3] and determines the size of the final hash in bytes.
57
-
58
- - **type**: Defines the variant of Argon2 to use (_argon2i_, _argon2d_, or _argon2id_).
59
- This is configured using [`kdf.argon2Type`][4].
60
-
61
- - **memoryCost**: Sets the amount of memory (in KB) that the algorithm will use during the hashing process.
62
- This value is determined by [`kdf.memoryCost`][5] and plays a critical role in resisting brute-force attacks.
63
-
64
- - **timeCost**: Specifies the number of iterations or the amount of computational work Argon2 will perform.
65
- It is defined via [`kdf.timeCost`][6] to ensure a balance between security and performance.
66
- :::
67
-
68
-
69
- #### **Outputs:**
70
-
71
- As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
72
-
73
-
74
- #### **Usage:**
75
- ```typescript
76
- async deriveSecureKeyFromMasterKey(
77
- key: string,
78
- ): Promise<string> {
79
- const keyBuffer = Buffer.from(key, 'utf-8');
80
- const salt = this.cryptographyService.generateSymmetricKey(128);
81
- const derivedKey = await this.cryptographyService.deriveMasterKey(keyBuffer, salt.export(), 256)
82
- return derivedKey.toString('hex')
83
- }
84
- ```
85
-
86
-
87
-
88
-
89
- <Tips />
90
-
91
- [1]: https://nodejs.org/api/buffer.html
92
-
93
- [2]: ../intro#configuration
94
-
95
- [3]: ../api-reference/settings#defaultoutputkeylength
96
- [4]: ../api-reference/settings#argon2type
97
- [5]: ../api-reference/settings#memorycost
98
- [6]: ../api-reference/settings#timecost
@@ -1,132 +0,0 @@
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 Tips from '@site/src/common/tips.mdx'
10
- import TimingAttack from '@site/src/common/timing-attack.mdx'
11
-
12
- In this section, we will explore how to securely hash passwords using [Argon2][2],
13
- one of the most advanced and secure password-hashing algorithms available today.
14
- Developed as a winner of the [Password Hashing Competition (PHC)][1], Argon2 is designed to protect against brute-force attacks,
15
- both by consuming significant computational resources and by utilizing memory-hard functions.
16
- This makes it a preferred choice for modern security practices.
17
-
18
-
19
-
20
- ## Create Argon2 hash
21
-
22
- Method to create a hash of a text/password using Argon2 algorithm.
23
-
24
- ### `createArgonHashFromPassword`
25
-
26
- ```typescript
27
- public createArgonHashFromPassword (
28
- data: string | Buffer,
29
- ): string;
30
- ```
31
-
32
-
33
- **Parameters:**
34
-
35
- | Name | Type | Default | Description |
36
- |---------------------------|------------------|---------|------------------|
37
- | **data** <RequiredLabel/> | string \| Buffer | | Password to hash |
38
-
39
-
40
- **Module Parameters:**
41
-
42
- :::info
43
- Internally, this method uses certain parameters that are defined at the module level during initialization,
44
- as we have seen [previously][4]. The internal parameters used and their corresponding configuration keys are as follows:
45
-
46
- - **hashLength**: Specifies the length of the resulting hash.
47
- This is set via [`hashing.password.outputKeyLength`][5] and determines the size of the final hash in bytes.
48
-
49
- - **type**: Defines the variant of Argon2 to use (_argon2i_, _argon2d_, or _argon2id_).
50
- This is configured using [`hashing.password.argon2Type`][6].
51
-
52
- - **memoryCost**: Sets the amount of memory (in KB) that the algorithm will use during the hashing process.
53
- This value is determined by [`hashing.password.memoryCost`][7] and plays a critical role in resisting brute-force attacks.
54
-
55
- - **timeCost**: Specifies the number of iterations or the amount of computational work Argon2 will perform.
56
- It is defined via [`hashing.password.timeCost`][8] to ensure a balance between security and performance.
57
- :::
58
-
59
-
60
- **Outputs:**
61
-
62
- As output, it will return a string of type: `$argon2i$v=19$m=4096,t=3,p=1$c2g56.....jk7A`
63
-
64
- > Where the options `argon2i`, `v=19`, `m=4096`, `t=3` and `p=1` may vary
65
- depending on the [options][3] supplied to CryptographyModule when it has been [configured][4].
66
-
67
-
68
- **Usage:**
69
- ```typescript
70
- async secureUserPassword(
71
- plainPassword: string,
72
- ): Promise<string> {
73
- const _buffer = Buffer.from(plainPassword, 'utf-8');
74
- const hashedPassword = await this.cryptographyService.createArgonHashFromPassword(_buffer);
75
- return hashedPassword.toString();
76
- }
77
- ```
78
-
79
-
80
-
81
- ## Verify Argon2 hash
82
-
83
- Method to verify if an existing Argon2 hash matches the desired text/password.
84
-
85
- ### `verifyArgonHashFromPassword`
86
-
87
- ```typescript
88
- public verifyArgonHashFromPassword (
89
- hash: string,
90
- data: string | Buffer,
91
- ): Promise<boolean>;
92
- ```
93
-
94
- **Parameters:**
95
-
96
- | Name | Type | Default | Description |
97
- |---------------------------|------------------|---------|-----------------------------|
98
- | **hash** <RequiredLabel/> | string | | String of the existing hash |
99
- | **data** <RequiredLabel/> | Buffer \| string | | Buffer or string to verify |
100
-
101
- **Outputs:**
102
-
103
- As output, it will return `true` if both matches, or `false` if not.
104
-
105
-
106
- **Usage:**
107
- ```typescript
108
- async checkUserPassword(
109
- plainPassword: string,
110
- hashedPassword: string
111
- ): Promise<boolean> {
112
- const _buffer = Buffer.from(plainPassword, 'utf-8');
113
- return await this.cryptographyService.verifyArgonHashFromPassword(hashedPassword, plainPassword)
114
- }
115
- ```
116
-
117
-
118
- <Tips />
119
-
120
-
121
-
122
-
123
- [1]: https://www.password-hashing.net
124
- [2]: https://github.com/P-H-C/phc-winner-argon2/blob/master/argon2-specs.pdf
125
-
126
- [3]: ../api-reference/settings
127
- [4]: ../intro#configuration
128
-
129
- [5]: ../api-reference/settings#outputkeylength
130
- [6]: ../api-reference/settings#argon2type-1
131
- [7]: ../api-reference/settings#memorycost-1
132
- [8]: ../api-reference/settings#timecost-1
@@ -1,107 +0,0 @@
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 Tips from '@site/src/common/tips.mdx'
10
- import TimingAttack from '@site/src/common/timing-attack.mdx'
11
-
12
- In this section, we will discuss symmetric encryption and decryption using AES-256-GCM,focusing on best practices to ensure robust security.
13
- AES-256-GCM is a widely used and highly secure cryptographic algorithm, but its strength depends heavily on proper implementation.
14
- Key best practices include never reusing initialization vectors (IVs), as doing so can compromise the encryption's integrity.
15
- It is also crucial to always derive a secure encryption key from the user-provided key using a strong key derivation function
16
- like Argon2 or HKDF. In certain cases, it’s recommended to encapsulate the Data Encryption Key (DEK) by encrypting it separately,
17
- providing an additional layer of security for sensitive operations.
18
- Following these principles ensures that your symmetric encryption implementations remain secure and resilient against common cryptographic attacks.
19
-
20
-
21
- ## Symmetric secure data encrypt
22
-
23
- Method to encrypt data using AES-256-GCM with a randomly generated Data Encryption Key (DEK).
24
- It ensures security by generating unique IVs and salts, securely deriving encryption keys,
25
- and encrypting the DEK using a master key.
26
- The final output is a concatenation of the encrypted DEK and the encrypted data, ensuring both confidentiality and key encapsulation.
27
-
28
- ### `symmetricSecureDataEncrypt`
29
-
30
- ```typescript
31
- public symmetricSecureDataEncrypt (
32
- data: string | Buffer,
33
- ): Promise<Buffer>;
34
- ```
35
-
36
- **Parameters:**
37
-
38
- | Name | Type | Default | Description |
39
- |---------------------------|------------------|---------|-----------------------------|
40
- | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to encrypt |
41
-
42
- **Outputs:**
43
-
44
- As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
45
-
46
- #### **Usage:**
47
- ```typescript
48
- async exampleEncrypt(
49
- data: string,
50
- ): Promise<string> {
51
- const bufferData = Buffer.from(data, 'utf-8');
52
- const encryptedData = await this.cryptographyService.symmetricSecureDataEncrypt(data);
53
- return encryptedData.toString('hex')
54
- }
55
- ```
56
-
57
-
58
- [//]: #--------------------#
59
-
60
-
61
- ## Symmetric secure data encrypt
62
-
63
- Method to decrypt data that was encrypted using the method [`symmetricSecureDataEncrypt`][2]
64
-
65
- :::warning
66
- Remember that the previous data must have been encrypted using [`symmetricSecureDataEncrypt`][2] method.
67
- :::
68
-
69
-
70
- ### `symmetricSecureDataDecrypt`
71
-
72
- ```typescript
73
- public symmetricSecureDataDecrypt (
74
- ata: string | Buffer
75
- ): Promise<Buffer>;
76
- ```
77
-
78
- **Parameters:**
79
-
80
- | Name | Type | Default | Description |
81
- |---------------------------|------------------|---------|-----------------------------|
82
- | **data** <RequiredLabel/> | string \| Buffer | | String or buffer to decrypt |
83
-
84
- **Outputs:**
85
-
86
- As output, it will return a [Buffer][1] `<Buffer cc 2b.....cd a1 08>`
87
-
88
-
89
- #### **Usage:**
90
- ```typescript
91
- async exampleDecrypt(
92
- data: string,
93
- ): Promise<string> {
94
- const bufferData = Buffer.from(data, 'hex');
95
- const decryptedData = await this.cryptographyService.symmetricSecureDataDecrypt(data);
96
- return decryptedData.toString('utf-8')
97
- }
98
- ```
99
-
100
-
101
- <Tips />
102
-
103
-
104
-
105
-
106
- [1]: https://nodejs.org/api/buffer.html
107
- [2]: symmetric-encryption#symmetricsecuredataencrypt
@@ -1,148 +0,0 @@
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
@@ -1,8 +0,0 @@
1
- {
2
- "tutorialSidebar": [
3
- {
4
- "type": "autogenerated",
5
- "dirName": "."
6
- }
7
- ]
8
- }
@@ -1,3 +0,0 @@
1
- [
2
- "2.x"
3
- ]