🔐 写一个加密字符串的方法

📅 发布于 2026年1月 | 👤 作者:博主 | 🏷️ 标签:字符串加密, Base64, UTF-8, JavaScript, Web开发, 前端, 面试

欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。

方法 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); // binary to ASCII
}

解密函数

function b64ToUtf8(b64) {
  const binStr = atob(b64);
  const bytes = Uint8Array.from(binStr, c => c.charCodeAt(0));
  return new TextDecoder().decode(bytes);
}

测试示例

// 测试
utf8ToB64("Hello 世界!"); // "SGVsbG8g5LiW55WMIQ=="
b64ToUtf8("SGVsbG8g5LiW55WMIQ=="); // "Hello 世界!"

方法 2:encodeURIComponent + escape(兼容旧环境)

⚠️ 注意

兼容旧环境,但较 hacky(比较"取巧"/"不正规"),不推荐在现代项目中使用。

加密函数

function utf8ToB64(str) {
  return btoa(unescape(encodeURIComponent(str)));
}

解密函数

function b64ToUtf8(b64) {
  return decodeURIComponent(escape(atob(b64)));
}

核心API说明

TextEncoder / TextDecoder

btoa / atob

String.fromCharCode / charCodeAt

完整示例代码

// 方法 1:UTF-8 → Uint8Array → binary string → Base64(推荐)
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); // "SGVsbG8g5LiW55WMIQ=="

const decrypted = b64ToUtf8(encrypted);
console.log(decrypted); // "Hello 世界!"

使用场景

✅ 适用场景

⚠️ 安全提示

Base64 不是加密算法!

方法对比

方法 1(推荐)

方法 2(兼容)

← 返回首页