问题描述:
前端:vue + typescript
后端:springboot
问题:前端调用登录接口,获取base64格式返回数据,解密失败。
1.typescript转码特殊base64编码格式时,需要先替换掉特殊字符
# - 替换为: +
# _ 替换为: /
str.replace(/-/g, '+', ).replace(/_/g, '/');
2.校验base64格式是否正确,如缺少字符则直接追加 = 号
while(s.length %4 !== 0){
s += '=';
}
3.使用atob转码
let v = atob(v);
v = utf8_decode(v);
console.log(v);
4.解决中文乱码问题
function utf8_decode(t: string): string {
let string = ''
let i = 0
let c = 0
let c1 = 0
let c2 = 0
while (i < t.length) {
c = t.charCodeAt(i)
if (c < 128) {
string += String.fromCharCode(c)
i++
} else if ((c > 191) && (c < 224)) {
c1 = t.charCodeAt(i + 1)
string += String.fromCharCode(((c & 31) << 6) | (c1 & 63))
i += 2
} else {
c1 = t.charCodeAt(i + 1)
c2 = t.charCodeAt(i + 2)
string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63))
i += 3
}
}
return string
}