@cloudpss/crypto 0.5.24 → 0.5.25

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 (42) hide show
  1. package/benchmark.js +44 -0
  2. package/dist/encryption/browser.d.ts +3 -3
  3. package/dist/encryption/browser.js.map +1 -1
  4. package/dist/encryption/common.d.ts +45 -16
  5. package/dist/encryption/common.js +57 -9
  6. package/dist/encryption/common.js.map +1 -1
  7. package/dist/encryption/index.d.ts +4 -21
  8. package/dist/encryption/index.js +11 -63
  9. package/dist/encryption/index.js.map +1 -1
  10. package/dist/encryption/js/aes.d.ts +20 -0
  11. package/dist/encryption/js/aes.js +151 -0
  12. package/dist/encryption/js/aes.js.map +1 -0
  13. package/dist/encryption/js/gcm.d.ts +26 -0
  14. package/dist/encryption/js/gcm.js +226 -0
  15. package/dist/encryption/js/gcm.js.map +1 -0
  16. package/dist/encryption/module.d.ts +22 -0
  17. package/dist/encryption/module.js +62 -0
  18. package/dist/encryption/module.js.map +1 -0
  19. package/dist/encryption/node.d.ts +3 -3
  20. package/dist/encryption/node.js +19 -15
  21. package/dist/encryption/node.js.map +1 -1
  22. package/dist/encryption/pure-js.d.ts +3 -3
  23. package/dist/encryption/pure-js.js +70 -42
  24. package/dist/encryption/pure-js.js.map +1 -1
  25. package/dist/encryption/web.d.ts +3 -3
  26. package/dist/encryption/web.js +17 -15
  27. package/dist/encryption/web.js.map +1 -1
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/package.json +7 -4
  32. package/src/encryption/browser.ts +3 -3
  33. package/src/encryption/common.ts +79 -16
  34. package/src/encryption/index.ts +12 -71
  35. package/src/encryption/js/aes.ts +191 -0
  36. package/src/encryption/js/gcm.ts +258 -0
  37. package/src/encryption/module.ts +94 -0
  38. package/src/encryption/node.ts +24 -15
  39. package/src/encryption/pure-js.ts +89 -46
  40. package/src/encryption/web.ts +24 -15
  41. package/src/index.ts +1 -1
  42. package/tests/encryption.js +126 -49
