BlowfishJS 是一款基于 Blowfish 加密算法实现的 JavaScript 库,主要用于在浏览器或 Node.js 环境中进行数据加密与解密,其轻量级、易集成的特性使其成为前端加密场景的常见选择,以下内容将详细介绍其核心用法,帮助开发者快速上手。
通过 CDN 引入:
<script src="https://cdn.jsdelivr.net/npm/blowfish-js@latest/dist/blowfish.min.js"></script>
使用 npm 安装:
npm install blowfish-js
引入模块:
const Blowfish = require('blowfish-js');
// 创建实例,指定密钥和模式 const bf = new Blowfish('my-secret-key', Blowfish.MODE.ECB); // 加密数据 const encrypted = bf.encrypt('Hello World'); console.log('加密结果:', encrypted.toHex()); // 输出十六进制格式 // 解密数据 const decrypted = bf.decrypt(encrypted); console.log('解密结果:', decrypted.toString()); // 输出原始字符串
const iv = Blowfish.Utils.utf8ToBytes('12345678'); // IV 长度需为 8 字节 const bf = new Blowfish('my-secret-key', Blowfish.MODE.CBC, iv); const encrypted = bf.encrypt('Sensitive Data'); const decrypted = bf.decrypt(encrypted);
支持多种输入/输出格式(UTF-8、Base64、Hex 等):
// 加密 UTF-8 字符串,输出 Base64 const encryptedBase64 = bf.encrypt('Message', Blowfish.TYPE.UTF8, Blowfish.TYPE.BASE64); // 解密 Base64 数据,还原为字符串 const decryptedText = bf.decrypt(encryptedBase64, Blowfish.TYPE.BASE64, Blowfish.TYPE.UTF8);
加密长文本时建议分块处理(每块 8 字节):
const longText = 'This is a very long message...'; const encryptedBlocks = []; for (let i = 0; i < longText.length; i += 8) { const block = longText.slice(i, i + 8); encryptedBlocks.push(bf.encrypt(block)); }
密钥安全性
模式选择
性能优化
浏览器端加密大文件可能引起主线程阻塞,建议使用 Web Worker。
兼容性
TextEncoder
等 Polyfill 使用。