-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathencryption.ts
More file actions
226 lines (197 loc) · 5.49 KB
/
Copy pathencryption.ts
File metadata and controls
226 lines (197 loc) · 5.49 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
import crypto from "crypto"
import fs from "fs"
import { join } from "path"
import { Transform } from "stream"
import { pipeline } from "stream/promises"
import zlib from "zlib"
import env from "../environment"
const ALGO = "aes-256-ctr"
const SEPARATOR = "-"
const ITERATIONS = 10000
const STRETCH_LENGTH = 32
const SALT_LENGTH = 16
const IV_LENGTH = 16
export enum SecretOption {
API = "api",
ENCRYPTION = "encryption",
}
export function getSecret(secretOption: SecretOption): string {
let secret, secretName
switch (secretOption) {
case SecretOption.ENCRYPTION:
secret = env.ENCRYPTION_KEY
secretName = "ENCRYPTION_KEY"
break
case SecretOption.API:
default:
secret = env.API_ENCRYPTION_KEY
secretName = "API_ENCRYPTION_KEY"
break
}
if (!secret) {
throw new Error(`Secret "${secretName}" has not been set in environment.`)
}
return secret
}
function stretchString(secret: string, salt: Buffer) {
return crypto.pbkdf2Sync(
secret,
new Uint8Array(salt),
ITERATIONS,
STRETCH_LENGTH,
"sha512"
)
}
export function encrypt(
input: string,
secretOption: SecretOption = SecretOption.API
) {
const salt = crypto.randomBytes(SALT_LENGTH)
const stretched = stretchString(getSecret(secretOption), salt)
const cipher = crypto.createCipheriv(
ALGO,
new Uint8Array(stretched),
new Uint8Array(salt)
)
const base = cipher.update(input, "utf8")
const final = cipher.final()
const encrypted = Buffer.concat([
new Uint8Array(base),
new Uint8Array(final),
]).toString("hex")
return `${salt.toString("hex")}${SEPARATOR}${encrypted}`
}
export function decrypt(
input: string,
secretOption: SecretOption = SecretOption.API
) {
const [salt, encrypted] = input.split(SEPARATOR)
const saltBuffer = Buffer.from(salt, "hex")
const stretched = stretchString(getSecret(secretOption), saltBuffer)
const decipher = crypto.createDecipheriv(
ALGO,
new Uint8Array(stretched),
new Uint8Array(saltBuffer)
)
const base = decipher.update(encrypted, "hex")
const final = decipher.final()
return Buffer.concat([new Uint8Array(base), new Uint8Array(final)]).toString()
}
export function compare(
plain: string,
encrypted: string,
secretOption: SecretOption = SecretOption.API
) {
try {
const encoder = new TextEncoder()
const decryptedBuffer = encoder.encode(decrypt(encrypted, secretOption))
const plainBuffer = encoder.encode(plain)
if (decryptedBuffer.length !== plainBuffer.length) {
return false
}
return crypto.timingSafeEqual(decryptedBuffer, plainBuffer)
} catch {
return false
}
}
export async function encryptFile(
{ dir, filename }: { dir: string; filename: string },
secret: string
) {
const outputFileName = `${filename}.enc`
const filePath = join(dir, filename)
if (fs.lstatSync(filePath).isDirectory()) {
throw new Error("Unable to encrypt directory")
}
const inputFile = fs.createReadStream(filePath)
const outputFile = fs.createWriteStream(join(dir, outputFileName))
const salt = crypto.randomBytes(SALT_LENGTH)
const iv = crypto.randomBytes(IV_LENGTH)
const stretched = stretchString(secret, salt)
const cipher = crypto.createCipheriv(
ALGO,
new Uint8Array(stretched),
new Uint8Array(iv)
)
outputFile.write(salt)
outputFile.write(iv)
inputFile.pipe(zlib.createGzip()).pipe(cipher).pipe(outputFile)
return new Promise<{ filename: string; dir: string }>(r => {
outputFile.on("finish", () => {
r({
filename: outputFileName,
dir,
})
})
})
}
async function getSaltAndIV(path: string) {
const fileStream = fs.createReadStream(path)
const salt = await readBytes(fileStream, SALT_LENGTH)
const iv = await readBytes(fileStream, IV_LENGTH)
fileStream.close()
return { salt, iv }
}
export class DecryptionSizeLimitError extends Error {
constructor() {
super("Decrypted file exceeds the size limit.")
}
}
export async function decryptFile(
inputPath: string,
outputPath: string,
secret: string,
{ maxOutputBytes = Infinity }: { maxOutputBytes?: number } = {}
) {
if (fs.lstatSync(inputPath).isDirectory()) {
throw new Error("Unable to decrypt directory")
}
const { salt, iv } = await getSaltAndIV(inputPath)
const inputFile = fs.createReadStream(inputPath, {
start: SALT_LENGTH + IV_LENGTH,
})
const outputFile = fs.createWriteStream(outputPath)
const stretched = stretchString(secret, salt)
const decipher = crypto.createDecipheriv(
ALGO,
new Uint8Array(stretched),
new Uint8Array(iv)
)
let outputBytes = 0
await pipeline(
inputFile,
decipher,
zlib.createGunzip(),
new Transform({
transform(chunk: Buffer, _encoding, callback) {
outputBytes += chunk.length
if (outputBytes > maxOutputBytes) {
callback(new DecryptionSizeLimitError())
return
}
callback(null, chunk)
},
}),
outputFile
)
}
function readBytes(stream: fs.ReadStream, length: number) {
return new Promise<Buffer>((resolve, reject) => {
let bytesRead = 0
const data: Buffer[] = []
stream.on("readable", () => {
let chunk
while ((chunk = stream.read(length - bytesRead)) !== null) {
data.push(chunk)
bytesRead += chunk.length
}
resolve(Buffer.concat(data.map(buf => new Uint8Array(buf))))
})
stream.on("end", () => {
reject(new Error("Insufficient data in the stream."))
})
stream.on("error", error => {
reject(error)
})
})
}