El extremo frontal y el extremo del nodo implementan métodos de cifrado y descifrado simétricos, respectivamente.
Interfaz:
Primero descargue el complemento crypto-js.js y luego importe el archivo index.html
<script src="./utils/crypto-js.js"></script>
Luego escribe el método en el archivo js:
var global_key = CryptoJS.enc.Utf8.parse('123456d899876b43211d1234')
var global_IV = CryptoJS.enc.Utf8.parse('1234b45f04e31234')
function decrypt(data, key, iv) {
let dataHexStr = CryptoJS.enc.Hex.parse(data);
let dataBase64 = CryptoJS.enc.Base64.stringify(dataHexStr);
let decrypt = CryptoJS.AES.decrypt(dataBase64, key, {
iv: iv, mode: CryptoJS.mode.CBC});
let decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
//encrypt
function encrypt(data, key, iv) {
let encrypted = CryptoJS.AES.encrypt(data, key, {
iv: iv, mode: CryptoJS.mode.CBC});
return encrypted.ciphertext.toString().toUpperCase();;
}
let data = {
a:1,
b:2
}
let str = encrypt(JSON.stringify(data), global_key, global_IV);
let word = JSON.parse(decrypt(localStorage.ringOffObj, global_key, global_IV));
console.log(str)
console.log(word)
- global_key es la clave secreta
- global_IV es el vector
- descifrar método de descifrado
- encryptEncryption method
- El ejemplo utiliza datos de tipo de objeto de cifrado y descifrado. Si solo es una cadena o un número, no es necesario utilizar los métodos JSON.stringify y JSON.parse para la conversión de tipo.
lado del nodo
let crypto = require('crypto')
// data:需要加解密的内容,
// key: 密钥
// 初始化向量(iv)
function aesEncrypt(data, key, iv) {
// 给定的算法,密钥和初始化向量(iv)创建并返回Cipher对象
const cipher = crypto.createCipheriv('aes-192-cbc', key, iv)
// Key length is dependent on the algorithm. In this case for aes192, it is 24 bytes (192 bits).
// 指定要摘要的原始内容,可以在摘要被输出之前使用多次update方法来添加摘要内容
// 数据的编码 utf8 返回值的编码 hex
var crypted = cipher.update(data, 'utf8', 'hex')
crypted += cipher.final('hex')
return crypted
}
function aesDecrypt(data, key, iv) {
// 给定的算法,密钥和初始化向量(iv)创建并返回Cipher对象
const decipher = crypto.createDecipheriv('aes-192-cbc', key, iv)
//数据的编码 hex 返回值的编码 utf8
var decrypted = decipher.update(data, 'hex', 'utf8')
decrypted += decipher.final('utf8')
return decrypted
}
const IV = '1234b45f04e31234' // 初始化向量(iv)
let data = {
a:1,
b:2
} // 需要加解密的内容,
let key = '123456d899876b43211d1234' // 24 位秘钥密钥
let encryptData = aesEncrypt(data, key, IV)
let decryptData = aesDecrypt(encryptData, key, IV)
console.log(encryptData)
console.log(decryptData)