2017-11-10 12:25:23 +08:00
|
|
|
const options = require('./options');
|
|
|
|
const my_scrypt = require('./my_scrypt');
|
|
|
|
const utils = require('./utils');
|
2017-11-16 12:39:50 +08:00
|
|
|
const data_encryption = require('./data_encryption');
|
2017-11-10 12:25:23 +08:00
|
|
|
|
|
|
|
async function verifyPassword(password) {
|
|
|
|
const givenPasswordHash = utils.toBase64(await my_scrypt.getVerificationHash(password));
|
|
|
|
|
|
|
|
const dbPasswordHash = await options.getOption('password_verification_hash');
|
|
|
|
|
|
|
|
return givenPasswordHash === dbPasswordHash;
|
|
|
|
}
|
|
|
|
|
2017-11-29 06:24:08 +08:00
|
|
|
async function setDataKey(password, plainTextDataKey) {
|
2017-11-16 12:39:50 +08:00
|
|
|
const passwordDerivedKey = await my_scrypt.getPasswordDerivedKey(password);
|
|
|
|
|
|
|
|
const encryptedDataKeyIv = utils.randomSecureToken(16).slice(0, 16);
|
|
|
|
|
2017-11-29 06:24:08 +08:00
|
|
|
await options.setOption('encrypted_data_key_iv', encryptedDataKeyIv);
|
2017-11-16 12:39:50 +08:00
|
|
|
|
2017-11-23 09:57:06 +08:00
|
|
|
const buffer = Buffer.from(plainTextDataKey);
|
2017-11-16 12:39:50 +08:00
|
|
|
|
2017-11-19 01:53:17 +08:00
|
|
|
const newEncryptedDataKey = data_encryption.encrypt(passwordDerivedKey, encryptedDataKeyIv, buffer);
|
2017-11-16 12:39:50 +08:00
|
|
|
|
2017-11-29 06:24:08 +08:00
|
|
|
await options.setOption('encrypted_data_key', newEncryptedDataKey);
|
2017-11-16 12:39:50 +08:00
|
|
|
}
|
|
|
|
|
2017-11-19 01:53:17 +08:00
|
|
|
async function getDataKey(password) {
|
2017-11-16 12:39:50 +08:00
|
|
|
const passwordDerivedKey = await my_scrypt.getPasswordDerivedKey(password);
|
|
|
|
|
|
|
|
const encryptedDataKeyIv = await options.getOption('encrypted_data_key_iv');
|
|
|
|
const encryptedDataKey = await options.getOption('encrypted_data_key');
|
|
|
|
|
2017-11-19 01:53:17 +08:00
|
|
|
const decryptedDataKey = data_encryption.decrypt(passwordDerivedKey, encryptedDataKeyIv, encryptedDataKey);
|
2017-11-16 12:39:50 +08:00
|
|
|
|
|
|
|
return decryptedDataKey;
|
|
|
|
}
|
|
|
|
|
2017-11-10 12:25:23 +08:00
|
|
|
module.exports = {
|
|
|
|
verifyPassword,
|
2017-11-19 01:53:17 +08:00
|
|
|
getDataKey,
|
|
|
|
setDataKey
|
2017-11-10 12:25:23 +08:00
|
|
|
};
|