TypeScript解码base64报错

问题描述:

        前端: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
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值