Skip to content

Commit 66d552f

Browse files
save file
1 parent 13f6c22 commit 66d552f

1 file changed

Lines changed: 29 additions & 8 deletions

File tree

blog/26-04-26/x509-certificates-in-js---encrypt-decrypt-data/ex/aes-encrypt-decrypt-browser.js

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,14 @@ aes encrypt / decrypt browser
1919
var blob = new Blob(['hello world']);
2020

2121
var key = await generateAesKey();
22+
var blob = await exportAesKey(key);
23+
console.log('key :',blob.size);
2224
var encrypted = await aesEncrypt(key,blob);
2325
var b64 = await blob_b64(encrypted);
2426
console.log('encrypted :');
2527
console.log(b64);
2628
console.log();
29+
var key = await importAesKey(blob);
2730
var blob = await aesDecrypt(key,encrypted);
2831

2932
var txt = await blob.text();
@@ -48,17 +51,19 @@ aes encrypt / decrypt browser
4851
async function exportAesKey(key){
4952

5053
var buf = await crypto.subtle.exportKey('raw',key);
51-
52-
var b64 = buf_b64(buf);
53-
return b64;
54+
var blob = new Blob([buf]);
55+
return blob;
5456

5557
}//exportAesKey
5658

5759

58-
async function importAesKey(b64){
60+
async function importAesKey(blob){
5961

62+
var buf = await blob.arrayBuffer();
63+
var uint8 = new Uint8Array(buf);
64+
6065
var format = 'raw';
61-
var keydata = b64_uint8(b64);
66+
var keydata = uint8;
6267
var algorithm = 'AES-GCM';
6368
var extractable = true;
6469
var keyusage = ['encrypt','decrypt'];
@@ -136,11 +141,27 @@ aes encrypt / decrypt browser
136141
}//blob_iv_buf
137142

138143

139-
async function blob_b64(blob){
144+
async function blob_uint8(blob){
140145

141146
var buf = await blob.arrayBuffer();
142-
var bytes = new Uint8Array(buf);
143-
var bin = [...bytes].reduce((acc,byte)=>acc+=String.fromCharCode(byte),'');
147+
var uint8 = new Uint8Array(buf);
148+
return uint8;
149+
150+
}//blob_uint8
151+
152+
153+
function uint8_blob(uint8){
154+
155+
var blob = new Blob([uint8]);
156+
return blob;
157+
158+
}//uint8_blob
159+
160+
161+
async function blob_b64(blob){
162+
163+
var uint8 = await blob_uint8(blob);
164+
var bin = [...uint8].reduce((acc,byte)=>acc+=String.fromCharCode(byte),'');
144165
var b64 = btoa(bin);
145166
return b64;
146167

0 commit comments

Comments
 (0)