站长资讯网
最全最丰富的资讯网站

聊聊Node如何实现前后端数据传输加密解密

Node如何实现数据传输加密解密?下面本篇文章给大家介绍一下Node.js实现前后端数据传输加密解密的方法,希望对大家有所帮助!

聊聊Node如何实现前后端数据传输加密解密

如何快速入门VUE3.0:进入学习

在前后端通信过程中,一些敏感信息,特别是用户的账号密码,需要加密进行传输,如何选择加密方式也是一门学问,这里倒也不过多偏题了。 通常来说B/S架构中用的比较多的传输数据加密是RSA加密,核心思想就是公钥加密,私钥解密。 公钥,可以理解为可以公开的钥匙,服务器将公钥发给客户端,客户端用公钥对数据进行加密传输,服务器收到客户端传来的密文,再用自己的配对的私钥进行解密,即可获得原始的数据。

大致流程如下图所示:

聊聊Node如何实现前后端数据传输加密解密

示例

1、生成公私钥对

Nodejs中有一个核心模块——crypto提供各种加密、解密相关API。以下示例是基于Node@12.15.0版本进行编写。

const crypto = require('crypto');  /**  * 生成RSA公私钥对  * @return {*} publicKey: 公钥;privateKey: 私钥  */ function genRSAKeyPaire() {   const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {     modulusLength: 4096,     publicKeyEncoding: {       type: 'pkcs1',       format: 'pem',     },     privateKeyEncoding: {       type: 'pkcs1',       format: 'pem',     },   });   return { publicKey, privateKey }; }  // 打印生成的公私钥对 console.log(genRSAKeyPaire());

输出示例如下:

(示例公私钥已被删除了一部分,请勿用于实验)

{   publicKey: '-----BEGIN RSA PUBLIC KEY-----n' +     'MIICCgKCAgEAsitohTu9Jf2h+NPV4tNfFhPrlbStzXNM8wSEcskwtpwi6aZfgQC7n' +     '/A7M1hN8Zk8WgiZjy05AHinWPvXo70OWj8TminIAjB2wh0nDqm+IQqN7r20uzeJmn' +     'GBf1KusGemChEiFwiad1h/OB9z9LC8zMYR/G+XAbFfcv8MxAMI9mgmS8t5+xeYm6n' +     'EMiCQkQjfqpErhW3oESj8hrdJdOZbiK3l0TgYLyjZRQu6pHzFkmd9We3BY1qcXo1n' +     '2BtNKvqoH9QDJItsb3S9v2mOGl1rbItKlDrqYCdGY4iyXVIfagNWHraVzHqH/tern' +     'X+hOmLOwu+Npkz+oEDmnUq1UGY181PBGiNwHVodXx+DF5ckj/bGIxFG2nSiNe3dOn' +     'WLxV3+W8Af0006Oe+fRo1D7xt5SK5AipCpylKKYdyuP3MJ5dpPu7GMIcwj20Ndnun' +     'cDJJ2HH9kZAKz6/r62S7ALluFSecuZr0Dqc6SrJs43zBTpS/hSI33r01ste6Zel8n' +     'uRZKW/4FhUg8gW1KCM+Mp1MaZufOurCDc1Iec0SI71Tteg52BTpfb8cQ9Z1h0xWRn' +     'FdbmLMLuJkIi5oG2+FLAqlGknik0AxXpnlivSOW5Q+eLOh0DjQxxU2sCAwEAAQ==n' +     '-----END RSA PUBLIC KEY-----n',   privateKey: '-----BEGIN RSA PRIVATE KEY-----n' +     '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' +     '-----END RSA PRIVATE KEY-----n' }

2、公钥加密

在有了公私钥对的基础上,使用公钥进行加密,示例代码如下:

