1
- import CryptoJS from "crypto-js" ;
2
-
3
-
4
1
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 ) ) ) ;
16
14
17
15
localStorage . setItem ( `encryptionKey-${ userId } ` , keyString ) ;
18
16
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
+ }
20
22
} ;
21
23
22
24
export const retrieveKey = async ( userId : string ) => {
@@ -35,6 +37,10 @@ export const retrieveKey = async (userId: string) => {
35
37
36
38
37
39
export const encrypt = async ( data : string , userId : string ) => {
40
+ if ( ! data || ! userId ) {
41
+ throw new Error ( 'Data and userId are required' ) ;
42
+ }
43
+
38
44
const key = await retrieveKey ( userId ) ;
39
45
const encoder = new TextEncoder ( ) ;
40
46
const encodedData = encoder . encode ( data ) ;
@@ -61,20 +67,25 @@ export const decrypt = async (
61
67
iv : string ,
62
68
userId : string
63
69
) : 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
+ }
80
91
} ;
0 commit comments