Skip to content

Commit 1874984

Browse files
committed
Added additional error handling for key generation / encryption actions
1 parent 7aa21c3 commit 1874984

File tree

1 file changed

+42
-31
lines changed

1 file changed

+42
-31
lines changed

src/utils/encryption.ts

Lines changed: 42 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
1-
import CryptoJS from "crypto-js";
2-
3-
41
export const generateAndStoreKey = async (userId: string) => {
5-
const key = await crypto.subtle.generateKey(
6-
{
7-
name: "AES-GCM",
8-
length: 256,
9-
},
10-
true,
11-
["encrypt", "decrypt"]
12-
);
13-
14-
const exportedKey = await crypto.subtle.exportKey("raw", key);
15-
const keyString = btoa(String.fromCharCode(...new Uint8Array(exportedKey)));
2+
try {
3+
const key = await crypto.subtle.generateKey(
4+
{
5+
name: "AES-GCM",
6+
length: 256,
7+
},
8+
true,
9+
["encrypt", "decrypt"]
10+
);
11+
12+
const exportedKey = await crypto.subtle.exportKey("raw", key);
13+
const keyString = btoa(String.fromCharCode(...new Uint8Array(exportedKey)));
1614

1715
localStorage.setItem(`encryptionKey-${userId}`, keyString);
1816

19-
return key;
17+
return key;
18+
} catch (error) {
19+
console.error('Key generation failed:', error);
20+
throw new Error('Failed to generate encryption key');
21+
}
2022
};
2123

2224
export const retrieveKey = async (userId: string) => {
@@ -35,6 +37,10 @@ export const retrieveKey = async (userId: string) => {
3537

3638

3739
export const encrypt = async (data: string, userId: string) => {
40+
if (!data || !userId) {
41+
throw new Error('Data and userId are required');
42+
}
43+
3844
const key = await retrieveKey(userId);
3945
const encoder = new TextEncoder();
4046
const encodedData = encoder.encode(data);
@@ -61,20 +67,25 @@ export const decrypt = async (
6167
iv: string,
6268
userId: string
6369
): Promise<string> => {
64-
const key = await retrieveKey(userId);
65-
const decoder = new TextDecoder();
66-
67-
const encryptedBuffer = Uint8Array.from(atob(encryptedData), (char) => char.charCodeAt(0));
68-
const ivBuffer = Uint8Array.from(atob(iv), (char) => char.charCodeAt(0));
69-
70-
const decryptedBuffer = await crypto.subtle.decrypt(
71-
{
72-
name: "AES-GCM",
73-
iv: ivBuffer,
74-
},
75-
key,
76-
encryptedBuffer
77-
);
78-
79-
return decoder.decode(decryptedBuffer);
70+
try {
71+
const key = await retrieveKey(userId);
72+
const decoder = new TextDecoder();
73+
74+
const encryptedBuffer = Uint8Array.from(atob(encryptedData), (char) => char.charCodeAt(0));
75+
const ivBuffer = Uint8Array.from(atob(iv), (char) => char.charCodeAt(0));
76+
77+
const decryptedBuffer = await crypto.subtle.decrypt(
78+
{
79+
name: "AES-GCM",
80+
iv: ivBuffer,
81+
},
82+
key,
83+
encryptedBuffer
84+
);
85+
86+
return decoder.decode(decryptedBuffer);
87+
} catch (error) {
88+
console.error('Decryption failed:', error);
89+
throw new Error('Failed to decrypt data');
90+
}
8091
};

0 commit comments

Comments
 (0)