Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS: How to decode base64 encoded string back to binary? [duplicate]

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.

like image 313
Xavier_Ex Avatar asked Jan 28 '13 23:01

Xavier_Ex


People also ask

How do I decode Base64 data in node?

The Base64 decoding process is very much similar to the encoding process. All you need to do is create a buffer from the Base64 encoding string by using base64 as the second parameter to Buffer. from() and then decode it to the UTF-8 string by using the toString() method.

Can Base64 encoding be reversed?

Encoded data has similar paddings at the end as base64, but definitely it is not base64. Probably crypted with some SHA-like algorithm. With the data you provided, I would say that it is not possible to reverse-engineer the encoding process.

How do I decrypt a Base64 string?

To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.

Is BTOA deprecated?

The Node btoa() and atob() functions are the only ones that have been deprecated.


1 Answers

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 } 
like image 92
Matt Ball Avatar answered Sep 19 '22 20:09

Matt Ball