(crypto.js)TypeError:数据必须是字符串或缓冲区

时间:2016-12-19 09:23:04

标签: javascript node.js

我目前正在使用crypto.js模块来散列东西。它工作了一段时间后我开始收到这个错误:

enter image description here

这是我服务器的基础:

process.stdout.write('\033c'); // Clear the console on startup

var
    express = require("express"),
    app = express(),
    http = require("http").Server(app),
    io = require("socket.io")(http),
    path = require("path"),
    colorworks = require("colorworks").create(),

    fs = require("fs"),

    crypto = require("crypto");

    function md5(msg){
        return crypto.createHash("md5").update(msg).digest("base64");
    }
    function sha256(msg) {
        return crypto.createHash("sha256").update(msg).digest("base64");
    }

        http.listen(443, function(){
        // Create the http server so it can be accessed via 127.0.0.1:443 in a web browser.

            console.log("NJ project webserver is running on port 443.");
            // Notify the console that the server is up and running

        });

        app.use(express.static(__dirname + "/public"));

        app.get("/", function(request, response){
            response.sendFile(__dirname + "/public/index.html");
        });

我知道这些功能正在产生问题:

    function md5(msg){
        return crypto.createHash("md5").update(msg).digest("base64");
    }
    function sha256(msg) {
        return crypto.createHash("sha256").update(msg).digest("base64");
    }

问题是,如果这些功能不起作用(他们不再使用),大约200行代码就会浪费掉。

2 个答案:

答案 0 :(得分:5)

尝试散列不存在的变量时会触发此错误:

function md5(msg){
    return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
    return crypto.createHash("sha256").update(msg).digest("base64");
}
md5(non_existent); // This variable does not exist.

答案 1 :(得分:1)

您尝试哈希的是哪种数据?它从何而来 ? 我先检查一下msg的值然后再尝试:

crypto.createHash('md5').update(msg.toString()).digest('hex');

您也可以使用这些包:

https://www.npmjs.com/package/md5

https://www.npmjs.com/package/js-sha256