在NodeJS中进行混合加密,可以按照以下步骤进行:
crypto
模块中的generateKeyPairSync
方法生成公钥和私钥。具体代码示例如下:const crypto = require('crypto');
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
console.log('公钥:', publicKey);
console.log('私钥:', privateKey);
const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const plaintext = 'Hello, World!';
const symmetricKey = crypto.randomBytes(32); // 生成32字节的随机密钥
const cipher = crypto.createCipheriv(algorithm, symmetricKey, crypto.randomBytes(16)); // 生成随机的初始化向量
let encryptedData = cipher.update(plaintext, 'utf8', 'hex');
encryptedData += cipher.final('hex');
console.log('加密后的数据:', encryptedData);
console.log('对称密钥:', symmetricKey.toString('hex'));
const crypto = require('crypto');
const publicKey = '-----BEGIN PUBLIC KEY-----\nMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAr4BaiyUId98JBDa6UB2d\nsLBQ8RmpNIdU/1D52A2/uQVweI8wIlA4+pFDvCnAqbrOGp7yfBLB4qnyEKhyXACX\nMY0dtdUf6SBv5qWmDriwcSljT3seTp6sn4MncaJtvnvhH7DWWQSt5CE9Mo4C5Kaf\n9FZNEjhUm8FVZP3p/cfkexiz4mPHDzSExDX2SihGBkmPvqtuxUjqI0gmhRusL3IZ\nfLoP9jsBW0CmYbFDWPr1s3eEeO8l/oy9ZGJIxPDL8WfJwH7yPSQImf8KtjvfUpXk\nEF87vDvpzjmyFRk92YaOYvK6TfMlymX80bymEkM6FdDo6m+kq3rt7B9D+aOZX/cj\n5yt7YdyFRL69J5z9aiR8pNscbIBO5eUArP48XHpgk6Dms8TV0+HucGm6fomV/TA4\nGEP95mCxkMHUZwS/N3pB/OWeELhJ8iKq+luHK/MWQs0Avh4jExrNckWjBQHGc7Xy\nQPV0/rPHEyNlHv8MkYtkKx1lM5Dd/EbKVsAXtRjNxZ0BKrW41Ahic4I7rX0DilXu\nFq1ZrhE0kfbZY/ocgVjmuJGkbOiCNbN07hh0EcsIrGekhjI4m1cGRHQHQiTJ6OFO\n0XZLrKUJY3uN8I/NpvwAsqIPbwyUcTzuoOrPsbMraU+MROA15F77x2ZGlyyMJDd7\nY5yMTRWHbBGKjy9jvXuUEU8CAwEAAQ==\n-----END PUBLIC KEY-----';
const symmetricKey = Buffer.from('8544c944a081f13e3c2a4d4f81b7c4b9e156ef314db5d6f3014e1a8d907e48c3', 'hex');
const encryptedSymmetricKey = crypto.publicEncrypt(publicKey, symmetricKey);
console.log('非对称加密后的对称密钥:', encryptedSymmetricKey.toString('hex'));
在以上步骤中,我们首先生成了一对公钥和私钥,然后使用生成的随机密钥对明文进行对称加密,接着使用公钥对生成的对称密钥进行非对称加密。
GAME-TECH
云+社区技术沙龙[第8期]
DBTalk
云+社区技术沙龙 [第31期]
云+未来峰会
DB TALK 技术分享会
DBTalk
云+社区开发者大会(北京站)
云+社区技术沙龙[第9期]
Elastic 中国开发者大会
云+社区技术沙龙[第6期]
领取专属 10元无门槛券
手把手带您无忧上云