-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCryptStore.js
286 lines (248 loc) · 6.89 KB
/
CryptStore.js
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
// Based on https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/encrypt
// Based on https://github.com/plamikcho/local-storage-encrypt
// Encoder based on https://github.com/plamikcho/local-storage-encrypt/blob/master/src/encoder.js
export function bufferToString(ab) {
let bytes = new Uint8Array(ab);
let str = new TextDecoder().decode(bytes);
return str
}
export function stringToBuffer(str) {
let bytes = new TextEncoder().encode(str);
return bytes.buffer;
}
/* @type {Uint8ArrayToHex} */
export function toHex(bytes) {
/** @type {Array<String>} */
let hex = [];
bytes.forEach(function (b) {
let h = b.toString(16);
h = h.padStart(2, "0");
hex.push(h);
});
return hex.join("");
};
/* @type {HexToUint8Array} */
export function toBytes(hex) {
let len = hex.length / 2;
let bytes = new Uint8Array(len);
let index = 0;
for (let i = 0; i < hex.length; i += 2) {
let c = hex.slice(i, i + 2);
let b = parseInt(c, 16);
bytes[index] = b;
index += 1;
}
return bytes;
};
export function bufferToHex(buf) {
let bytes = new Uint8Array(buf)
let hex = toHex(bytes)
return hex
}
export function hexToBuffer(hex) {
let bytes = toBytes(hex)
return bytes.buffer
}
/**
* Creates an instance of PbCrypto with encrypt and decrypt operations
*
* @param {String} password
* @param {String} salt
* @param {Crypto} currentCrypto - window.crypto instance
*/
export function encryptMsg(
password, salt, currentCrypto = window.crypto
) {
const name = 'AES-GCM';
const targets = ["encrypt", "decrypt"];
const pbkdfName = 'PBKDF2';
const hash = { name: 'SHA-256', length: 256 };
const iterations = 1000;
const deriveKey = async (password, salt, currentCrypto = window.crypto) => {
const keyMaterial = await currentCrypto.subtle.importKey(
"raw",
stringToBuffer(password),
{ name: pbkdfName },
false,
["deriveBits", "deriveKey"]
);
return currentCrypto.subtle.deriveKey(
{
name: pbkdfName,
salt: stringToBuffer(salt),
iterations,
hash: hash.name,
},
keyMaterial,
{ name, length: hash.length },
true,
// @ts-ignore
targets,
);
};
async function encrypt(message, iv) {
if ('string' === typeof iv) {
iv = hexToBuffer(iv)
}
return await deriveKey(password, salt)
.then(async cryptoKey => await currentCrypto.subtle.encrypt(
{ name, iv },
cryptoKey,
stringToBuffer(message)
))
.then(enc => bufferToHex(enc));
}
async function decrypt(ciphertext, iv) {
if ('string' === typeof iv) {
iv = hexToBuffer(iv)
}
return await deriveKey(password, salt)
.then(async function (cryptoKey) {
let dec = await currentCrypto.subtle.decrypt(
{ name, iv },
cryptoKey,
hexToBuffer(ciphertext)
)
return dec
})
.then(dec => bufferToString(dec));
}
function getInitVector () {
return currentCrypto.getRandomValues(new Uint8Array(16));
}
return { encrypt, decrypt, getInitVector }
}
export const isBrowserSupported = async () => {
const testMessage = 'w?';
try {
const cryptoWrapper = encryptMsg('a', 'b');
const iv = cryptoWrapper.getInitVector();
const encrypted = await cryptoWrapper.encrypt(testMessage, iv);
const decrypted = await cryptoWrapper.decrypt(encrypted, iv);
return decrypted === testMessage;
} catch (error) {
console.warn('Your browser does not support WebCrypto API', error);
return false;
}
}
/**
* Gets encrypted storage with async getItem and setItem
*
* @param {Storage} storage Browser storage - localStorage, sessionStorage
* @param {Encryptage} cryptoWrapper Crypto
*/
export async function getEncryptedStorageFromCrypto(
storage,
cryptoWrapper,
ivKey = null // 'encryptage'
) {
let isSupported;
// const getInitVectorKey = key => `${key}_iv`;
const getInitVectorKey = (key) => `${ivKey || key}_iv`;
const unmodifiedFunctions = {
clear() {
storage.clear();
},
get length() {
return storage.length;
},
key(i) {
return storage.key(i);
},
};
const setBrowserSupport = async () => {
if (typeof isSupported === 'undefined') {
isSupported = await isBrowserSupported();
}
};
await setBrowserSupport();
if (isSupported && ivKey) {
// const iv = cryptoWrapper.getInitVector();
let iv = storage.getItem(getInitVectorKey()) ||
cryptoWrapper.getInitVector();
if ('string' !== typeof iv) {
iv = bufferToHex(iv)
}
console.log(
'isSupported && ivKey',
iv,
// stringToBuffer(iv),
// hexToBuffer(iv),
)
storage.setItem(
getInitVectorKey(),
iv,
);
}
return {
...storage,
async setItem(key, value) {
await setBrowserSupport();
if (isSupported) {
try {
const iv = storage.getItem(getInitVectorKey(key)) ||
cryptoWrapper.getInitVector();
const encrypted = await cryptoWrapper.encrypt(value, iv);
storage.setItem(key, String(encrypted));
if (!ivKey) {
storage.setItem(
getInitVectorKey(key),
bufferToHex(iv),
);
}
}
catch (error) {
console.error(`Cannot set encrypted value for ${key}. Error: ${error}`);
throw error;
}
} else {
storage.setItem(key, value); // legacy mode, no encryption
}
},
async getItem(key) {
await setBrowserSupport();
if (isSupported) {
try {
const data = storage.getItem(key);
const iv = storage.getItem(getInitVectorKey(key));
const decrypted = await cryptoWrapper.decrypt(data, iv);
return decrypted;
}
catch (error) {
console.error(`Cannot get encrypted item for ${key}. Error: ${error}`);
return null;
}
}
return storage.getItem(key); // legacy mode, no encryption
},
async hasItem(key) {
const data = storage.getItem(key);
const iv = storage.getItem(getInitVectorKey(key));
return data !== null && iv !== null
},
removeItem(key) {
storage.removeItem(key);
const ivKey = getInitVectorKey(key);
storage.getItem(ivKey) && storage.removeItem(ivKey);
},
...unmodifiedFunctions,
};
};
export async function getEncryptedStorageFromPassword(
storage, password, salt, ivKey
) {
return await getEncryptedStorageFromCrypto(
storage,
encryptMsg(password, salt),
ivKey,
);
}
export async function getEncryptedStorage(storage, ...args) {
const [arg1, arg2, arg3] = args;
if (typeof arg1 === 'object') { // it is crypto object
return await getEncryptedStorageFromCrypto(storage, arg1, arg2);
}
if (typeof arg1 === 'string' && typeof arg2 === 'string') {
return await getEncryptedStorageFromPassword(storage, arg1, arg2, arg3);
}
};