use 16 bytes IV for newly encrypted data, closes #3017

This commit is contained in:
zadam 2022-07-28 22:42:02 +02:00
parent 80887fd3c1
commit 5a37547b37

View file

@ -30,14 +30,14 @@ function pad(data) {
return Buffer.from(data);
}
function encrypt(key, plainText, ivLength = 13) {
function encrypt(key, plainText) {
if (!key) {
throw new Error("No data key!");
}
const plainTextBuffer = Buffer.from(plainText);
const iv = crypto.randomBytes(ivLength);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-128-cbc', pad(key), pad(iv));
const digest = shaArray(plainTextBuffer).slice(0, 4);
@ -51,7 +51,7 @@ function encrypt(key, plainText, ivLength = 13) {
return encryptedDataWithIv.toString('base64');
}
function decrypt(key, cipherText, ivLength = 13) {
function decrypt(key, cipherText) {
if (cipherText === null) {
return null;
}
@ -62,6 +62,10 @@ function decrypt(key, cipherText, ivLength = 13) {
try {
const cipherTextBufferWithIv = Buffer.from(cipherText.toString(), 'base64');
// old encrypted data can have IV of length 13, see some details here: https://github.com/zadam/trilium/issues/3017
const ivLength = cipherTextBufferWithIv.length % 16 === 0 ? 16 : 13;
const iv = cipherTextBufferWithIv.slice(0, ivLength);
const cipherTextBuffer = cipherTextBufferWithIv.slice(ivLength);