1+ export async function generateAESKey ( ) : Promise < string > {
2+ const key = crypto . getRandomValues ( new Uint8Array ( 16 ) ) ;
3+ return btoa ( String . fromCharCode ( ...key ) ) ;
4+ }
5+
6+ function base64ToUint8Array ( base64 : string ) : Uint8Array {
7+ const binary = atob ( base64 ) ;
8+ const bytes = new Uint8Array ( binary . length ) ;
9+ for ( let i = 0 ; i < binary . length ; i ++ ) {
10+ bytes [ i ] = binary . charCodeAt ( i ) ;
11+ }
12+ return bytes ;
13+ }
14+
115export async function encryptData (
216 plainText : string ,
317 key : string
418) : Promise < string > {
5- const enc = new TextEncoder ( ) ;
619 const iv = crypto . getRandomValues ( new Uint8Array ( 12 ) ) ;
720 const alg = { name : "AES-GCM" , iv } ;
821
9- const cryptoKey = await crypto . subtle . importKey (
10- "raw" ,
11- enc . encode ( key ) ,
12- alg ,
13- false ,
14- [ "encrypt" ]
15- ) ;
22+ const rawKey = base64ToUint8Array ( key ) ;
23+
24+ const cryptoKey = await crypto . subtle . importKey ( "raw" , rawKey , alg , false , [
25+ "encrypt" ,
26+ ] ) ;
1627
1728 const encrypted = await crypto . subtle . encrypt (
1829 alg ,
1930 cryptoKey ,
20- enc . encode ( plainText )
31+ new TextEncoder ( ) . encode ( plainText )
2132 ) ;
2233
2334 const combined = new Uint8Array ( iv . byteLength + encrypted . byteLength ) ;
@@ -31,22 +42,21 @@ export async function decryptData(
3142 cipherText : string ,
3243 key : string
3344) : Promise < string > {
34- const enc = new TextEncoder ( ) ;
3545 const combined = Uint8Array . from ( atob ( cipherText ) , ( c ) => c . charCodeAt ( 0 ) ) ;
3646 const iv = combined . slice ( 0 , 12 ) ;
3747 const data = combined . slice ( 12 ) ;
3848
49+ const rawKey = base64ToUint8Array ( key ) ;
3950 const alg = { name : "AES-GCM" , iv } ;
4051
4152 const cryptoKey = await crypto . subtle . importKey (
4253 "raw" ,
43- enc . encode ( key ) ,
54+ rawKey ,
4455 alg ,
4556 false ,
4657 [ "decrypt" ]
4758 ) ;
4859
4960 const decrypted = await crypto . subtle . decrypt ( alg , cryptoKey , data ) ;
50-
5161 return new TextDecoder ( ) . decode ( decrypted ) ;
52- }
62+ }
0 commit comments