NodeJS:如何将 base64 编码的字符串解码回二进制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14573001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:02:24  来源:igfitidea点击:

NodeJS: How to decode base64 encoded string back to binary?

node.jsencodingbase64decoding

提问by Xavier_Ex

I was implementing password hashing with salt, so I generated salt as binary, hashed the password, base64 encoded the password and salt then stored them into database.

我正在使用 salt 实现密码散列,所以我将 salt 生成为二进制文件,对密码进行散列,base64 对密码进行编码,然后用 salt 将它们存储到数据库中。

Now when I am checking password, I am supposed to decode the salt back into binary data, use it to hash the supplied password, base64 encode the result and check if the result matches the one in database.

现在,当我检查密码时,我应该将 salt 解码回二进制数据,使用它来散列提供的密码,对结果进行 base64 编码并检查结果是否与数据库中的结果匹配。

The problem is, I cannot find a method to decode the salt back into binary data. I encoded them using the Buffer.toString method but there doesn't seem to be reverse function.

问题是,我找不到将盐解码回二进制数据的方法。我使用 Buffer.toString 方法对它们进行了编码,但似乎没有反向功能。

回答by Matt Ball

As of Node.js v6.0.0using the constructor method has been deprecatedand the following method should instead be used to construct a new buffer from a base64 encoded string:

从 Node.js v6.0.0 开始,使用构造函数方法已被弃用,应使用以下方法从 base64 编码字符串构造新缓冲区:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

对于 Node.js v5.11.1 及以下

Construct a new Bufferand pass 'base64'as the second argument:

构造一个 newBuffer作为第二个参数传递'base64'

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether fromexists :

如果你想干净,你可以检查是否from存在:

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}