trilium/dump-db/inc/data_key.js

44 lines
1.1 KiB
JavaScript
Raw Normal View History

2022-02-13 05:20:15 +08:00
const crypto = require("crypto");
const sql = require("./sql.js");
const decryptService = require("./decrypt.js");
2022-02-11 06:37:25 +08:00
function getDataKey(password) {
2022-02-13 05:20:15 +08:00
if (!password) {
return null;
}
2022-02-11 06:37:25 +08:00
2022-02-13 05:20:15 +08:00
try {
const passwordDerivedKey = getPasswordDerivedKey(password);
2022-02-11 06:37:25 +08:00
2022-02-13 05:20:15 +08:00
const encryptedDataKey = getOption('encryptedDataKey');
2022-02-11 06:37:25 +08:00
2022-02-13 05:20:15 +08:00
const decryptedDataKey = decryptService.decrypt(passwordDerivedKey, encryptedDataKey, 16);
return decryptedDataKey;
}
catch (e) {
throw new Error(`Cannot read data key, the entered password might be wrong. The underlying error: '${e.message}', stack:\n${e.stack}`);
}
2022-02-11 06:37:25 +08:00
}
function getPasswordDerivedKey(password) {
const salt = getOption('passwordDerivedKeySalt');
return getScryptHash(password, salt);
}
function getScryptHash(password, salt) {
const hashed = crypto.scryptSync(password, salt, 32,
{N: 16384, r:8, p:1});
return hashed;
}
function getOption(name) {
2022-02-13 05:20:15 +08:00
return sql.getValue("SELECT value FROM options WHERE name = ?", [name]);
2022-02-11 06:37:25 +08:00
}
module.exports = {
getDataKey
};