下面是详解使用Nodejs内置加密模块实现对等加密与解密的完整攻略。
什么是对等加密?
对等加密,又称对称加密算法,是一种加密与解密使用相同密钥的加密方式。这种加密方式速度快,适用于数据较小的场合。在这种加密方式下,密钥的安全性极为重要,一旦被泄漏可能会导致加密数据不安全。
使用Nodejs内置加密模块实现对等加密
Nodejs中提供了crypto模块,其中包含了对等加密的API。下面是使用内置加密模块实现对等加密的步骤:
- 导入crypto模块
const crypto = require('crypto');
- 生成密钥
const secret = 'abcdefg';
- 创建加密算法
const algorithm = 'aes-256-cbc';
- 创建加密对象
const cipher = crypto.createCipher(algorithm, secret);
- 加密数据
const text = 'Hello World.';
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(`encrypted: ${encrypted}`);
解释一下这段代码,我们首先定义了明文文本text,然后通过cipher.update()方法进行部分加密,最后通过cipher.final()方法进行最终加密。输出的encrypted就是加密后的密文。
- 创建解密对象
const decipher = crypto.createDecipher(algorithm, secret);
- 解密数据
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(`decrypted: ${decrypted}`);
这段代码是对上面加密过程的逆向操作,我们先创建解密对象decipher,然后通过decipher.update()方法进行部分解密,最后通过decipher.final()方法进行最终解密。输出的decrypted就是解密后的明文。
示例
下面是两条使用Nodejs内置加密模块实现对等加密与解密的示例:
示例1:使用crypto模块加密和解密字符串
const crypto = require('crypto');
const secret = 'abcdefg';
const algorithm = 'aes-256-cbc';
const encrypt = (text) => {
const cipher = crypto.createCipher(algorithm, secret);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
const decrypt = (encrypted) => {
const decipher = crypto.createDecipher(algorithm, secret);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
const text = 'Hello World.';
const encrypted = encrypt(text);
const decrypted = decrypt(encrypted);
console.log(`text: ${text}`);
console.log(`encrypted: ${encrypted}`);
console.log(`decrypted: ${decrypted}`);
输出结果:
text: Hello World.
encrypted: 7d902cf0f7f194de46ca4b61b40728bc
decrypted: Hello World.
示例2:使用crypto模块加密和解密JSON对象
const crypto = require('crypto');
const secret = 'abcdefg';
const algorithm = 'aes-256-cbc';
const encrypt = (obj) => {
const cipher = crypto.createCipher(algorithm, secret);
let encrypted = cipher.update(JSON.stringify(obj), 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
}
const decrypt = (encrypted) => {
const decipher = crypto.createDecipher(algorithm, secret);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return JSON.parse(decrypted);
}
const obj = {
name: 'Alice',
age: 18
};
const encrypted = encrypt(obj);
const decrypted = decrypt(encrypted);
console.log(`obj: ${JSON.stringify(obj)}`);
console.log(`encrypted: ${encrypted}`);
console.log(`decrypted: ${JSON.stringify(decrypted)}`);
输出结果:
obj: {"name":"Alice","age":18}
encrypted: 62bb6ce54971f2b4e7375776af3ce878fd4c6fb4e02a230a4ce854d02b48f2c9
decrypted: {"name":"Alice","age":18}
综上所述,我们可以看到使用Nodejs内置加密模块实现对等加密和解密非常容易,只需要按照上述步骤即可。同时,我们还提供了两个示例,分别用于加密和解密字符串和JSON对象。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解使用Nodejs内置加密模块实现对等加密与解密 - Python技术站