Skip to content

Commit 62e6795

Browse files
save file
1 parent 1fa5e3f commit 62e6795

1 file changed

Lines changed: 94 additions & 0 deletions

File tree

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
2+
3+
4+
/*
5+
6+
7+
aes encrypt / decrypt
8+
9+
10+
30-04-26
11+
12+
13+
*/
14+
15+
16+
(async()=>{
17+
console.clear();
18+
19+
20+
var key = await generateAesKey();
21+
var encrypted = await aesEncrypt(key,'hello world');
22+
var txt = await aesDecrypt(key,encrypted);
23+
24+
console.log(txt);
25+
26+
27+
28+
async function generateAesKey() {
29+
30+
var key = await crypto.subtle.generateKey({name:"AES-GCM",length: 256},true,["encrypt", "decrypt"]);
31+
return key;
32+
33+
}//generateAesKey
34+
35+
36+
async function exportAesKey(key) {
37+
38+
const raw = await crypto.subtle.exportKey("raw", key);
39+
var b64 = btoa(String.fromCharCode(...new Uint8Array(raw)));
40+
return b64;
41+
42+
}//exportAesKey
43+
44+
45+
async function importAesKey(base64) {
46+
47+
const raw = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
48+
var key = await crypto.subtle.importKey("raw",raw,"AES-GCM",true,["encrypt", "decrypt"]);
49+
return key;
50+
51+
}//importAesKey
52+
53+
54+
async function aesEncrypt(key, plaintext) {
55+
56+
const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV recommended
57+
58+
const encoded = new TextEncoder().encode(plaintext);
59+
60+
const ciphertext = await crypto.subtle.encrypt({name: "AES-GCM",iv},key,encoded);
61+
62+
return {
63+
iv: btoa(String.fromCharCode(...iv)),
64+
data: btoa(String.fromCharCode(...new Uint8Array(ciphertext))),
65+
};
66+
67+
}//aesEncrypt
68+
69+
70+
async function aesDecrypt(key, encrypted) {
71+
72+
const iv = Uint8Array.from(atob(encrypted.iv), c => c.charCodeAt(0));
73+
const data = Uint8Array.from(atob(encrypted.data), c => c.charCodeAt(0));
74+
75+
const plaintext = await crypto.subtle.decrypt(
76+
{
77+
name: "AES-GCM",
78+
iv,
79+
},
80+
key,
81+
data
82+
);
83+
84+
return new TextDecoder().decode(plaintext);
85+
86+
}//aesDecrypt
87+
88+
89+
90+
91+
})();
92+
93+
94+

0 commit comments

Comments
 (0)