使用js进行自定义字符表编码与解码
const BASE64_CHARS = "ABCabcdefghijklmnopqrstuvwxyzDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; /** * 编码base64自定义字符表 * @param {Object} str */ encode(str) { /* let code = CryptoJS.AES.encrypt(string, secretKey).toString(); code = btoa(code) return code */ let characters = BASE64_CHARS; let result = ""; let binaryStr = ""; for (let i = 0; i < str.length; i++) { let code = str.charCodeAt(i); binaryStr += code.toString(2).padStart(8, "0"); while (binaryStr.length >= 6) { let index = parseInt(binaryStr.slice(0, 6), 2); binaryStr = binaryStr.slice(6); result += characters[index]; } } if (binaryStr.length > 0) { let index = parseInt(binaryStr.padEnd(6, "0"), 2); result += characters[index]; } return result; }, /** * 解码base64自定义字符表 * @param {Object} str */ decode(str) { /* string = atob(string); var bytes = CryptoJS.AES.decrypt(string, secretKey); return bytes.toString(CryptoJS.enc.Utf8); */ let characters = BASE64_CHARS; let binaryStr = ""; for (let i = 0; i < str.length; i++) { let index = characters.indexOf(str.charAt(i)); if (index >= 0) { binaryStr += index.toString(2).padStart(6, "0"); } } let result = ""; for (let i = 0; i < binaryStr.length; i += 8) { let code = parseInt(binaryStr.slice(i, i + 8), 2); result += String.fromCharCode(code); } return result; }
转载请注明:七彩悠悠博客 | 心悠悠 情悠悠 » js编码与解码base64自定义字符