是否可以使用唯一的验证来加密/解密 Sequelize 模型的字段?



对于GDPR,我正在尝试从Sequelize Users模型加密和解密用户的个人数据。我的用户名和电子邮件字段必须唯一。

我尝试使用afterValidate和beforeValidate钩子,但是在验证时,Sequelize无法识别字段是否唯一,因为它们已经被加密,并且加密总是不同的。

你怎么处理这个?

我认为你使用的是随机的initVector和Securitykey,这在不同的时间会有所不同。因此,您必须使用可以保存在配置文件中的const值。例:

initVectorString: 'xx567876567898765',
securitykeyString:
'Zzzz345678909876545678984567890',

在配置文件中保存后,您可以拥有加密和解密功能,如下所示

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const initVector = Buffer.from(initVectorString, 'hex');
const Securitykey = Buffer.from(securitykeyString, 'hex');
function encryptData(data) {
try {
const cipher = crypto.createCipheriv(algorithm, Securitykey, initVector);
let encryptedData = cipher.update(data, 'utf-8', 'hex');
encryptedData += cipher.final('hex');
return encryptedData;
} catch (error) {}
}

function decryptData(data) {
try {
const decipher = crypto.createDecipheriv(
algorithm,
Securitykey,
initVector
);
let decryptedData = decipher.update(data, 'hex', 'utf-8');
decryptedData += decipher.final('utf8');
return decryptedData;
} catch (error) {}
}

最新更新