@TOC
1 介绍
本文将使用 js-base64 进行js base64相关操作
2 安装
npm
代码语言:text复制npm install --save js-base64
cdn
代码语言:text复制<script src="https://cdn.jsdelivr.net/npm/js-base64@3.7.2/base64.min.js"></script>
3 base64加密/解密案例
加密、解密具体方法如下案例所示
代码语言:javascript复制let nick = "有勇气的牛排good"
// 显式扩展
Base64.extendString();
// 加密
console.log(nick.toBase64()) // 5pyJ5YuH5rCU55qE54mb5o6SZ29vZA==
console.log(nick.toBase64(true)) // 5pyJ5YuH5rCU55qE54mb5o6SZ29vZA
console.log(nick.toBase64URI()) // 5pyJ5YuH5rCU55qE54mb5o6SZ29vZA
console.log(nick.toBase64URL()) // 5pyJ5YuH5rCU55qE54mb5o6SZ29vZA
// 解密
console.log(nick.toBase64().fromBase64()) // 有勇气的牛排good
console.log(nick.toBase64(true).fromBase64()) // 有勇气的牛排good
console.log(nick.toBase64URI().fromBase64()) // 有勇气的牛排good
console.log(nick.toBase64URL().toUint8Array())
// Uint8Array(22) [230, 156, 137, 229, 139, 135, 230, 176, 148, 231, 154, 132, 231, 137, 155, 230, 142, 146, 103, 111, 111, 100, buffer: ArrayBuffer(22), byteLength: 22, byteOffset: 0, length: 22, Symbol(Symbol.toStringTag): 'Uint8Array']
4 decode与atob
Base64.decode()
:解码为 UTF-8字符串
Base64.atob()
:解码为字节
5 jwt解析操作实战
代码语言:javascript复制function jwt_parse(token) {
return Base64.atob(token.split(".")[1]);
}
let token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJcdTY3MDlcdTUyYzdcdTZjMTRcdTc2ODRcdTcyNWJcdTYzOTIiLCJpYXQiOjE2Njc0NTg5ODAsImV4cCI6MTY2ODA2Mzc4MCwiYXVkIjoid3d3LmNvdXJhZ2VzdGVhay5jb20iLCJkYXRhIjp7InVpZCI6MSwidXNlcm5hbWUiOiJjaGVhcmxlcyJ9fQ.4Xrf3Chpfu1qOnmDy7UQqJAt6dpvKBVxafvr7gdCwdk";
let userinfo = jwt_parse(token)
console.log(userinfo)
结果
代码语言:json复制{
"iss": "有勇气的牛排",
"iat": 1667458980,
"exp": 1668063780,
"aud": "www.couragesteak.com",
"data": {
"uid": 1,
"username": "charles"
}
}