trilium/services/data_encryption.js

92 lines
2.1 KiB
JavaScript
Raw Normal View History

"use strict";
2017-11-16 07:23:19 +08:00
const crypto = require('crypto');
2017-11-11 11:55:19 +08:00
function arraysIdentical(a, b) {
let i = a.length;
if (i !== b.length) return false;
while (i--) {
if (a[i] !== b[i]) return false;
}
return true;
}
function shaArray(content) {
// we use this as simple checksum and don't rely on its security so SHA-1 is good enough
return crypto.createHash('sha1').update(content).digest();
}
function pad(data) {
let padded = Array.from(data);
if (data.length >= 16) {
padded = padded.slice(0, 16);
2017-11-16 07:23:19 +08:00
}
else {
padded = padded.concat(Array(16 - padded.length).fill(0));
}
return Buffer.from(padded);
}
function encrypt(key, iv, plainText) {
2017-11-16 13:22:00 +08:00
if (!key) {
throw new Error("No data key!");
}
const plainTextBuffer = Buffer.from(plainText);
2017-11-16 13:22:00 +08:00
const cipher = crypto.createCipheriv('aes-128-cbc', pad(key), pad(iv));
const digest = shaArray(plainTextBuffer).slice(0, 4);
const digestWithPayload = Buffer.concat([digest, plainTextBuffer]);
const encryptedData = Buffer.concat([cipher.update(digestWithPayload), cipher.final()]);
return encryptedData.toString('base64');
}
function decrypt(key, iv, cipherText) {
2017-11-16 13:22:00 +08:00
if (!key) {
return "[protected]";
}
2017-11-16 13:22:00 +08:00
const decipher = crypto.createDecipheriv('aes-128-cbc', pad(key), pad(iv));
const cipherTextBuffer = Buffer.from(cipherText, 'base64');
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;
}
function decryptString(dataKey, iv, cipherText) {
const buffer = decrypt(dataKey, iv, cipherText);
return buffer.toString('utf-8');
}
function noteTitleIv(iv) {
return "0" + iv;
}
function noteTextIv(iv) {
return "1" + iv;
}
2017-11-11 11:55:19 +08:00
module.exports = {
encrypt,
decrypt,
decryptString,
noteTitleIv,
noteTextIv
2017-11-11 11:55:19 +08:00
};