我正在尝试创建一个nodejs服务来加密数据并发送到第三方服务器。
节点中的结果与php不同(php是对的)。
这是节点代码(PHP代码已注释):
var crypto = require('crypto');
var Buffer = require('buffer').Buffer;
function encodeBase64 = function(data){
//return base64_encode(data); //php code
return new Buffer(data).toString('base64');
}
function decodeBase64(data){
//data = base64_decode(data); //PHP code
return new Buffer(data, 'base64').toString("binary");
}
错误在这里,节点中的输出是不同的:
function encrypt_3DES(message, key){
//PHP code:
//$bytes = array(0,0,0,0,0,0,0,0);
//$iv = implode(array_map("chr", $bytes));
//$ciphertext = mcrypt_encrypt(MCRYPT_3DES, $key, $message, MCRYPT_MODE_CBC, $iv);
//return $ciphertext;
var bytes = [0,0,0,0,0,0,0,0];
var iv = String.fromCharCode.apply(String, bytes);
var cipher = crypto.createCipheriv("des-ede3-cbc", key, iv);
var crypted = cipher.update(""+message, 'utf8', 'hex');
crypted += cipher.final('hex');
console.log("JS output hex: " + crypted);
console.log("PHP output hex: f318a5942e4f6d5a3c14fd11f8879540");
return crypted;
}
在这里:
function mac256(ent, key, input_format){
//return hash_hmac('sha256', ent, key, true); //(PHP 5 >= 5.1.2)
var hash = crypto.createHmac('SHA256', key).update(ent, input_format).digest();
return hash;
}
使用此功能运行全部:
function run(){
var data1 = "1446117555";
var data2 = "eyJEU19NRVJDSEFOVF9BTU9VTlQiOiIxNDUiLCJEU19NRVJDSEFOVF9PUkRFUiI6IjE0NDYx";
data2 += "MTc1NTUiLCJEU19NRVJDSEFOVF9NRVJDSEFOVENPREUiOiIzMjcyMzQ2ODgiLCJEU19NRVJDSEF";
data2 += "OVF9DVVJSRU5DWSI6Ijk3OCIsIkRTX01FUkNIQU5UX1RSQU5TQUNUSU9OVFlQRSI6IjAiLCJEU1";
data2 += "9NRVJDSEFOVF9URVJNSU5BTCI6IjEiLCJEU19NRVJDSEFOVF9NRVJDSEFOVFVSTCI6Imh0dHA6X";
data2 += "C9cL3d3dy5iYW5jc2FiYWRlbGwuY29tXC91cmxOb3RpZmljYWNpb24ucGhwIiwiRFNfTUVSQ0hB";
data2 += "TlRfVVJMT0siOiJodHRwOlwvXC93d3cuYmFuY3NhYmFkZWxsLmNvbVwvdXJsT0sucGhwIiwiRFN";
data2 += "fTUVSQ0hBTlRfVVJMS08iOiJodHRwOlwvXC93d3cuYmFuY3NhYmFkZWxsLmNvbVwvdXJsS08ucGhwIn0=";
var keyb64 = "sq7HjrUOBfKmC576ILgskD5srU870gJ7";
var decodedKey = decodeBase64(keyb64);
var key3des = encrypt_3DES(data1, decodedKey);
var res = mac256(data2, key3des, 'base64');
console.log("JS mac256: ", encodeBase64(res));
console.log("PHP mac256: QfLVUv4nF2Nw7jBAkw0w8H0eRlwh2E1w/ZlKHdA2Sq0=");
return encodeBase64(res);
}