AES (高级加密标准)
原理详解
AES是一种对称加密算法,使用相同的密钥进行加密和解密。它采用替代-置换网络(SPN)结构,主要步骤包括:
密钥扩展:从初始密钥派生多轮密钥
初始轮:AddRoundKey(轮密钥加)
主轮(重复9-13次):
SubBytes(字节替换)
ShiftRows(行移位)
MixColumns(列混淆)
AddRoundKey
最终轮(省略MixColumns)
AES有三种密钥长度:128位、192位和256位,分别对应10、12和14轮加密。
应用场景
HTTPS传输中的数据加密
数据库敏感字段加密
文件加密存储
实战代码(Node.js)
const crypto = require('crypto');// AES-256-CBC加密
function encrypt(text, key, iv) {const cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);let encrypted = cipher.update(text);encrypted = Buffer.concat([encrypted, cipher.final()]);return encrypted.toString('hex');
}// AES-256-CBC解密
function decrypt(encryptedText, key, iv) {const encryptedBuffer = Buffer.from(encryptedText, 'hex');const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv);let decrypted = decipher.update(encryptedBuffer);decrypted = Buffer.concat([decrypted, decipher.final()]);return decrypted.toString();
}// 使用示例
const key = crypto.randomBytes(32); // 256位密钥
const iv = crypto.randomBytes(16); // 初始向量
const message = 'Secret Message';const encrypted = encrypt(message, key, iv);
console.log('Encrypted:', encrypted);const decrypted = decrypt(encrypted, key, iv);
console.log('Decrypted:', decrypted);