-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
100 lines (83 loc) · 2.75 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
99
100
// Node.js WebCrypto API
const crypto = require("crypto").webcrypto;
// Utility function to convert an ArrayBuffer to a hex string
function bufferToHex(buffer) {
const byteArray = new Uint8Array(buffer);
return Array.from(byteArray)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
// Utility function to convert a hex string to an ArrayBuffer
function hexToBuffer(hex) {
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < bytes.length; i++) {
bytes[i] = parseInt(hex.substr(i * 2, 2), 16);
}
return bytes.buffer;
}
// Hash the string to produce a key of correct length
async function createKeyFromString(keyString) {
const encoder = new TextEncoder();
const data = encoder.encode(keyString);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
return crypto.subtle.importKey(
"raw",
hashBuffer,
{
name: "AES-GCM",
length: 256,
},
true,
["encrypt", "decrypt"]
);
}
// Encrypt function
async function encryptData(plainText, keyString) {
try {
const key = await createKeyFromString(keyString);
const encoder = new TextEncoder();
const data = encoder.encode(plainText);
const iv = crypto.getRandomValues(new Uint8Array(12));
const cipherText = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: iv,
},
key,
data
);
const tag = cipherText.slice(-16); // Authentication tag
const encryptedBytes = cipherText.slice(0, -16); // Cipher text without tag
return {
iv: bufferToHex(iv),
cipherText: bufferToHex(encryptedBytes),
tag: bufferToHex(tag),
};
} catch (error) {
throw new Error(`Encryption failed: ${error.message}`);
}
}
// Decrypt function
async function decryptData(encryptedData, keyString) {
try {
const key = await createKeyFromString(keyString);
const iv = hexToBuffer(encryptedData.iv);
const cipherText = hexToBuffer(encryptedData.cipherText);
const tag = hexToBuffer(encryptedData.tag);
const cipherTextWithTag = new Uint8Array([...new Uint8Array(cipherText), ...new Uint8Array(tag)]);
const decryptedData = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: iv,
tagLength: 128,
},
key,
cipherTextWithTag
);
const decoder = new TextDecoder();
return decoder.decode(decryptedData);
} catch (error) {
throw new Error(`Decryption failed: ${error.message}`);
}
}
module.exports = { encryptData, decryptData };