演示如何通过代码实现对称加密和非对称加密。
对称加密
对称加密使用相同的密钥进行加密和解密。常见的对称加密算法包括AES、DES等。下面是一个使用Node.js进行对称加密的示例:
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const plaintext = 'Hello, world!';
const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(plaintext, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log('加密后的文本:', encrypted);
const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log('解密后的文本:', decrypted);
非对称加密
非对称加密使用一对密钥,公钥用于加密,私钥用于解密。常见的非对称加密算法包括RSA、ECC等。下面是一个使用Node.js进行非对称加密的示例:
const crypto = require('crypto');
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
const plaintext = 'Hello, world!';
const encrypted = crypto.publicEncrypt(publicKey, Buffer.from(plaintext, 'utf8'));
console.log('加密后的文本:', encrypted.toString('base64'));
const decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log('解密后的文本:', decrypted.toString('utf8'));