forked from qwertycxz/NUIST-VPN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bg.js
75 lines (63 loc) · 2.3 KB
/
bg.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
// 将字符串转换为 ArrayBuffer
function str2ab(str) {
var buf = new ArrayBuffer(str.length);
var bufView = new Uint8Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
// 将 ArrayBuffer 转换为十六进制字符串
function ab2hex(buffer) {
return Array.prototype.map.call(new Uint8Array(buffer), x => ('00' + x.toString(16)).slice(-2)).join('');
}
// AES-CBC 加密函数
async function encrypt(domainWithPort) {
const key = await crypto.subtle.importKey(
"raw",
str2ab("CASB2021EnLink!!"),
{ name: "AES-CBC" },
false,
["encrypt"]
);
const iv = str2ab("CASB2021EnLink!!");
const encrypted = await crypto.subtle.encrypt(
{
name: "AES-CBC",
iv: iv
},
key,
str2ab(domainWithPort)
);
return ab2hex(encrypted);
}
// 监听 action 点击事件
chrome.action.onClicked.addListener(async function (tab) {
// 目标 VPN 地址前缀
const httpsVpnPrefix = "https://vpn.njupt.edu.cn:8443/https/webvpn";
const httpVpnPrefix = "https://vpn.njupt.edu.cn:8443/http/webvpn";
// 解析当前 URL
let url = new URL(tab.url);
let domainWithPort = url.host; // 包括域名和端口(如果有)
if (url.protocol === "https:") {
// 如果协议是 HTTPS
if (!tab.url.startsWith(httpsVpnPrefix)) {
// 使用 AES-CBC 加密域名+端口
let encryptedDomain = await encrypt(domainWithPort);
// 构造新的 URL
let newUrl = httpsVpnPrefix + encryptedDomain + url.pathname + url.search + url.hash;
// 跳转到新的 URL
chrome.tabs.create({ url: newUrl });
}
} else if (url.protocol === "http:") {
// 如果协议是 HTTP
if (!tab.url.startsWith(httpVpnPrefix)) {
// 使用 AES-CBC 加密域名+端口
let encryptedDomain = await encrypt(domainWithPort);
// 构造新的 URL
let newUrl = httpVpnPrefix + encryptedDomain + url.pathname + url.search + url.hash;
// 跳转到新的 URL
chrome.tabs.create({ url: newUrl });
}
}
});