前端怎么使用AES 实现对登陆密码的加密和解密
import crypto from ‘crypto’
// @version 1.0 aes-128-gcm 加密
// @params msg 为加密信息 key为32位的16进制key
// @return 返回base64编码
export function Encrypt(msg) {
let key = ‘adasdasdsad….’
try {
var pwd = Buffer.from(key, ‘hex’);
var iv = crypto.randomBytes(12);
var cipher = crypto.createCipheriv(‘aes-128-gcm’, pwd, iv);
var enc = cipher.update(msg, ‘utf8’, ‘base64’)
enc += cipher.final(‘base64’);
//cipher.getAuthTag() 方法返回一个 Buffer,它包含已从给定数据计算后的认证标签。 ****
//cipher.getAuthTag() 方法只能在使用 cipher.final() 之后调用 这里返回的是一个十六进制后的数组
var tags = cipher.getAuthTag();
enc = Buffer.from(enc, ‘base64’);
//由于和java对应的AES/GCM/PKCS5Padding模式对应 所以采用这个拼接
var totalLength = iv.length + enc.length + tags.length;
var bufferMsg = Buffer.concat([iv, enc, tags], totalLength);
return bufferMsg.toString(‘base64’);
} catch (e) {
return null;
}
}
// version 1.0 aes-128-gcm 解密
// return msg 返回字符串
export function Decrypt(serect) {
let key = ‘adasdasdsad….’
try {
var tmpSerect = Buffer.from(serect, ‘base64’);
var pwd = Buffer.from(key, ‘hex’);
//读取数组
var iv = tmpSerect.slice(0, 12);
var cipher = crypto.createDecipheriv(‘aes-128-gcm’, pwd, iv);
//这边的数据为 去除头的iv12位和尾部的tags的16位
var msg = cipher.update(tmpSerect.slice(12, tmpSerect.length – 16));
return msg.toString('utf8');
} catch (e) {
return null;
}
}
页面的使用
import {Encrypt,Decrypt } from ‘index.js’
var enc = Encrypt(testMsg);
console.log(“加密结果”, enc);
var dec = Decrypt(enc);
console.log(‘解密结果’, dec);
参考文献:https://blog.csdn.net/qq_26026975/article/details/114582797
原创文章,作者:wure,如若转载,请注明出处:https://blog.ytso.com/271780.html