【发布时间】:2018-01-29 11:48:42
【问题描述】:
我使用node forge 加密表单,然后使用AES 将其发送到服务器。
目前加密部分的代码是
const bigInt = require("big-integer");
const forge = require('node-forge');
function generateParams() {
// Cryptographic random number generator
var array = new Uint32Array(2);
var _key = bigInt(window.crypto.getRandomValues(array)[0]).toString();
var _iv = bigInt(window.crypto.getRandomValues(array)[1]).toString();
// generate random key and IV
var key = forge.util.encode64(_key);
var iv = forge.util.encode64(_iv);
const params = {
key: key,
iv: iv
}
return params;
}
function encrypt(params) {
var cipher = forge.rc2.createEncryptionCipher(params.key);
cipher.start(params.iv);
// Encrypting "testing"
cipher.update(forge.util.createBuffer("testing"));
cipher.finish();
return cipher.output;
}
function decrypt(params, encrypted) {
var cipher = forge.rc2.createDecryptionCipher(params.key);
cipher.start(params.iv);
cipher.update(encrypted);
cipher.finish();
return cipher.output;
}
jQuery 函数是(尚未发布)
$('#recordForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
// Grab form data
// Crypto
const params = generateParams();
const encryptedForm = {
test: encrypt(params),
}
console.log("Encrypted: " + encryptedForm.test);
const decryptedForm = {
test: decrypt(params, encryptedForm.id).data,
}
console.log("Decrypted: " + decryptedForm.test);
});
我的问题是我不断返回(cryptob.js 是我的文件名,由 browserify 生成)
Uncaught URIError: URI malformed
at decodeURIComponent (<anonymous>)
at Object.util.decodeUtf8 (cryptob.js:24437)
at ByteStringBuffer.util.ByteStringBuffer.toString (cryptob.js:23490)
at HTMLFormElement.<anonymous> (cryptob.js:1282)
at HTMLFormElement.dispatch (jquery-3.1.1.slim.min.js:3)
at HTMLFormElement.q.handle (jquery-3.1.1.slim.min.js:3)
拨打encrypt()时。
这里有this 答案,建议包含一个特殊的元标记。我已经这样做了,但它仍然不起作用。由于网上有些资源说和UTF-8编码有关,所以我尝试替换
cipher.update(forge.util.createBuffer("testing"));
与
cipher.update(forge.util.createBuffer(encodeURIComponent("testing")));
或
cipher.update(forge.util.createBuffer("testing", 'utf8'));
但它也不起作用(基于encodeURIComponent(str))。
你可以测试 forge here,如果你运行这段代码(这基本上就是我正在做的)
var forge = require("node-forge")
// generate a random key and IV
var key = forge.util.encode64("12354523465");
var iv = forge.util.encode64("2315");
// encrypt some bytes
var cipher = forge.rc2.createEncryptionCipher(key);
cipher.start(iv);
cipher.update(forge.util.createBuffer("testing"));
cipher.finish();
var encrypted = cipher.output;
console.log(encrypted);
// decrypt some bytes
var cipher = forge.rc2.createDecryptionCipher(key);
cipher.start(iv);
cipher.update(encrypted);
cipher.finish();
console.log(cipher.output.data)
它工作正常。
我该如何解决这个问题?
【问题讨论】:
-
RC2 是与 AES 不同的密码。根据文档,使用
var cipher = forge.cipher.createCipher('AES-CBC', key);或forge.aes.createEncryptionCipher(key);。此外,您不应该使用 CBC 模式。最好使用GCM模式。
标签: javascript jquery node.js encryption