🔐 写一个加密字符串的方法
欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。
方法 1:UTF-8 → Uint8Array → binary string → Base64(推荐)
✅ 推荐理由
与加密代码一致,标准化处理,支持所有Unicode字符。
加密函数
function utf8ToB64(str) {
const bytes = new TextEncoder().encode(str);
const binStr = String.fromCharCode(...bytes);
return btoa(binStr);
}
解密函数
function b64ToUtf8(b64) {
const binStr = atob(b64);
const bytes = Uint8Array.from(binStr, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
测试示例
utf8ToB64("Hello 世界!");
b64ToUtf8("SGVsbG8g5LiW55WMIQ==");
方法 2:encodeURIComponent + escape(兼容旧环境)
⚠️ 注意
兼容旧环境,但较 hacky(比较"取巧"/"不正规"),不推荐在现代项目中使用。
加密函数
function utf8ToB64(str) {
return btoa(unescape(encodeURIComponent(str)));
}
解密函数
function b64ToUtf8(b64) {
return decodeURIComponent(escape(atob(b64)));
}
核心API说明
TextEncoder / TextDecoder
- TextEncoder().encode(str):将字符串转换为 UTF-8 编码的 Uint8Array
- TextDecoder().decode(bytes):将 Uint8Array 解码为字符串
- 优势:标准API,支持所有Unicode字符
btoa / atob
- btoa(binaryString):将二进制字符串转换为 Base64
- atob(base64):将 Base64 解码为二进制字符串
- 限制:只能处理 Latin1 字符(0-255),不能直接处理 UTF-8
String.fromCharCode / charCodeAt
- String.fromCharCode(...bytes):将字节数组转换为字符串
- charCodeAt(0):获取字符的 Unicode 编码
完整示例代码
function utf8ToB64(str) {
const bytes = new TextEncoder().encode(str);
const binStr = String.fromCharCode(...bytes);
return btoa(binStr);
}
function b64ToUtf8(b64) {
const binStr = atob(b64);
const bytes = Uint8Array.from(binStr, c => c.charCodeAt(0));
return new TextDecoder().decode(bytes);
}
const encrypted = utf8ToB64("Hello 世界!");
console.log(encrypted);
const decrypted = b64ToUtf8(encrypted);
console.log(decrypted);
使用场景
✅ 适用场景
- URL参数传递:将复杂数据编码后放入URL
- localStorage存储:简单混淆敏感信息
- API传输:Base64编码二进制数据
- 前端临时加密:防止明文暴露(非安全加密)
⚠️ 安全提示
Base64 不是加密算法!
- Base64 只是编码方式,可以轻易解码
- 不要用于存储密码等敏感信息
- 真正的加密需要使用 AES、RSA 等算法
- 敏感数据应该在后端加密,前端只做传输
方法对比
方法 1(推荐)
- ✅ 标准API,现代浏览器全支持
- ✅ 代码清晰,易于理解
- ✅ 支持所有Unicode字符
- ❌ 需要较新的浏览器(IE不支持)
方法 2(兼容)
- ✅ 兼容旧浏览器(包括IE)
- ✅ 代码简洁
- ❌ 使用了已废弃的 escape/unescape
- ❌ 不够标准,较"取巧"