我有新的使用Crypto来加密NodeJ中的音频数据。当我尝试解密数据时,我得到了一些错误输出。这是我的测试代码。
function encrypt (buf, key) {
const cipher = crypto.createCipheriv('des-ecb', key, new Buffer(0))
let c = cipher.update(Buffer.from(buf))
c += cipher.final('binary')
return c
}
function decrypt (buf, key) {
const cipher = crypto.createDecipheriv('des-ecb', key, new Buffer(0))
let c = cipher.update(buf)
c += cipher.final('binary')
return c
}
let pcmbuf = fs.readFileSync("test.pcm")
let enc = encrypt(pcmbuf,gen_key())
let dec = decrypt(enc,gen_key())
fs.writeFileSync('dec.pcm',dec)
运行此代码时出现错误。细节就像下面一样。
internal/crypto/cipher.js:104
var ret = this._handle.final();
^
Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length
at Decipheriv.final (internal/crypto/cipher.js:104:26)
at decrypt (/home/zsc/asr-js/test.js:60:17)
at Object.<anonymous> (/home/zsc/asr-js/test.js:67:11)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:190:16)
我该如何解决这个问题。谢谢你回答我的问题!
答案 0 :(得分:1)
显然问题出在填充上...由于加密/解密的语言不同...答案是here在node.js github问题页面上
引用答案
因此,在创建解密实例后调用
decrypt.setAutoPadding(false);
将使其按预期工作:
var crypto = require('crypto');
//the encrypted result
var theCipher = "ccZmMULq3tlzAY+iafZz+96xz+qFsAuGpEjhN7CckJTcdBT03fgobfSVGCGYzILyPNSA3e3msUqHUTCpv8kRnWvFdLv9c+GTEhg+Lj5dOThGDHtkQX2j5bd6Eubw9/l+Lcwj0PeyW0ZoVkB5Nnp1yCnmKAn2Euliq+IurgthT+wln6cQmTjXfL4IB5VxwUEb72FcbeiCfbKxa+MxxbcQTCpli3ErSptwdp9on2k87JTPFqyyMmMRFA9VgOXpHNe43IwFzME01DyHZ+Rp/eQguTmY9FtkFIZeD2e2nrbbDbW6tlk/KOtdhGVIlIGMPNS5m8LYqlrGZlJU3JythEy+J0z1wW1owjVe9Yto2OtUe8WeKI744enBKAX4FnD4My7+/XRjbF5kf6loT9lqeMCdXFb3LDej3GVcKWbJuZjXmD4="
var key = "abcdefghijklmnopqrstuvwx"
var decrypt = crypto.createDecipheriv('des-ede3', key, "");
//Add the auto padding here....IT HAVE TO BE after creating the decipher immeditely
decrypt.setAutoPadding(false);
var s = decrypt.update(theCipher, 'base64', 'utf8');
console.log(s + decrypt.final('utf8'));
答案 1 :(得分:0)
最后。我找到了解决这种情况的方法。传递二进制编码的字符串作为参数而不是传递缓冲代码如下。
function encrypt (buf, key) {
const cipher = crypto.createCipheriv('des-ecb', key, new Buffer(0))
let c = cipher.update(buf,'binary','base64')
c += cipher.final('base64')
return c
}
function decrypt (buf, key) {
const cipher = crypto.createDecipheriv('des-ecb', key, new Buffer(0))
let c = cipher.update(buf,'base64','base64')
c += cipher.final('base64')
return c
}
let pcmbuf = fs.readFileSync("test.pcm")
let enc = encrypt(pcmbuf.toString('binary'),gen_key())
let dec = decrypt(enc,gen_key())
fs.writeFileSync('dec.pcm',Buffer.from(dec,'base64'))