-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathECDH.js
107 lines (93 loc) · 2.69 KB
/
ECDH.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
99
100
101
102
103
104
105
106
107
const ECDH = {};
//const NAMED_CURVE = "P-521";
const NAMED_CURVE = "P-384";
ECDH.generateKeyPair = async () => {
const canexport = true;
return await window.crypto.subtle.generateKey(
{ name: "ECDH", namedCurve: NAMED_CURVE },
canexport,
["deriveKey"]
);
};
ECDH.getPublicKey = async (keypair) => {
const exported = await window.crypto.subtle.exportKey("raw", keypair.publicKey);
return new Uint8Array(exported);
};
ECDH.getPrivateKey = async (keypair) => {
return await window.crypto.subtle.exportKey("jwk", keypair.privateKey);
};
ECDH.importKeyPair = async (pubkey, prikey) => {
const canexport = false;
try {
const publicKey = await window.crypto.subtle.importKey(
"raw",
pubkey,
{ name: "ECDH", namedCurve: NAMED_CURVE },
canexport,
[]
);
const privateKey = await window.crypto.subtle.importKey(
"jwk",
prikey,
{ name: "ECDH", namedCurve: NAMED_CURVE },
canexport,
["deriveKey"]
);
return { publicKey, privateKey };
} catch (e) {
console.log(e);
return null;
}
};
ECDH.deriveSecretKey = async (keypair, publicKey) => {
const canexport = true;
const importedKey = await window.crypto.subtle.importKey(
"raw",
publicKey,
{ name: "ECDH", namedCurve: NAMED_CURVE },
canexport,
[]
);
return await window.crypto.subtle.deriveKey(
{ name: "ECDH", public: importedKey },
keypair.privateKey,
{ name: "AES-GCM", length: 256 },
canexport,
["encrypt", "decrypt"]
);
};
ECDH.exportSecretKey = async (key) => {
const exported = await window.crypto.subtle.exportKey("raw", key);
return new Uint8Array(exported);
};
ECDH.importSecretKey = async (key) => {
const canexport = true;
return await window.crypto.subtle.importKey(
"raw",
key,
{ name: "AES-GCM", length: 256 },
canexport,
["encrypt", "decrypt"]
);
};
ECDH.encrypt = async (secretKey, plaintext) => {
const iv = window.crypto.getRandomValues(new Uint8Array(12));
const ciphertextabuf = await window.crypto.subtle.encrypt({ name: "AES-GCM", iv }, secretKey, plaintext);
const ciphertext = new Uint8Array(ciphertextabuf);
return { iv, ciphertext };
};
ECDH.encryptText = async (secretKey, plaintexts) => {
return await ECDH.encrypt(secretKey, new TextEncoder().encode(plaintexts));
};
ECDH.decrypt = async (secretKey, iv, ciphertext) => {
const decrypted = await window.crypto.subtle.decrypt({ name: "AES-GCM", iv }, secretKey, ciphertext);
return decrypted;
};
ECDH.decryptText = async (secretKey, iv, ciphertext) => {
try {
return new TextDecoder().decode(await ECDH.decrypt(secretKey, iv, ciphertext));
} catch (e) {
return "error!! " + e;
}
};
export { ECDH };