-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
253 lines (219 loc) · 7.05 KB
/
index.js
File metadata and controls
253 lines (219 loc) · 7.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
const encryptionAlgorithm = "AES-GCM"
const ivBytesLength = 12
/**
* @type {KeyUsage[]}
*/
const keyUsages = ["encrypt", "decrypt"]
Object.freeze(keyUsages)
/**
* @type {Parameters<Uint8Array<ArrayBuffer>["toBase64"]>[0]}
*/
const BASE64URL_OPTIONS = Object.freeze({
alphabet: "base64url"
})
/**
* Before encrypting and decrypting values, a symmetric `CryptoKey` must be created.
* This method also converts your value key to a SHA-256 hash.
*
* @async
* @function createSymmetricKeyFromText
* @param {string} key - Text key to be hashed. A 32-byte high entropy string is recommended.
* @param {boolean} [extractable] - Whether the generated key is extractable. Defaults to `false`..
* @param {TextEncoder} [textEncoder] - If you have an instance of a `TextEncoder`, you can reuse it.
* @returns {Promise<CryptoKey>} A `CryptoKey` containing a SHA-256 hash used to encrypt and decrypt strings.
* @throws {TypeError} Thrown if `text` is invalid.
*/
export async function createSymmetricKeyFromText(
key,
extractable = false,
textEncoder = new TextEncoder()
) {
return (
await crypto.subtle.importKey(
"raw",
await crypto.subtle.digest("SHA-256", textEncoder.encode(key)),
encryptionAlgorithm,
extractable,
keyUsages
)
)
}
/**
* Encrypts a value with a `CryptoKey` previously generated with `createSymmetricKeyFromText`.
*
* @async
* @function encryptTextSymmetrically
* @param {CryptoKey} key - Symmetric key generated with `createSymmetricKeyFromText`.
* @param {string} text - String value to be encrypted.
* @param {boolean} [urlSafe] - The encrypted values default to `base64` alphabet; this property enables the `base64url` alphabet. Enabled by default.
* @param {TextEncoder} [textEncoder] - If you have an instance of a `TextEncoder`, you can reuse it.
* @param {BufferSource} [additionalData] - Additional data for authentication.
* @returns {Promise<string>} The value encrypted and encoded as a Base64 string.
* @throws {DOMException} Raised when:
* - The provided key is not valid.
* - The operation failed (e.g., AES-GCM plaintext longer than 2^39−256 bytes).
*/
export async function encryptTextSymmetrically(
key,
text,
urlSafe = true,
textEncoder = new TextEncoder(),
additionalData
) {
const iv = crypto.getRandomValues(new Uint8Array(ivBytesLength))
/**
* @type {Parameters<Uint8Array["toBase64"]>[0]}
*/
const options = urlSafe ? BASE64URL_OPTIONS : undefined
return (
iv.toBase64(options) +
new Uint8Array(
await crypto.subtle.encrypt(
{ name: encryptionAlgorithm, iv, additionalData },
key,
textEncoder.encode(text)
)
).toBase64(options)
)
}
/**
* Decrypts a value with a `CryptoKey` previously generated with `createSymmetricKeyFromText`.
*
* @async
* @function decryptTextSymmetrically
* @param {CryptoKey} key - Symmetric key used to encrypt the value.
* @param {string} ciphertext - Encrypted value to be decrypted.
* @param {TextDecoder} [textDecoder] - If you have an instance of a `TextDecoder`, you can reuse it.
* @param {BufferSource} [additionalData] - Additional data for authentication.
* @returns {Promise<string>} The value decrypted.
* @throws {TypeError} Thrown if `ciphertext` is not a string.
* @throws {SyntaxError} Thrown if `ciphertext` contains characters outside Base64 alphabet.
* @throws {DOMException} Raised when:
* - The provided key is not valid.
* - The operation failed.
*/
export async function decryptTextSymmetrically(
key,
ciphertext,
textDecoder = new TextDecoder(),
additionalData
) {
/**
* @type {(boolean|undefined)}
*/
let urlSafe
let i = 0
do {
switch (ciphertext[i]) {
case "-":
case "_":
urlSafe = true
break
case "+":
case "/":
urlSafe = false
break
default:
i++
}
} while (urlSafe === undefined && i < ciphertext.length)
const data = Uint8Array.fromBase64(
ciphertext,
urlSafe ? BASE64URL_OPTIONS : undefined
)
return (
textDecoder.decode(
await crypto.subtle.decrypt(
{ name: encryptionAlgorithm, iv: data.subarray(0, ivBytesLength), additionalData },
key,
data.subarray(ivBytesLength)
)
)
)
}
/**
* Class that simplifies the encryption and decryption using the same key.
*/
export class SingleCryptText {
/**
* @type {(CryptoKey|undefined)}
*/
#key
/**
* @type {(Promise<CryptoKey>|undefined)}
*/
#keyPromise
#textEncoder
#textDecoder
/**
* Create an instance using a text as a key.
*
* @param {string} key - Text key to be hashed. A 32-byte high entropy string is recommended.
* @param {boolean} [extractable] - Whether the generated key is extractable. Defaults to `false`..
* @param {TextEncoder} [textEncoder] - If you have an instance of a `TextEncoder`, you can reuse it.
* @param {TextDecoder} [textDecoder] - If you have an instance of a `TextDecoder`, you can reuse it.
* @throws {TypeError} Thrown if `key` is invalid.
*/
constructor(
key,
extractable = false,
textEncoder = new TextEncoder(),
textDecoder = new TextDecoder()
) {
this.#keyPromise = createSymmetricKeyFromText(key, extractable, textEncoder)
this.#textEncoder = textEncoder
this.#textDecoder = textDecoder
}
/**
* @async
* @function getKey
* @returns {Promise<CryptoKey>}
*/
async getKey() {
if (!this.#key && this.#keyPromise) {
this.#key = await this.#keyPromise
this.#keyPromise = undefined
}
// @ts-expect-error: TS doesn't detect that `#key` has been defined.
return this.#key
}
/**
* @async
* @param {string} text - String value to be encrypted.
* @param {boolean} [urlSafe] - The encrypted values default to `base64` alphabet; this property enables the `base64url` alphabet. Enabled by default.
* @param {BufferSource} [additionalData] - Additional data for authentication.
* @returns {Promise<string>} The value encrypted and encoded as a Base64 string.
* @throws {DOMException} Raised when:
* - The provided key is not valid.
* - The operation failed (e.g., AES-GCM plaintext longer than 2^39−256 bytes).
*/
async encrypt(text, urlSafe = true, additionalData) {
return await encryptTextSymmetrically(
await this.getKey(),
text,
urlSafe,
this.#textEncoder,
additionalData
)
}
/**
* @async
* @param {string} ciphertext - Encrypted value to be decrypted.
* @param {BufferSource} [additionalData] - Additional data for authentication.
* @returns {Promise<string>} The value decrypted.
* @throws {TypeError} Thrown if `ciphertext` is not a string.
* @throws {SyntaxError} Thrown if `ciphertext` contains characters outside Base64 alphabet.
* @throws {DOMException} Raised when:
* - The provided key is not valid.
* - The operation failed.
*/
async decrypt(ciphertext, additionalData) {
return await decryptTextSymmetrically(
await this.getKey(),
ciphertext,
this.#textDecoder,
additionalData
)
}
}
export default SingleCryptText