Mr_老冷 发表于 2024-10-4 23:26:55

【JavaScript】纯js,base64字符串加密解密

加密:字符串加密成base64

function stringToBase64(str) {
    // 将字符串转换为UTF-8字节数组
    let utf8 = unescape(encodeURIComponent(str))
    // Base64字符集
    let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
    // 初始化输出字符串
    let out = ''
    // 遍历UTF-8字节数组
    for (let i = 0; i < utf8.length;) {
      let c1 = utf8.charCodeAt(i++) & 0xff
      if (i === utf8.length) {
            let enc1 = c1 >> 2
            let enc2 = (c1 & 0x3) << 4
            out += chars.charAt(enc1) + chars.charAt(enc2) + '=='
            break
      }
      let c2 = utf8.charCodeAt(i++)
      if (i === utf8.length) {
            let enc1 = c1 >> 2
            let enc2 = ((c1 & 0x3) << 4) | (c2 >> 4)
            let enc3 = (c2 & 0xf) << 2
            out += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + '='
            break
      }
      let c3 = utf8.charCodeAt(i++)
      let enc1 = c1 >> 2
      let enc2 = ((c1 & 0x3) << 4) | (c2 >> 4)
      let enc3 = ((c2 & 0xf) << 2) | (c3 >> 6)
      let enc4 = c3 & 0x3f
      out += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4)
    }
    return out
}
let ret = stringToBase64("老冷编程学院http://bbs.laoleng.vip")
logd(ret)
//结果6ICB5Ya357yW56iL5a2m6ZmiW3VybD1odHRwOi8vYmJzLmxhb2xlbmcudmlwXWh0dHA6Ly9iYnMubGFvbGVuZy52aXBbL3VybF0=


解密:base64转字符串
function base64ToString(base64) {
    let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
    let out = '', i = 0, len = base64.length, c1, c2, c3, c4
    while (i < len) {
      c1 = chars.indexOf(base64.charAt(i++)) << 2
      c2 = chars.indexOf(base64.charAt(i++))
      out += String.fromCharCode((c1 | (c2 >> 4)) & 0xFF)
      if (i >= len || base64.charAt(i) === '=') break
      c3 = chars.indexOf(base64.charAt(i++))
      out += String.fromCharCode(((c2 << 4) | (c3 >> 2)) & 0xFF)
      if (i >= len || base64.charAt(i) === '=') break
      c4 = chars.indexOf(base64.charAt(i++))
      out += String.fromCharCode(((c3 << 6) | c4) & 0xFF)
    }
    // 将UTF-8字节数组转换回字符串
    return decodeURIComponent(escape(out))
}
logd(base64ToString("6ICB5Ya357yW56iL5a2m6ZmiW3VybD1odHRwOi8vYmJzLmxhb2xlbmcudmlwXWh0dHA6Ly9iYnMubGFvbGVuZy52aXBbL3VybF0="))
//结果 老冷编程学院http://bbs.laoleng.vip

页: [1]
查看完整版本: 【JavaScript】纯js,base64字符串加密解密