client-index.ts
Raw
1async function encrypt(content: Uint8Array, password: string): Promise<ArrayBuffer> {
2 const iv = crypto.getRandomValues(new Uint8Array(16))
3 const salt = crypto.getRandomValues(new Uint8Array(16))
4 const keyMaterial = await crypto.subtle.importKey(
5 "raw",
6 new TextEncoder().encode(password),
7 { name: "PBKDF2" },
8 false,
9 ["deriveBits", "deriveKey"]
10 )
11 const key = await crypto.subtle.deriveKey(
12 {
13 name: "PBKDF2",
14 salt: salt,
15 iterations: 100000,
16 hash: "SHA-512"
17 },
18 keyMaterial,
19 { name: "AES-CBC", length: 256 },
20 false,
21 ["encrypt"]
22 )
23 const encryptedContent = await crypto.subtle.encrypt(
24 { name: "AES-CBC", iv: iv },
25 key,
26 content
27 )
28 return new Uint8Array([...salt, ...iv, ...new Uint8Array(encryptedContent)]).buffer
29}
30
31async function uploadFile() {
32 const passwordInput = document.getElementById("password") as HTMLInputElement | null
33 const fileInput = document.getElementById("file") as HTMLInputElement | null
34 const filenameInput = document.getElementById("filename") as HTMLInputElement | null
35 const encryptedInput = document.getElementById("encrypted") as HTMLInputElement | null
36 const form = document.getElementById("uploadForm") as HTMLFormElement | null
37
38 if (!passwordInput || !fileInput || !filenameInput || !encryptedInput || !form) {
39 console.error("Missing required elements.")
40 console.error(passwordInput, fileInput, filenameInput, encryptedInput, form)
41 return
42 }
43
44 const password = passwordInput.value;
45 if (!password) {
46 form.submit()
47 return
48 }
49
50 const file = fileInput.files?.[0];
51 if (!file) {
52 return
53 }
54
55 const content = await file.bytes()
56 const encryptedContent = await encrypt(content, password)
57
58 const myFile = new File([encryptedContent], file.name)
59 const dataTransfer = new DataTransfer()
60 dataTransfer.items.add(myFile)
61
62 fileInput.files = dataTransfer.files
63 encryptedInput.checked = true
64 console.log("encryption done")
65 form.submit()
66}
67
68(document.getElementById("uploadForm") as HTMLFormElement | null)?.reset()
69
70const jsguards = document.getElementsByClassName("jsguard")
71for (let i = 0; i < jsguards.length; i++) {
72 jsguards[i].remove()
73}
74
75window.uploadFile = uploadFile
76
77