data_key.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const crypto = require("crypto");
  2. const sql = require('./sql.js');
  3. const decryptService = require('./decrypt.js');
  4. function getDataKey(password) {
  5. if (!password) {
  6. return null;
  7. }
  8. try {
  9. const passwordDerivedKey = getPasswordDerivedKey(password);
  10. const encryptedDataKey = getOption('encryptedDataKey');
  11. const decryptedDataKey = decryptService.decrypt(passwordDerivedKey, encryptedDataKey, 16);
  12. return decryptedDataKey;
  13. }
  14. catch (e) {
  15. throw new Error(`Cannot read data key, the entered password might be wrong. The underlying error: '${e.message}', stack:\n${e.stack}`);
  16. }
  17. }
  18. function getPasswordDerivedKey(password) {
  19. const salt = getOption('passwordDerivedKeySalt');
  20. return getScryptHash(password, salt);
  21. }
  22. function getScryptHash(password, salt) {
  23. const hashed = crypto.scryptSync(password, salt, 32,
  24. {N: 16384, r:8, p:1});
  25. return hashed;
  26. }
  27. function getOption(name) {
  28. return sql.getValue("SELECT value FROM options WHERE name = ?", [name]);
  29. }
  30. module.exports = {
  31. getDataKey
  32. };