-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (85 loc) · 3.03 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
async function generateKeypair() {
const { publicKey, privateKey } = await crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]), // 65537
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
const publicKeyExported = await crypto.subtle.exportKey("spki", publicKey);
const privateKeyExported = await crypto.subtle.exportKey("pkcs8", privateKey);
const publicKeyBase64 = btoa(String.fromCharCode(...new Uint8Array(publicKeyExported)));
const privateKeyBase64 = btoa(String.fromCharCode(...new Uint8Array(privateKeyExported)));
return {
publicKey: publicKeyBase64,
privateKey: privateKeyBase64,
};
}
async function encryptData(data, publicKey) {
const publicKeyImported = await crypto.subtle.importKey(
"spki",
new Uint8Array(atob(publicKey).split("").map((c) => c.charCodeAt(0))),
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["encrypt"]
);
const encryptedData = await crypto.subtle.encrypt(
{
name: "RSA-OAEP",
},
publicKeyImported,
new TextEncoder().encode(data)
);
return btoa(String.fromCharCode(...new Uint8Array(encryptedData)));
}
async function decryptData(encryptedData, privateKey) {
const privateKeyImported = await crypto.subtle.importKey(
"pkcs8",
new Uint8Array(atob(privateKey).split("").map((c) => c.charCodeAt(0))),
{
name: "RSA-OAEP",
hash: "SHA-256",
},
true,
["decrypt"]
);
const decryptedData = await crypto.subtle.decrypt(
{
name: "RSA-OAEP",
},
privateKeyImported,
new Uint8Array(atob(encryptedData).split("").map((c) => c.charCodeAt(0)))
);
return new TextDecoder().decode(decryptedData);
}
async function onEncrypt() {
try {
const publicKey = document.getElementById("publicKey").value;
const data = document.getElementById("encryptData").value;
const encrypted = await encryptData(data, publicKey);
document.getElementById("encryptResult").value = encrypted;
} catch (err) {
alert("Invalid public key");
}
}
async function onDecrypt() {
try {
const privateKey = document.getElementById("privateKey").value;
const data = document.getElementById("decryptData").value;
const decrypted = await decryptData(data, privateKey);
document.getElementById("decryptResult").value = decrypted;
} catch (err) {
alert("Invalid or wrong private key");
}
}
async function onKeyGen() {
const keypair = await generateKeypair();
document.getElementById("generatedPrivateKey").value = keypair.privateKey;
document.getElementById("generatedPublicKey").value = keypair.publicKey;
}