const crypto = require('crypto');  /**  * 生成公私钥对  * @return {*} publicKey: 公钥;privateKey: 私钥  */ function genRSAKeyPaire() {   const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {     modulusLength: 4096,     publicKeyEncoding: {       type: 'pkcs1',       format: 'pem',     },     privateKeyEncoding: {       type: 'pkcs1',       format: 'pem',     },   });    return { publicKey, privateKey }; }  const { publicKey } = genRSAKeyPaire();  /**    * 使用公钥进行加密    * @param {String} data     * @param {String} publicKey     * @return {String} 加密后的密文    */ function publicKeyEncrypt(data, publicKey) {   return crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64') }  const entry = {   name: 'zhangsan',   password: '123456' };  // 将数据转为字符串格式,并进行公钥加密后打印 console.log(publicKeyEncrypt(JSON.stringify(entry), publicKey));

输出内容为如下格式:

(数据已做删改)

Ri0p8QFmnYe8Xo36DextK242o9pcdL0QFDo6gUxhzjwQD30UFlqJL57na445BebSp1VT1z94emJgrME7xTDzV1tshtmVNtarqCUCzZMF4uYAtZCQLJhCX3708g7lOFksiUvi6MlXCVVOIu2VyFsIS/6DeEWYNirPK6zEBw1e2V2jWoL+63+iGNyhtKFJI1ECGyMmXUWCMicUmgE/JiHJD7YXPKB9+WaB7Wglj5udBdd4fALUp7qIo8TWJZJkLUg5yMbe7kemNWk050Xi1KiEt3s8IAqoRB1qGghTmE/TW+M/jIblSSy3Urle1AYsOFUzh9wV/H+uD+UNdaCvlvfmdV8hTIjjLNy9r/GbuaI5N0TkaX/dk47iUuorZabPoINEnM8lYxcKPvgVJufMfSX5wLxgx60nt4cpz3T2IutO97sdocVbhsiSlpFLpIk88xd4=

3、私钥解密

有了公钥加密后的密文,再用私钥进行解密,代码如下:

const crypto = require('crypto');  /**  * 生成公私钥对  * @return {*} publicKey: 公钥;privateKey: 私钥  */ function genRSAKeyPaire() {   const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {     modulusLength: 4096,     publicKeyEncoding: {       type: 'pkcs1',       format: 'pem',     },     privateKeyEncoding: {       type: 'pkcs1',       format: 'pem',     },   });    return { publicKey, privateKey }; }  const { publicKey, privateKey } = genRSAKeyPaire();  /**    * 使用公钥进行加密    * @param {String} data     * @param {String} publicKey     * @return {String} 加密后的密文    */ function publicKeyEncrypt(data, publicKey) {   return crypto.publicEncrypt(publicKey, Buffer.from(data)).toString('base64') }  const entry = {   name: 'zhangsan',   password: '123456' };  const encryptedData = publicKeyEncrypt(JSON.stringify(entry), publicKey);  /**  * 使用私钥进行解密  * @param {String} encryptedData   * @param {String} privateKey   * @return {String} 解密后的明文  */ function privateKeyDecrypt(encryptedData, privateKey) {   return crypto.privateDecrypt(privateKey, Buffer.from(encryptedData, 'base64')).toString(); }  const originData = privateKeyDecrypt(encryptedData, privateKey);  // 打印用私钥解密后的数据 console.log(originData);

输出结果:

{"name":"zhangsan","password":"123456"}

和我们上面定义的entry数据内容一致,说明解密成功,但是解密后是一个字符串,如果原始数据是一个对象的话,别忘记了将其反序列化为对象。

总结

在日常开发中,涉及到前后端通信,特别是重要的信息,为了防止被第三方获取从而加以利用,一般都会做一下通信传输加密,最基本的就是使用https协议,但是光有https协议还不够(容易被中间人劫持攻击)。 因此要对数据在应用层进行加密以防止数据被他人劫持利用,使用非对称加密可以保证发送的密文只有拥有私钥的服务器才能解开,从而避免密文被其余无关人员解密并加以利用。 互联网领域没有绝对的安全,只有不断提高自己的安全意识,增强自己的安全技能,才是长久之计。

本文完。

赞(0)
分享到: 更多 (0)
网站地图   沪ICP备18035694号-2    沪公网安备31011702889846号