js实现cbc加密
使用JavaScript实现CBC加密
在JavaScript中实现CBC(Cipher Block Chaining)模式加密,通常需要结合加密算法如AES。以下是使用Web Crypto API实现AES-CBC加密的示例:
async function encryptCBC(plaintext, key, iv) {
const encoder = new TextEncoder();
const encodedData = encoder.encode(plaintext);
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
key,
{ name: 'AES-CBC' },
false,
['encrypt']
);
const encryptedData = await window.crypto.subtle.encrypt(
{
name: 'AES-CBC',
iv: iv,
},
cryptoKey,
encodedData
);
return new Uint8Array(encryptedData);
}
参数说明
- plaintext: 需要加密的文本数据。
- key: 加密密钥,需为16、24或32字节(对应AES-128、AES-192、AES-256)。
- iv: 初始化向量(IV),固定为16字节。
示例调用
const key = new Uint8Array(16); // 16字节密钥(AES-128)
const iv = new Uint8Array(16); // 16字节IV
const plaintext = "Hello, CBC!";
encryptCBC(plaintext, key, iv)
.then(encrypted => console.log("加密结果:", encrypted))
.catch(err => console.error("加密失败:", err));
解密实现
解密过程与加密类似,使用decrypt方法:
async function decryptCBC(ciphertext, key, iv) {
const cryptoKey = await window.crypto.subtle.importKey(
'raw',
key,
{ name: 'AES-CBC' },
false,
['decrypt']
);
const decryptedData = await window.crypto.subtle.decrypt(
{
name: 'AES-CBC',
iv: iv,
},
cryptoKey,
ciphertext
);
return new TextDecoder().decode(decryptedData);
}
注意事项
- IV安全性: IV需随机生成且每次加密不同,不可重复使用。
- 密钥管理: 密钥需安全存储,避免硬编码。
- 环境支持: Web Crypto API在现代浏览器中可用,Node.js需使用
crypto模块。
Node.js实现
在Node.js中可通过内置crypto模块实现:
const crypto = require('crypto');
function encryptCBC(plaintext, key, iv) {
const cipher = crypto.createCipheriv('aes-256-cbc', key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
以上方法提供了在浏览器和Node.js环境中实现AES-CBC加密的核心逻辑。







