1

this value was encoded to base64

    {
     a: "008078888658936",
     b: "REA"
    }

and was decoded using this code

    var mytokenvalue = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ=="
    let decoded = Buffer.from(token, 'base64')

meanwhile, when I try to get the decoded value

console.log(decoded.a)

I am getting undefined in my console. Please help

Afeez Olawale
  • 65
  • 4
  • 13

2 Answers2

2

You may need to return the decoded value as a string with .toString().

let token = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ==";
let decoded = Buffer.from(token, 'base64').toString();
console.log(decoded);
Jake
  • 68
  • 1
  • 10
  • thanks for duplicating my code, the issue is to get the element of the object. like this console.log(decoded.a); – Afeez Olawale Feb 15 '19 at 15:48
  • Afeez, you're a sweetie :) Some people on here are actually trying to help you. – Jake Feb 15 '19 at 15:50
  • The issue is likely a malformed JS object before you encode it. Try this token: "ewogICJhIjogIjAwODA3ODg4ODY1ODkzNiIsCiAgImIiOiAiYWZlZXoiCn0=" – Jake Feb 15 '19 at 15:52
  • 1
    The OP's provided base64 decodes to invalid JSON because the property names are not enclosed with quotations. `{ a : "..." }` is not valid JSON, but `{ "a" : "..." }` is. Assuming the encoded base64 text indeed represents a valid JSON, this is the proper answer. – Norman Breau Feb 16 '19 at 05:35
1

You could do:

    var token = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ==";
    eval('var decoded = ' + Buffer.from(token, 'base64').toString());
    console.log(decoded.a);

But eval is extremely dangerous if the base64-encoded string can come from somewhere that is outside your control. An arbitrary string could expand to some unexpected JavaScript that would cause eval to do something that would make your program misbehave or breach security.

It would be better to express the original object as a JSON string (use JSON.stringify to do that) and base64-encode that string. Then you can use JSON.parse to reconstruct the original object without taking on the risk of using eval. Like this:

    var obj = { x: "foo", y: 123 };
    var obj_json = JSON.stringify(obj);
            // obj_json is '{"x":"foo","y":123}'
    var obj_b64 = Buffer(obj_json).toString('base64');
            // obj_b64 is 'eyJ4IjoiZm9vIiwieSI6MTIzfQ=='
    var decoded = JSON.parse(Buffer.from(obj_b64, 'base64').toString());        
    console.log(decoded.x);
ottomeister
  • 5,415
  • 2
  • 23
  • 27