概述:注册或者登录功能进行密码传输时,为了数据的安全性,前端往后端传输密码等敏感数据时需要对数据进行加密,后端再对密码进行解密。然后再用指定方法进行加密后存储到数据库。这里使用crypto对前后端密码传输时进行加解密操作。
安装
npm install crypto --save
注意事项:
- 加密解密时,使用的 key 和 iv 必须同一个,我这里希望每次加密时 key 和 iv 不是固定的,所以直接拼接到密码中了,解密时直接从密码中取,也可采取其他方法,保证加密解密时使用的一样即可
- key 的长度和 algorithm 有对应关系,key 的长度不对会报错 Invalid key length, 如果选 aes-256-gcm 则 key 为 randomBytes(256/8=32) ,以此类推
- algorithm 选用 aes-xxx-gcm 时,需要使用 authTag ,否则解密时报错Unsupported state or unable to authenticate data
- algorithm 取的值不同,处理方式略有不同 (此处适用 algorithm 为 aes-xxx-gcm 时的处理方式)
- 拼接逻辑可随意改变,不要容易被猜到加密和拼接规则即可
代码示例
import {
createCipheriv,
createDecipheriv,
randomBytes,
} from 'crypto';
const algorithm = 'aes-256-gcm';
const hexEncoding = 'hex';
const utf8Encoding = 'utf8';
/**
* @description: 密码加密 (可以解密)
* @param {string} pwd 加密前的密码
* @return {string} 加密后的密码
*/
export function cEncrypt(pwd: string): string {
const key = randomBytes(32);
const iv = randomBytes(16);
const cipher = createCipheriv(algorithm, key, iv);
let encrypted = `${cipher.update(
pwd,
utf8Encoding,
hexEncoding,
)}${cipher.final(hexEncoding)}`;
// algorithm 为 aes-xxx-gcm 时需要使用
const authTag = cipher.getAuthTag().toString(hexEncoding);
const ivStr = iv.toString(hexEncoding);
const keyStr = key.toString(hexEncoding);
encrypted = [encrypted, keyStr, ivStr, authTag].join('|');
return encrypted;
}
/**
* @description: 密码解密
* @param {string} encryptedPwd 经过cEncrypt方法加密的密码
* @return {*} 明文密码
*/
export function cDecrypt(encryptedPwd: string): string {
const [encrypted, keyStr, ivStr, authTag] = encryptedPwd.split('|');
const key = Buffer.from(keyStr, hexEncoding);
const iv = Buffer.from(ivStr, hexEncoding);
const decipher = createDecipheriv(algorithm, key, iv);
decipher.setAuthTag(Buffer.from(authTag, hexEncoding));
let decrypted = `${decipher.update(
encrypted,
hexEncoding,
utf8Encoding,
)}${decipher.final(utf8Encoding)}`;
return decrypted;
}
附上 algorithm 可用的取值(强调:取值不一致可能处理逻辑不一致)
💡 Tips:xdm,转载请附上链接;如有错误,请不吝指出,必将及时订正!!!
www.yuque.com/jslover/ldr…