在Node.js中使用加密时的错误处理

10

我正在使用Node.js的加密库进行加密/解密操作,代码如下:

    encrypt = function(text, passPhrase){
        var cipher = crypto.createCipher('AES-128-CBC-HMAC-SHA1', passPhrase);
        var crypted = cipher.update(text,'utf8','hex');
        crypted += cipher.final('hex');
        return crypted;
    } ,

    decrypt = function(text, passPhrase){
        var decipher = crypto.createDecipher('AES-128-CBC-HMAC-SHA1', passPhrase)
        var dec = decipher.update(text,'hex','utf8')
        dec += decipher.final('utf8');
        return dec;
    }

加密部分没有问题。如果我发送正确的密码短语进行解密也没有问题。我的问题是,如果我发送了“错误”的密码短语进行解密,代码会崩溃并抛出一个错误:

TypeError: Bad input string
    at Decipher.Cipher.update (crypto.js:279:27)
    at module.exports.decrypt (/xxxx/yyyyy/jjj/ssss/encryptionService.js:19:28)
    at Object.module.exports.passwordDecryptor (/xxxx/yyyyy/jjj/ssss/encryptionService.js:59:56)
    at Object.<anonymous> (/xxxx/yyyyy/jjj/ssss/test.js:32:33)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

我不希望它发生。我希望例如解密函数返回“密码错误”的句子。根据文档createDecipher函数不接受回调函数。


我也遇到了这个挑战。加密库没有处理那里的错误吗? - Costa Michailidis
1个回答

15

我用trycatch解决了问题。(回调函数无法正常工作。)

 decrypt = function(text, passPhrase){
        var decipher = crypto.createDecipher('AES-128-CBC-HMAC-SHA1', passPhrase);
        try {
            var dec = decipher.update(text,'hex','utf8');
            dec += decipher.final('utf8');
            return dec;
        } catch (ex) {
            console.log('failed');
            return;
        }
    }

你可以创建一个错误对象并抛出它,然后在代码的其他地方捕获它,而不是使用console.log()。 - Danial
当使用管道时,知道如何捕获错误肯定是很好的。啊,框架,混淆无处不在。 - David Dombrowsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接