NodeJS:如何将 base64 编码的字符串解码回二进制? [英] NodeJS: How to decode base64 encoded string back to binary?

查看:21
本文介绍了NodeJS:如何将 base64 编码的字符串解码回二进制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 解码回二进制数据,使用它来散列提供的密码,对结果进行 base64 编码并检查结果是否与数据库中的匹配.

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.

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

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.

推荐答案

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

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

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

对于 Node.js v5.11.1 及以下

构造一个新的 Buffer 并将 传递 'base64' 作为第二个参数:

Construct a new Buffer and pass 'base64' as the second argument:

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

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

If you want to be clean, you can check whether from exists :

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
}

这篇关于NodeJS:如何将 base64 编码的字符串解码回二进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