添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
豪爽的饭盒  ·  Pycharm安装talib No ...·  1 年前    · 
文雅的炒饭  ·  Python ...·  1 年前    · 
读研的排球  ·  ElementHost 類別 ...·  2 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

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.

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.

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

For Node.js v5.11.1 and below

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

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

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
                And for those searching the reverse method - ( new Buffer( str ) ).toString( "base64" ).
– Nikolay Tsenkov
                Sep 5, 2015 at 18:33
                This method has been deprecated now, the correct way is now: var buf = Buffer.from(b64string, 'base64'); as noted here: nodejs.org/api/…
– Kristoffer Dorph
                May 8, 2016 at 20:48
                FYI, this code does not appear to work on older Node versions. Buffer.from is still a function on node 4.3.6, but 'TypeError: base64 is not a function'
– Doug
                Dec 21, 2016 at 21:59
                If toString('ascii') isn't working for you, try this instead: Buffer.from(string, 'base64').toString('utf-8')
– joeytwiddle
                Apr 23, 2018 at 8:37