@@ -0,0 +1,258 @@
1
+ import { AES } from './aes.js';
2
+
3
+ // const console = { log() {} };
4
+ const EMPTY = new Uint8Array(0);
5
+
6
+ /** GCM (Galois/Counter Mode) */
7
+ export class GCM {
8
+ constructor(
9
+ readonly cipher: AES,
10
+ readonly iv: Uint8Array,
11
+ readonly tagLength = 128,
12
+ readonly aad = EMPTY,
13
+ ) {
14
+ this.H = new Uint32Array(4);
15
+ this.cipher.encrypt(new Uint32Array(4), 0, this.H, 0);
16
+ }
17
+
18
+ /** Convert a Uint8Array to a Uint32Array */
19
+ private toUint32Array(data: Uint8Array): Uint32Array {
20
+ const out = new Uint32Array(Math.ceil(data.byteLength / 4));
21
+ for (let i = 0; i < out.length; i++) {
22
+ out[i] = (data[i * 4] << 24) | (data[i * 4 + 1] << 16) | (data[i * 4 + 2] << 8) | data[i * 4 + 3];
23
+ }
24
+ return out;
25
+ }
26
+ /** Convert a Uint32Array to a Uint8Array */
27
+ private toUint8Array(data: Uint32Array, byteLength: number): Uint8Array {
28
+ const out = new Uint8Array(byteLength);
29
+ for (let i = 0; i < byteLength; i++) {
30
+ out[i] = (data[Math.trunc(i / 4)] >>> (24 - (i % 4) * 8)) & 0xff;
31
+ }
32
+ return out;
33
+ }
34
+
35
+ /** Set out of range bytes to 0 */
36
+ private clamp(data: Uint32Array, byteLength: number): void {
37
+ const mask = 0xffff_ffff << (32 - (byteLength % 4) * 8);
38
+ data[Math.trunc(byteLength / 4)] &= mask;
39
+ }
40
+
41
+ private readonly H: Uint32Array;
42
+ /** Compute the galois multiplication of X and Y */
43
+ private galoisMultiply(x_r: Uint32Array, y: Uint32Array): void {
44
+ let Zi0 = 0,
45
+ Zi1 = 0,
46
+ Zi2 = 0,
47
+ Zi3 = 0;
48
+ let Vi0 = y[0],
49
+ Vi1 = y[1],
50
+ Vi2 = y[2],
51
+ Vi3 = y[3];
52
+
53
+ // Block size is 128 bits, run 128 times to get Z_128
54
+ for (let i = 0; i < 128; i++) {
55
+ const xi = (x_r[i >> 5] & (1 << (31 - (i % 32)))) !== 0;
56
+ if (xi) {
57
+ // Z_i+1 = Z_i ^ V_i
58
+ Zi0 ^= Vi0;
59
+ Zi1 ^= Vi1;
60
+ Zi2 ^= Vi2;
61
+ Zi3 ^= Vi3;
62
+ }
63
+
64
+ // Store the value of LSB(V_i)
65
+ const lsb_Vi = (Vi3 & 1) !== 0;
66
+
67
+ // V_i+1 = V_i >> 1
68
+ Vi3 = (Vi3 >>> 1) | ((Vi2 & 1) << 31);
69
+ Vi2 = (Vi2 >>> 1) | ((Vi1 & 1) << 31);
70
+ Vi1 = (Vi1 >>> 1) | ((Vi0 & 1) << 31);
71
+ Vi0 = Vi0 >>> 1;
72
+
73
+ // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
74
+ if (lsb_Vi) {
75
+ Vi0 = Vi0 ^ (0xe1 << 24);
76
+ }
77
+ }
78
+ x_r[0] = Zi0;
79
+ x_r[1] = Zi1;
80
+ x_r[2] = Zi2;
81
+ x_r[3] = Zi3;
82
+ }
83
+
84
+ /** Ghash */
85
+ private ghash(Y: Uint32Array, data: Uint32Array): void {
86
+ const l = data.length;
87
+ for (let i = 0; i < l; i += 4) {
88
+ Y[0] ^= 0xffff_ffff & data[i];
89
+ Y[1] ^= 0xffff_ffff & data[i + 1];
90
+ Y[2] ^= 0xffff_ffff & data[i + 2];
91
+ Y[3] ^= 0xffff_ffff & data[i + 3];
92
+ this.galoisMultiply(Y, this.H);
93
+ }
94
+ }
95
+
96
+ /** GCM CTR mode. */
97
+ private ctr(encrypt: boolean, data: Uint32Array, length: number): { data: Uint32Array; tag: Uint8Array } {
98
+ // console.log('data inpm', toHex(data));
99
+ // Calculate data lengths
100
+ const l = length / 4;
101
+ const bl = l * 32;
102
+ const abl = this.aad.byteLength * 8;
103
+ const ivbl = this.iv.byteLength * 8;
104
+
105
+ // Calculate the parameters
106
+ const J0 = new Uint32Array(4);
107
+ if (ivbl === 96) {
108
+ new Uint8Array(J0.buffer, J0.byteOffset).set(this.iv);
109
+ J0[3] = 1;
110
+ } else {
111
+ this.ghash(J0, this.toUint32Array(this.iv));
112
+ this.ghash(J0, new Uint32Array([0, 0, Math.trunc(ivbl / 0x1_0000_0000), ivbl & 0xffff_ffff]));
113
+ }
114
+
115
+ const S0 = new Uint32Array(4);
116
+ this.ghash(S0, this.toUint32Array(this.aad));
117
+
118
+ // Initialize ctr and tag
119
+ const tag = S0.slice(0);
120
+
121
+ // If decrypting, calculate hash
122
+ if (!encrypt) {
123
+ this.ghash(tag, data);
124
+ }
125
+
126
+ // Encrypt all the data
127
+ const ctr = J0.slice(0);
128
+ const enc = new Uint32Array(4);
129
+ for (let i = 0; i < l; i += 4) {
130
+ ctr[3]++;
131
+ this.cipher.encrypt(ctr, 0, enc, 0);
132
+
133
+ data[i] ^= enc[0];
134
+ data[i + 1] ^= enc[1];
135
+ data[i + 2] ^= enc[2];
136
+ data[i + 3] ^= enc[3];
137
+ }
138
+ this.clamp(data, length);
139
+ // console.log('data inpm', toHex(data));
140
+
141
+ // console.log('H impl', toHex(this.H));
142
+ // console.log('tag impl', toHex(tag));
143
+ // If encrypting, calculate hash
144
+ if (encrypt) {
145
+ this.ghash(tag, data);
146
+ }
147
+ // console.log('tag impl', toHex(tag));
148
+
149
+ // Calculate last block from bit lengths, ugly because bitwise operations are 32-bit
150
+ // Calculate the final tag block
151
+ this.ghash(
152
+ tag,
153
+ new Uint32Array([
154
+ Math.trunc(abl / 0x1_0000_0000),
155
+ abl & 0xffff_ffff,
156
+ Math.trunc(bl / 0x1_0000_0000),
157
+ bl & 0xffff_ffff,
158
+ ]),
159
+ );
160
+
161
+ this.cipher.encrypt(J0, 0, enc, 0);
162
+ tag[0] ^= enc[0];
163
+ tag[1] ^= enc[1];
164
+ tag[2] ^= enc[2];
165
+ tag[3] ^= enc[3];
166
+
167
+ // console.log('tag impl', toHex(tag));
168
+ return {
169
+ tag: new Uint8Array(tag.buffer, tag.byteOffset, this.tagLength / 8),
170
+ data,
171
+ };
172
+ }
173
+
174
+ /** 加密 */
175
+ encrypt(data: Uint8Array): Uint8Array {
176
+ const length = data.byteLength;
177
+ const data32 = this.toUint32Array(data);
178
+ const { data: out, tag } = this.ctr(true, data32, length);
179
+ const result = new Uint8Array(length + tag.byteLength);
180
+ result.set(this.toUint8Array(out, length), 0);
181
+ result.set(tag, length);
182
+ return result;
183
+ }
184
+
185
+ /** 解密 */
186
+ decrypt(data: Uint8Array): Uint8Array {
187
+ let tag, data32, length;
188
+ if (this.tagLength / 8 > data.byteLength) {
189
+ throw new Error('GCM: invalid data length');
190
+ } else if (this.tagLength / 8 === data.byteLength) {
191
+ length = 0;
192
+ tag = data;
193
+ data32 = new Uint32Array(0);
194
+ } else {
195
+ length = data.byteLength - this.tagLength / 8;
196
+ tag = data.subarray(length);
197
+ data32 = this.toUint32Array(data.subarray(0, length));
198
+ }
199
+ const { data: out, tag: tag2 } = this.ctr(false, data32, length);
200
+ if (tag2.some((v, i) => v !== tag[i])) {
201
+ throw new Error('GCM: tag does not match');
202
+ }
203
+ return this.toUint8Array(out, length);
204
+ }
205
+ }
206
+
207
+ // import sjcl from 'sjcl';
208
+ // global.sjcl = sjcl;
209
+
210
+ // // @ts-expect-error sjcl is not a module
211
+ // await import('sjcl/core/aes.js');
212
+ // // @ts-expect-error sjcl is not a module
213
+ // await import('sjcl/core/gcm.js');
214
+ // // @ts-expect-error sjcl is not a module
215
+ // await import('sjcl/core/bitArray.js');
216
+ // // @ts-expect-error sjcl is not a module
217
+ // await import('sjcl/core/pbkdf2.js');
218
+ // // @ts-expect-error sjcl is not a module
219
+ // await import('sjcl/core/hmac.js');
220
+ // // @ts-expect-error sjcl is not a module
221
+ // await import('sjcl/core/sha256.js');
222
+ // // @ts-expect-error sjcl is not a module
223
+ // await import('sjcl/core/codecBytes.js');
224
+
225
+ // function toHex(arr: number[] | Uint32Array | Int32Array | Uint8Array): string[] {
226
+ // if (arr instanceof Uint8Array) {
227
+ // const result = [];
228
+ // for (let i = 0; i < arr.length; i += 4) {
229
+ // const a = arr[i].toString(16).padStart(2, '0');
230
+ // const b = arr[i + 1]?.toString(16).padStart(2, '0') ?? '';
231
+ // const c = arr[i + 2]?.toString(16).padStart(2, '0') ?? '';
232
+ // const d = arr[i + 3]?.toString(16).padStart(2, '0') ?? '';
233
+ // result.push(a + b + c + d);
234
+ // }
235
+ // return result;
236
+ // }
237
+ // return [...arr].map((x) => {
238
+ // if (x < 0) x = 0xffffffff + x + 1;
239
+ // return x.toString(16).padStart(8, '0');
240
+ // });
241
+ // }
242
+ // // @ts-expect-error sjcl is not a module
243
+ // global.toHex = toHex;
244
+
245
+ // const data = new Uint8Array([1, 2, 3, 4, 5, 6, 7]);
246
+ // const key = [1, 2, 3, 4];
247
+ // const iv = [9, 8, 7];
248
+
249
+ // const aes = new AES(new Uint32Array(key));
250
+ // const gcm = new GCM(aes, new Uint8Array(new Uint32Array(iv).buffer));
251
+ // const e1 = gcm.encrypt(data);
252
+ // const e2 = sjcl.mode.gcm.encrypt(new sjcl.cipher.aes(key), sjcl.codec.bytes.toBits([...data]), iv);
253
+ // console.log({ d: toHex(e1), l: e1.byteLength }, { d: toHex(e2), l: sjcl.bitArray.bitLength(e2) / 8 });
254
+
255
+ // const d1 = gcm.decrypt(e1);
256
+ // const d2 = sjcl.mode.gcm.decrypt(new sjcl.cipher.aes(key), e2, iv);
257
+
258
+ // console.log({ d: toHex(d1), l: d1.byteLength }, { d: toHex(d2), l: sjcl.bitArray.bitLength(d2) / 8 });
@@ -0,0 +1,94 @@
1
+ import { toUint8Array } from '../utils.js';
2
+ import {
3
+ AAD_LEN_SIZE,
4
+ AAD_MAX_SIZE,
5
+ AAD_PADDING,
6
+ MAGIC_NUMBER,
7
+ NONCE_SIZE,
8
+ padding,
9
+ parseEncrypted,
10
+ type PlainData,
11
+ } from './common.js';
12
+
13
+ /** 检查密码 */
14
+ function assertPassphrase(passphrase: string): void {
15
+ if (typeof passphrase !== 'string') {
16
+ throw new TypeError('Invalid passphrase, must be a string');
17
+ }
18
+ if (passphrase.length === 0) {
19
+ throw new TypeError('Invalid passphrase, must not be empty');
20
+ }
21
+ }
22
+
23
+ /** 模块 */
24
+ interface Module {
25
+ /**
26
+ * 加密数据
27
+ * @throws {TypeError} 如果密码无效
28
+ */
29
+ encrypt(data: BinaryData, passphrase: string): Promise<Uint8Array>;
30
+ /**
31
+ * 加密数据,包含不加密的附加数据
32
+ * @throws {TypeError} 如果密码无效
33
+ */
34
+ encryptAad(data: BinaryData, aad: BinaryData | undefined, passphrase: string): Promise<Uint8Array>;
35
+ /**
36
+ * 解密数据
37
+ * @throws {TypeError} 如果数据不是有效的加密数据
38
+ * @throws {TypeError} 如果密码无效
39
+ */
40
+ decrypt(data: BinaryData, passphrase: string): Promise<Uint8Array>;
41
+ }
42
+
43
+ /** 创建模块 */
44
+ export function createModule(impl: typeof import('#encryption')): Module {
45
+ const encryptAad: Module['encryptAad'] = async (data, aad, passphrase) => {
46
+ assertPassphrase(passphrase);
47
+ const aadSize = aad?.byteLength ?? 0;
48
+ if (aadSize > AAD_MAX_SIZE) {
49
+ throw new TypeError('Invalid AAD size');
50
+ }
51
+ const paddedAddSize = padding(aadSize, AAD_PADDING);
52
+ const plain: PlainData = {
53
+ aad: aadSize ? toUint8Array(aad!) : undefined,
54
+ data: toUint8Array(data),
55
+ };
56
+ const encrypted = await impl.encrypt(plain, passphrase);
57
+ const result = new Uint8Array(
58
+ MAGIC_NUMBER.length + NONCE_SIZE + AAD_LEN_SIZE + paddedAddSize + encrypted.data.length,
59
+ );
60
+ result.set(MAGIC_NUMBER);
61
+ result.set(encrypted.nonce, MAGIC_NUMBER.length);
62
+ if (aadSize) {
63
+ result[MAGIC_NUMBER.length + NONCE_SIZE] = aadSize >>> 24;
64
+ result[MAGIC_NUMBER.length + NONCE_SIZE + 1] = aadSize >>> 16;
65
+ result[MAGIC_NUMBER.length + NONCE_SIZE + 2] = aadSize >>> 8;
66
+ result[MAGIC_NUMBER.length + NONCE_SIZE + 3] = aadSize;
67
+ result.set(plain.aad!, MAGIC_NUMBER.length + NONCE_SIZE + AAD_LEN_SIZE);
68
+ }
69
+ result.set(encrypted.data, MAGIC_NUMBER.length + NONCE_SIZE + AAD_LEN_SIZE + paddedAddSize);
70
+ return result;
71
+ };
72
+ const encrypt: Module['encrypt'] = async (data, passphrase) => {
73
+ return await encryptAad(data, undefined, passphrase);
74
+ };
75
+
76
+ const decrypt: Module['decrypt'] = async (data, passphrase) => {
77
+ assertPassphrase(passphrase);
78
+ const encrypted = parseEncrypted(data);
79
+ if (encrypted == null) {
80
+ throw new TypeError('Invalid encrypted data');
81
+ }
82
+ try {
83
+ const result = await impl.decrypt(encrypted, passphrase);
84
+ return result.data;
85
+ } catch (ex) {
86
+ throw new Error('Wrong passphrase', { cause: ex });
87
+ }
88
+ };
89
+ return {
90
+ encrypt,
91
+ encryptAad,
92
+ decrypt,
93
+ };
94
+ }
@@ -1,30 +1,39 @@
1
1
  import { pbkdf2 as _pbkdf2, createCipheriv, createDecipheriv, randomBytes } from 'node:crypto';
