Notes/dump-db/inc/decrypt.ts

89 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-01-09 18:07:02 +02:00
import crypto from "crypto";
2022-02-10 23:37:25 +01:00
2024-08-10 18:23:49 +02:00
function decryptString(dataKey: any, cipherText: any) {
2022-02-10 23:37:25 +01:00
const buffer = decrypt(dataKey, cipherText);
if (buffer === null) {
return null;
}
2025-01-09 18:07:02 +02:00
const str = buffer.toString("utf-8");
2022-02-10 23:37:25 +01:00
2025-01-09 18:07:02 +02:00
if (str === "false") {
2022-02-10 23:37:25 +01:00
throw new Error("Could not decrypt string.");
}
return str;
}
2025-01-15 10:16:04 +08:00
function decrypt(key: any, cipherText: any, ivLength = 16) {
2022-02-10 23:37:25 +01:00
if (cipherText === null) {
return null;
}
if (!key) {
return "[protected]";
}
try {
2025-01-09 18:07:02 +02:00
const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), "base64");
2022-02-10 23:37:25 +01:00
const iv = cipherTextBufferWithIv.slice(0, ivLength);
const cipherTextBuffer = cipherTextBufferWithIv.slice(ivLength);
2025-01-09 18:07:02 +02:00
const decipher = crypto.createDecipheriv("aes-128-cbc", pad(key), pad(iv));
2022-02-10 23:37:25 +01:00
const decryptedBytes = Buffer.concat([decipher.update(cipherTextBuffer), decipher.final()]);
const digest = decryptedBytes.slice(0, 4);
const payload = decryptedBytes.slice(4);
const computedDigest = shaArray(payload).slice(0, 4);
if (!arraysIdentical(digest, computedDigest)) {
return false;
}
return payload;
2025-01-09 18:07:02 +02:00
} catch (e: any) {
2022-02-10 23:37:25 +01:00
// recovery from https://github.com/zadam/trilium/issues/510
if (e.message?.includes("WRONG_FINAL_BLOCK_LENGTH") || e.message?.includes("wrong final block length")) {
2024-08-10 18:23:49 +02:00
console.log("Caught WRONG_FINAL_BLOCK_LENGTH, returning cipherText instead");
2022-02-10 23:37:25 +01:00
return cipherText;
2025-01-09 18:07:02 +02:00
} else {
2022-02-10 23:37:25 +01:00
throw e;
}
}
}
2024-08-10 18:23:49 +02:00
function pad(data: any) {
2022-02-12 22:20:15 +01:00
if (data.length > 16) {
data = data.slice(0, 16);
2025-01-09 18:07:02 +02:00
} else if (data.length < 16) {
2022-02-12 22:20:15 +01:00
const zeros = Array(16 - data.length).fill(0);
data = Buffer.concat([data, Buffer.from(zeros)]);
}
return Buffer.from(data);
}
2024-08-10 18:23:49 +02:00
function arraysIdentical(a: any, b: any) {
2022-02-10 23:37:25 +01:00
let i = a.length;
if (i !== b.length) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
}
2024-08-10 18:23:49 +02:00
function shaArray(content: any) {
2022-02-10 23:37:25 +01:00
// we use this as simple checksum and don't rely on its security so SHA-1 is good enough
2025-01-09 18:07:02 +02:00
return crypto.createHash("sha1").update(content).digest();
2022-02-10 23:37:25 +01:00
}
2024-08-10 18:23:49 +02:00
export default {
2022-02-10 23:37:25 +01:00
decrypt,
decryptString
};