@@ -110,22 +110,28 @@ export async function decryptKey(
110110 return new Uint8Array ( decrypted ) . toBase64 ( ) ;
111111}
112112
113- export async function encryptData (
114- data : Uint8Array < ArrayBuffer > ,
115- noteKey : string ,
116- ) : Promise < Uint8Array > {
117- const keyBuffer = Uint8Array . fromBase64 ( noteKey ) ;
118- const key = await crypto . subtle . importKey (
113+ async function getCryptoKeyFromBase64 ( base64Key : string ) : Promise < CryptoKey > {
114+ const keyBuffer = Uint8Array . fromBase64 ( base64Key ) ;
115+ return crypto . subtle . importKey (
119116 "raw" ,
120117 keyBuffer ,
121118 {
122119 name : "AES-GCM" ,
123120 } ,
124121 false ,
125- [ "encrypt" ] ,
122+ [ "encrypt" , "decrypt" ] ,
126123 ) ;
124+ }
125+
126+ const IV_LENGTH = 12 ; // AES-GCM standard IV length
127127
128- const iv = crypto . getRandomValues ( new Uint8Array ( 12 ) ) ;
128+ export async function encryptData (
129+ data : Uint8Array < ArrayBuffer > ,
130+ noteKey : string ,
131+ ) : Promise < Uint8Array > {
132+ const key = await getCryptoKeyFromBase64 ( noteKey ) ;
133+
134+ const iv = crypto . getRandomValues ( new Uint8Array ( IV_LENGTH ) ) ;
129135 const encrypted = await crypto . subtle . encrypt (
130136 {
131137 name : "AES-GCM" ,
@@ -147,20 +153,11 @@ export async function decryptData(
147153 encrypted : Uint8Array ,
148154 noteKey : string ,
149155) : Promise < Uint8Array > {
150- const keyBuffer = Uint8Array . fromBase64 ( noteKey ) ;
151- const key = await crypto . subtle . importKey (
152- "raw" ,
153- keyBuffer ,
154- {
155- name : "AES-GCM" ,
156- } ,
157- false ,
158- [ "decrypt" ] ,
159- ) ;
156+ const key = await getCryptoKeyFromBase64 ( noteKey ) ;
160157
161158 // Extract IV from first 12 bytes
162- const iv = encrypted . slice ( 0 , 12 ) ;
163- const data = encrypted . slice ( 12 ) ;
159+ const iv = encrypted . slice ( 0 , IV_LENGTH ) ;
160+ const data = encrypted . slice ( IV_LENGTH ) ;
164161
165162 const decrypted = await crypto . subtle . decrypt (
166163 {
0 commit comments