aes-gcm模式前端加解密(html页面 js)——使用node-forge库
node-forge
之前讲过了AES-GCM模式在vue中如何加解密,使用的是node自带的crypto模块,但是会有个问题,纯html页面中无法使用node.js中的api。
这时候我们需要用到一个库:node-forge(js, vue中都可使用)
npm地址:node-forge - npm
github地址:https://github.com/digitalbazaar/forge
官方列举的可以加解密的模式:
使用
1:引入
js:
<script src ="https://unpkg.com/node-forge@1.0.0/dist/forge.min.js "></script>
vue:
安装:npm install node-forge 在需要用的地方引入:import forge from 'node-forge'
2:密钥
const keyStr = '16位/24位/32位的密钥'
// 如果跟后端搭配加解密需要和后端约定好密钥 密钥必须一致
3:加密
js
// 加密 function encrypt(someBytes) { var iv = forge.random.getBytesSync(12) // 生成随机iv 12字节 var cipher = forge.cipher.createCipher('AES-GCM', keyStr); // 生成AES-GCM模式的cipher对象 并传入密钥 cipher.start({ iv: iv }); cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(someBytes))); cipher.finish(); var encrypted = cipher.output; var tag = cipher.mode.tag; return btoa(iv+encrypted.data+tag.data) }
vue
export function encrypt(word) { var iv = forge.random.getBytesSync(12) // 生成随机iv 12字节 var cipher = forge.cipher.createCipher('AES-GCM', keyStr) // 生成AES-GCM模式的cipher对象 并传入密钥 cipher.start({ iv: iv }) cipher.update(forge.util.createBuffer(forge.util.encodeUtf8(word))) cipher.finish() var encrypted = cipher.output var tag = cipher.mode.tag return window.btoa(iv + encrypted.data + tag.data) }
4:解密
js
function decrypt(someBytes) { someBytes = atob(someBytes) const iv = someBytes.slice(0, 12) const tag = someBytes.slice(-16) const data = someBytes.slice(12, someBytes.length - 16) var decipher = forge.cipher.createDecipher('AES-GCM', keyStr) decipher.start({ iv: iv, tag: tag }); decipher.update(forge.util.createBuffer(data)) const pass = decipher.finish() if (pass) { return decipher.output.toString() } }
vue
export function decrypt(datamsg) { datamsg = window.atob(datamsg) const iv = datamsg.slice(0, 12) const tag = datamsg.slice(-16) const data = datamsg.slice(12, datamsg.length - 16) var decipher = forge.cipher.createDecipher('AES-GCM', keyStr) decipher.start({ iv: iv, tag: tag }) decipher.update(forge.util.createBuffer(data)) const pass = decipher.finish() if (pass) { return decipher.output.toString() } }
5:举个栗子
var str = '我是密码123.!' var en = encrypt(str) console.log(en) var de = decrypt(en) console.log(de)