加密存储在我的数据库中的数据



我目前使用nodejs作为我的后端,sequelize ORM和postgres作为我的db.

当我的用户注册时,我正在尝试使用内置的加密模块加密数据。

一切都在工作,但由于我正在生成一个自定义IV,加密的数据都采用相同的IV,因为它每次节点重启时都呈现。我如何给每个领域不同的静脉注射?

这是我第一次加密数据,有人能告诉我我所做的是正确的还是不?

let key ="12345678123456781234567812345678";
let iv = crypto.randomBytes(16);
router.post(
"/register",
(req, res) => {

let cipher1 = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let cipher2 = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let cipher3 = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let cipher4 = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let cipher5 = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let mobilenumber = cipher1.update(req.body.mobilenumber);
const encrypted_mobilenumber = Buffer.concat([mobilenumber, cipher1.final()]);
let firstname = cipher2.update(req.body.firstname);
const encrypted_firstname = Buffer.concat([firstname, cipher2.final()]);
let lastname = cipher3.update(req.body.lastname);
const encrypted_lastname = Buffer.concat([lastname, cipher3.final()]);
let dob = cipher4.update(req.body.dob);
const encrypted_dob = Buffer.concat([dob, cipher4.final()]);
const fullAddress= req.body.housenumber + ', ' + req.body.address1 + 
(req.body.address2===''?'': ', ' + req.body.address2 ) + 
', ' + req.body.city + ', ' + req.body.postcode + ', ' + req.body.country
let address = cipher5.update(fullAddress);
const encrypted_address = Buffer.concat([address, cipher5.final()]);

User.create({
email: req.body.email,
mobilenumber:iv.toString('hex') + ':' + encrypted_mobilenumber.toString('hex'),
passcode: req.body.passcode,
firstname:iv.toString('hex') + ':' + encrypted_firstname.toString('hex'),
lastname:iv.toString('hex') + ':' + encrypted_lastname.toString('hex'),
dob:iv.toString('hex') + ':' + encrypted_dob.toString('hex'),
address:iv.toString('hex') + ':' + encrypted_address.toString('hex')
}) 

我认为我们可以通过引入一个新函数来简化这段代码,encryptField(),它将使用提供的密钥加密给定的字段,并在返回之前将iv添加到它前面。

我还建议创建一个getFullAddress函数来将地址组件转换为完整地址。

所有这些都将显著减少代码长度和重复:

const key = "12345678123456781234567812345678";
function encryptField(data, key) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
return iv.toString('base64') + ':' + Buffer.concat([cipher.update(data),cipher.final()]).toString("base64");
}
function getFullAddress({housenumber, address1, address2, city, postcode, country}) {
return [housenumber, address1, ...(address2 ? [address2]: []), city, postcode, country].join(", ");
}
router.post(
"/register",
(req, res) => {
User.create({
email: encryptField(req.body.email, key),
mobilenumber: encryptField(req.body.mobilenumber, key),
passcode: req.body.passcode,
firstname: encryptField(req.body.firstname, key),
lastname: encryptField(req.body.lastname, key),
dob: encryptField(req.body.dob, key),
address: encryptField(getFullAddress(req.body), key)
})
}
) 

最新更新