纯 JavsScript 实现 base64 加解密
原创
52cxy
11-17 18:44
阅读数:403
分享一个JavsScript 实现 base64 加解密的方法,亲测有用。
const BASE64_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; //base64 加密 function encodeBase64(input) { let output = ''; let i = 0; const inputBytes = new TextEncoder().encode(input); // 将输入字符串转换为字节数组 while (i < inputBytes.length) { const byte1 = inputBytes[i++] || 0; const byte2 = inputBytes[i++] || 0; const byte3 = inputBytes[i++] || 0; const enc1 = byte1 >> 2; const enc2 = ((byte1 & 3) << 4) | (byte2 >> 4); const enc3 = ((byte2 & 15) << 2) | (byte3 >> 6); const enc4 = byte3 & 63; if (isNaN(byte2)) { output += BASE64_CHARS.charAt(enc1) + BASE64_CHARS.charAt(enc2) + '=='; } else if (isNaN(byte3)) { output += BASE64_CHARS.charAt(enc1) + BASE64_CHARS.charAt(enc2) + BASE64_CHARS.charAt(enc3) + '='; } else { output += BASE64_CHARS.charAt(enc1) + BASE64_CHARS.charAt(enc2) + BASE64_CHARS.charAt(enc3) + BASE64_CHARS.charAt(enc4); } } return output; } //base64 解密 function decodeBase64(input) { let output = ''; let i = 0; const sanitizedInput = input.replace(/[^A-Za-z0-9+/=]/g, ''); // 清理无效字符 const inputBytes = []; while (i < sanitizedInput.length) { const enc1 = BASE64_CHARS.indexOf(sanitizedInput.charAt(i++)); const enc2 = BASE64_CHARS.indexOf(sanitizedInput.charAt(i++)); const enc3 = BASE64_CHARS.indexOf(sanitizedInput.charAt(i++)); const enc4 = BASE64_CHARS.indexOf(sanitizedInput.charAt(i++)); const byte1 = (enc1 << 2) | (enc2 >> 4); const byte2 = ((enc2 & 15) << 4) | (enc3 >> 2); const byte3 = ((enc3 & 3) << 6) | enc4; inputBytes.push(byte1); if (enc3 !== 64) inputBytes.push(byte2); if (enc4 !== 64) inputBytes.push(byte3); } output = new TextDecoder().decode(Uint8Array.from(inputBytes)); // 将字节数组转换回字符串 return output; }
共0条评论