如何使用 crypto 模块(服务器端)和 crypto-js(客户端,react-native)正确加密/解密 node.js 之间的数据?
注意:我在 react-native 项目中使用 cryptojs,因此我不能在客户端使用 crypto。替换加密服务器端不是我的选择。
服务器端代码:
var Crypto = require("crypto");
var Cipher = {
pass: "0123456789abcdef0123456789abcdef",
iv: "0123456789abcdef",
encript: function (msg) {
try {
var cipher = Crypto.createCipheriv("aes-256-cbc", this.pass, this.iv);
var hash = cipher.update(msg, 'utf8', "hex");
var hex = hash + cipher.final("hex");
return hex;
} catch (err) {
console.error(err);
return "";
}
},
decript: function (hex){
try {
var decipher = Crypto.createDecipheriv("aes-256-cbc", this.pass, this.iv);
var dec = decipher.update(hex, "hex", 'utf8');
return dec + decipher.final('utf8');
} catch (err) {
console.error(err);
return "";
}
}
}
Cipher.encript("i have an apple"); // 577267026f88f82ea286baf6bf089acb
Cipher.decript("577267026f88f82ea286baf6bf089acb"); // i have an apple
客户端代码
var CryptoJS = require("crypto-js");
var Cipher = {
pass: CryptoJS.enc.Hex.parse("0123456789abcdef0123456789abcdef"),
iv: CryptoJS.enc.Hex.parse("0123456789abcdef"),
encript: function (msg) {
try {
var options = { mode: CryptoJS.mode.CBC, iv: this.iv};
var json = CryptoJS.AES.encrypt(msg, this.pass, options);
return json.ciphertext.toString(CryptoJS.enc.Hex);
} catch (err) {
console.error(err);
return "";
}
},
decript: function (hex){
try {
// ???????????????????????????????????
// ???????????????????????????????????
} catch (err) {
console.error(err);
return "";
}
}
}
Cipher.encript("i have an apple"); // 405552d9a77ea9e29442057d27cd7aee
Cipher.decript(?????); // I have no Idea