-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencrypt.ts
59 lines (47 loc) · 1.6 KB
/
encrypt.ts
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
import { encodeToString } from "https://deno.land/std@v0.50.0/encoding/hex.ts";
import { concat } from "https://deno.land/std/bytes/mod.ts";
import { encrypt } from "./aes.ts";
import { deflate_encode_raw } from "./flate.ts";
import {
curry,
pipe,
randomBytes,
collectFromBuffer,
withPadding
} from "./helpers.ts";
const encodeBuffer = async (buffer: Deno.Reader): Promise<Uint8Array> => {
const stream = Deno.iter(buffer);
let result: Uint8Array = new Uint8Array();
for await (const chunk of stream) {
const encoded = deflate_encode_raw(chunk);
result = concat(result, encoded);
}
return result;
};
const encryptBuffer = async (
key: Uint8Array,
buffer: Deno.Reader
): Promise<Uint8Array> => {
const stream = Deno.iter(buffer, { bufSize: 16 });
let result: Uint8Array = new Uint8Array();
for await (const chunk of stream) {
const padded = withPadding(chunk);
const encrypted = encrypt(padded, key);
result = concat(result, encrypted);
}
return result;
};
// read file
const [filename] = Deno.args;
const key = randomBytes(16);
const raw = await Deno.open(filename);
const cipher = curry<Uint8Array, Deno.Reader, Uint8Array>(encryptBuffer)(key);
const encrypted = await pipe(cipher, encodeBuffer)(raw);
const [name, ext] = filename.split(".");
const data = await collectFromBuffer(encrypted);
const encryptedName = `${name}.end.${ext}`;
const keyName = `${name}.key`;
Deno.writeTextFile(encryptedName, encodeToString(data));
Deno.writeTextFile(keyName, encodeToString(key));
console.log(`Saving key at ${keyName}`);
console.log(`${filename} encrypted as ${encryptedName}!`);