2
- import { PBKDF2_ITERATIONS, PBKDF2_SALT_SIZE, type EncryptionResult, AES_IV_SIZE, AES_KEY_SIZE } from './common.js';
2
+ import {
3
+ PBKDF2_ITERATIONS,
4
+ NONCE_SIZE,
5
+ AES_TAG_SIZE,
6
+ AES_KEY_SIZE,
7
+ type EncryptedData,
8
+ type PlainData,
9
+ } from './common.js';
3
10
  import { promisify } from 'node:util';
4
11
  import { toUint8Array } from '../utils.js';
5
12
 
13
+ const pbkdf2 = promisify(_pbkdf2);
6
14
  const aesKdf = (passphrase: string, salt: Uint8Array): Promise<Buffer> => {
7
- return promisify(_pbkdf2)(passphrase, salt, PBKDF2_ITERATIONS, AES_KEY_SIZE, 'sha256');
15
+ return pbkdf2(passphrase, salt, PBKDF2_ITERATIONS, AES_KEY_SIZE, 'sha256');
8
16
  };
9
17
 
10
18
  /** nodejs encrypt */
11
- export async function encrypt(data: Uint8Array, passphrase: string): Promise<EncryptionResult> {
12
- const salt = randomBytes(PBKDF2_SALT_SIZE);
13
- const key = await aesKdf(passphrase, salt);
14
- const iv = randomBytes(AES_IV_SIZE);
15
- const cipher = createCipheriv('aes-256-cbc', key, iv);
16
- const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
19
+ export async function encrypt({ data, aad }: PlainData, passphrase: string): Promise<EncryptedData> {
20
+ const nonce = randomBytes(NONCE_SIZE);
21
+ const key = await aesKdf(passphrase, nonce);
22
+ const cipher = createCipheriv('aes-256-gcm', key, nonce, { authTagLength: AES_TAG_SIZE });
23
+ if (aad) cipher.setAAD(aad);
24
+ const encrypted = Buffer.concat([cipher.update(data), cipher.final(), cipher.getAuthTag()]);
17
25
  return {
18
- salt: toUint8Array(salt),
19
- iv: toUint8Array(iv),
26
+ nonce: toUint8Array(nonce),
20
27
  data: toUint8Array(encrypted),
21
28
  };
22
29
  }
23
30
 
24
31
  /** nodejs decrypt */
25
- export async function decrypt({ data, iv, salt }: EncryptionResult, passphrase: string): Promise<Uint8Array> {
26
- const key = await aesKdf(passphrase, salt);
27
- const decipher = createDecipheriv('aes-256-cbc', key, iv);
28
- const decrypted = Buffer.concat([decipher.update(data), decipher.final()]);
29
- return toUint8Array(decrypted);
32
+ export async function decrypt({ nonce, aad, data }: EncryptedData, passphrase: string): Promise<PlainData> {
33
+ const key = await aesKdf(passphrase, nonce);
34
+ const decipher = createDecipheriv('aes-256-gcm', key, nonce, { authTagLength: AES_TAG_SIZE });
35
+ decipher.setAuthTag(data.subarray(data.length - AES_TAG_SIZE));
36
+ if (aad) decipher.setAAD(aad);
37
+ const decrypted = Buffer.concat([decipher.update(data.subarray(0, data.length - AES_TAG_SIZE)), decipher.final()]);
38
+ return { data: toUint8Array(decrypted) };
30
39
  }
@@ -1,62 +1,105 @@
1
- import { pbkdf2, createSHA256 } from 'hash-wasm';
2
- import AES from 'crypto-js/aes.js';
3
- import WordArray from 'crypto-js/lib-typedarrays.js';
4
- import type CryptoJS from 'crypto-js';
5
- import { AES_IV_SIZE, AES_KEY_SIZE, PBKDF2_SALT_SIZE, type EncryptionResult, PBKDF2_ITERATIONS } from './common.js';
1
+ import sjcl from 'sjcl';
2
+ import {
3
+ NONCE_SIZE,
4
+ AES_KEY_SIZE,
5
+ AES_TAG_SIZE,
6
+ type EncryptedData,
7
+ PBKDF2_ITERATIONS,
8
+ type PlainData,
9
+ } from './common.js';
10
+
11
+ // Load unminified version for debugging
12
+ // globalThis.sjcl = sjcl;
13
+ // // @ts-expect-error sjcl is not a module
14
+ // await import('sjcl/core/aes.js');
15
+ // // @ts-expect-error sjcl is not a module
16
+ // await import('sjcl/core/gcm.js');
17
+ // // @ts-expect-error sjcl is not a module
18
+ // await import('sjcl/core/bitArray.js');
19
+ // // @ts-expect-error sjcl is not a module
20
+ // await import('sjcl/core/pbkdf2.js');
21
+ // // @ts-expect-error sjcl is not a module
22
+ // await import('sjcl/core/hmac.js');
23
+ // // @ts-expect-error sjcl is not a module
24
+ // await import('sjcl/core/sha256.js');
6
25
 
7
26
  /** Convert word array to buffer data */
8
- function wordArrayToBuffer(wordArray: WordArray): Uint8Array {
9
- const { sigBytes, words } = wordArray;
10
- if (sigBytes < 0 || words.length * 4 < sigBytes) throw new Error('Invalid word array');
11
- const result = new Uint8Array(sigBytes);
12
- for (let i = 0; i < sigBytes; i++) {
13
- result[i] = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
27
+ function wordArrayToBuffer(bitArray: sjcl.BitArray): Uint8Array {
28
+ const len = sjcl.bitArray.bitLength(bitArray) / 8;
29
+ const out = new Uint8Array(len);
30
+ for (let i = 0; i < len; i += 4) {
31
+ const tmp = bitArray[i / 4];
32
+ out[i] = (tmp >>> 24) & 0xff;
33
+ out[i + 1] = (tmp >>> 16) & 0xff;
34
+ out[i + 2] = (tmp >>> 8) & 0xff;
35
+ out[i + 3] = tmp & 0xff;
14
36
  }
15
- return result;
37
+ return out;
16
38
  }
17
39
 
18
40
  /** Convert buffer data to word array */
19
- function bufferToWordArray(buffer: Uint8Array): WordArray {
20
- return WordArray.create(buffer);
41
+ function bufferToWordArray(buffer: Uint8Array): sjcl.BitArray {
42
+ const out = [];
43
+ const length = buffer.byteLength;
44
+ for (let i = 0; i < length; i += 4) {
45
+ out.push((buffer[i] << 24) | (buffer[i + 1] << 16) | (buffer[i + 2] << 8) | buffer[i + 3]);
46
+ }
47
+ if (length & 3) {
48
+ out[out.length - 1] = sjcl.bitArray.partial(8 * (length & 3), out[out.length - 1], 1);
49
+ }
50
+ return out;
21
51
  }
22
52
 
23
53
  /** Create aes params */
24
- async function aesKdfJs(passphrase: string, salt: Uint8Array): Promise<WordArray> {
25
- const result = await pbkdf2({
26
- password: passphrase,
27
- salt: salt,
28
- iterations: PBKDF2_ITERATIONS,
29
- hashLength: AES_KEY_SIZE,
30
- hashFunction: createSHA256(),
31
- outputType: 'binary',
32
- });
33
- return WordArray.create(result);
54
+ function aesKdfJs(passphrase: string, salt: sjcl.BitArray): sjcl.BitArray {
55
+ return sjcl.misc.pbkdf2(passphrase, salt, PBKDF2_ITERATIONS, AES_KEY_SIZE * 8, sjcl.misc.hmac);
56
+ }
57
+
58
+ /** wrap non-error thrown */
59
+ function wrapError(error: unknown): Error {
60
+ if (error instanceof Error) {
61
+ return error;
62
+ }
63
+ return new Error(String(error), { cause: error });
34
64
  }
35
65
 
36
66
  /** crypto-js encrypt */
37
- export async function encrypt(data: Uint8Array, passphrase: string): Promise<EncryptionResult> {
38
- const salt = wordArrayToBuffer(WordArray.random(PBKDF2_SALT_SIZE));
39
- const key = await aesKdfJs(passphrase, salt);
40
- const iv = WordArray.random(AES_IV_SIZE);
41
- const encrypted = AES.encrypt(bufferToWordArray(data), key, { iv });
42
- return {
43
- salt: salt,
44
- iv: wordArrayToBuffer(iv),
45
- data: wordArrayToBuffer(encrypted.ciphertext),
46
- };
67
+ export async function encrypt({ data, aad }: PlainData, passphrase: string): Promise<EncryptedData> {
68
+ try {
69
+ const nonce = sjcl.random.randomWords(NONCE_SIZE / 4);
70
+ const key = aesKdfJs(passphrase, nonce);
71
+ const encrypted = sjcl.mode.gcm.encrypt(
72
+ new sjcl.cipher.aes(key),
73
+ bufferToWordArray(data),
74
+ nonce,
75
+ aad ? bufferToWordArray(aad) : undefined,
76
+ AES_TAG_SIZE * 8,
77
+ );
78
+ return await Promise.resolve({
79
+ nonce: wordArrayToBuffer(nonce),
80
+ data: wordArrayToBuffer(encrypted),
81
+ });
82
+ } catch (ex) {
83
+ throw wrapError(ex);
84
+ }
47
85
  }
48
86
 
49
87
  /** crypto-js decrypt */
50
- export async function decrypt({ data, iv, salt }: EncryptionResult, passphrase: string): Promise<Uint8Array> {
51
- const key = await aesKdfJs(passphrase, salt);
52
- const decrypted = AES.decrypt(
53
- {
54
- ciphertext: bufferToWordArray(data),
55
- } as CryptoJS.lib.CipherParams,
56
- key,
57
- {
58
- iv: bufferToWordArray(iv),
59
- },
60
- );
61
- return wordArrayToBuffer(decrypted);
88
+ export async function decrypt({ data, aad, nonce }: EncryptedData, passphrase: string): Promise<PlainData> {
89
+ try {
90
+ const n = bufferToWordArray(nonce);
91
+ const key = aesKdfJs(passphrase, n);
92
+ const decrypted = sjcl.mode.gcm.decrypt(
93
+ new sjcl.cipher.aes(key),
94
+ bufferToWordArray(data),
95
+ n,
96
+ aad ? bufferToWordArray(aad) : undefined,
97
+ AES_TAG_SIZE * 8,
98
+ );
99
+ return await Promise.resolve({
100
+ data: wordArrayToBuffer(decrypted),
101
+ });
102
+ } catch (ex) {
103
+ throw wrapError(ex);
104
+ }
62
105
  }
@@ -1,4 +1,11 @@
1
- import { AES_IV_SIZE, AES_KEY_SIZE, PBKDF2_SALT_SIZE, type EncryptionResult, PBKDF2_ITERATIONS } from './common.js';
1
+ import {
2
+ NONCE_SIZE,
3
+ AES_TAG_SIZE,
4
+ AES_KEY_SIZE,
5
+ type EncryptedData,
6
+ type PlainData,
7
+ PBKDF2_ITERATIONS,
8
+ } from './common.js';
2
9
 
3
10
  const encoder = new TextEncoder();
4
11
 
@@ -11,42 +18,44 @@ async function aesKdfWeb(passphrase: string, salt: Uint8Array): Promise<CryptoKe
11
18
  iterations: PBKDF2_ITERATIONS,
12
19
  hash: 'SHA-256',
13
20
  };
14
- return await crypto.subtle.deriveKey(pbkdf2Params, pass, { name: 'AES-CBC', length: AES_KEY_SIZE * 8 }, false, [
21
+ return await crypto.subtle.deriveKey(pbkdf2Params, pass, { name: 'AES-GCM', length: AES_KEY_SIZE * 8 }, false, [
15
22
  'encrypt',
16
23
  'decrypt',
17
24
  ]);
18
25
  }
19
26
 
20
27
  /** webcrypto encrypt */
21
- export async function encrypt(data: Uint8Array, passphrase: string): Promise<EncryptionResult> {
22
- const salt = crypto.getRandomValues(new Uint8Array(PBKDF2_SALT_SIZE));
23
- const key = await aesKdfWeb(passphrase, salt);
24
- const iv = crypto.getRandomValues(new Uint8Array(AES_IV_SIZE));
28
+ export async function encrypt({ data, aad }: PlainData, passphrase: string): Promise<EncryptedData> {
29
+ const nonce = crypto.getRandomValues(new Uint8Array(NONCE_SIZE));
30
+ const key = await aesKdfWeb(passphrase, nonce);
25
31
  const encrypted = await crypto.subtle.encrypt(
26
32
  {
27
- name: 'AES-CBC',
28
- iv,
33
+ name: 'AES-GCM',
34
+ iv: nonce,
35
+ tagLength: AES_TAG_SIZE * 8,
36
+ additionalData: aad,
29
37
  },
30
38
  key,
31
39
  data,
32
40
  );
33
41
  return {
34
- salt: salt,
35
- iv: iv,
42
+ nonce,
36
43
  data: new Uint8Array(encrypted),
37
44
  };
38
45
  }
39
46
 
40
47
  /** webcrypto decrypt */
41
- export async function decrypt({ data, salt, iv }: EncryptionResult, passphrase: string): Promise<Uint8Array> {
42
- const key = await aesKdfWeb(passphrase, salt);
48
+ export async function decrypt({ data, nonce, aad }: EncryptedData, passphrase: string): Promise<PlainData> {
49
+ const key = await aesKdfWeb(passphrase, nonce);
43
50
  const decrypted = await crypto.subtle.decrypt(
44
51
  {
45
- name: 'AES-CBC',
46
- iv,
52
+ name: 'AES-GCM',
53
+ iv: nonce,
54
+ tagLength: AES_TAG_SIZE * 8,
55
+ additionalData: aad,
47
56
  },
48
57
  key,
49
58
  data,
50
59
  );
51
- return new Uint8Array(decrypted);
60
+ return { data: new Uint8Array(decrypted) };
52
61
  }
package/src/index.ts CHANGED
@@ -1 +1 @@
1
- export { isEncrypted, encrypt, decrypt } from './encryption/index.js';
1
+ export { isEncrypted, encrypt, decrypt, encryptAad, extractAad } from './encryption/index.js';