我正在使用node-forge加密一些客户端数据,我将其发送到服务器以存储在mongoDB集合中。
我的问题是,尽管能够生成数据客户端,但服务器只接收一个空字符串。
jQuery代码是
$('#recordForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this),
_id = $form.find("input[name='_id']" ).val();
// Grab form data
// Crypto
const params = generateParams();
const encryptedForm = {
test: encrypt(params, _id),
}
console.log(encryptedForm.test.data); // correctly logs à:û^ìQ%
const decryptedForm = {
test: decrypt(params, encryptedForm.test).data,
}
console.log("Decrypted text: " + decryptedForm.test);
url = $form.attr("action");
// Send the data using post
$.post(url, {id: encryptedForm.test.data});
});
尽管正确记录encryptedForm.test.data
,服务器才会收到回传
{ id: '' }
记录req.body
时。
我尝试使用Chrome的开发者工具,并记录记录此
的encryptedForm.test
ByteStringBuffer {data: "ÐæáÁþà", read: 0, _constructedStringLength: 8}
data:""
read:0
_constructedStringLength:8
__proto__: Object
将数据显示为""
。这可以解释服务器也看到""
但是为什么console.log(encryptedForm.test.data)
会正确记录à:û^ìQ%
?
我做错了什么?
编辑:添加encrypt()代码以澄清
// Encrypt under symmetric key
function encrypt(params, m) {
var cipher = forge.rc2.createEncryptionCipher(params.key);
cipher.start(params.iv);
cipher.update(forge.util.createBuffer(m));
cipher.finish();
return cipher.output;
}
答案 0 :(得分:0)
尝试发布一些应该发布的纯文本。您发送的字符可能有问题,但不支持
url = $form.attr("action");
// Send the data using post
$.post(url, {id: 'hello'});
答案 1 :(得分:0)
在将所有内容转换为十六进制后,我设法修复了它。
function encrypt(params, m) {
var cipher = forge.rc2.createEncryptionCipher(params.key);
cipher.start(params.iv);
cipher.update(forge.util.createBuffer(m));
cipher.finish();
return cipher.output.toHex();
}
伪造中有一种方法可以将十六进制转换为可用于解密的对象。我们可以这样做
const enc = encrypt(params, m);
// the line below can be used to convert the hex back for decryption
forge.util.createBuffer(forge.util.hexToBytes(enc))
这样,一切都在伪造加密和解密,服务器收到正确的值。