Ding Yu
Ding Yu

Reputation: 151

Encode a Ruby hash using base64

Trying to encode a hash using base64 but I couldn't get the expected base64 string.

json = {
  "v": "2",
  "ps": "法国",
  "add": "fr.sangyu.tw",
  "port": "443",
  "id": "ce14d788-0f79-491e-85ca-05240612f28a",
  "aid": "233",
  "net": "ws",
  "type": "none",
  "host": "fr.sangyu.tw",
  "path": "/",
  "tls": "tls"
}

Base64.encode64 JSON.dump(json)

Expected string:

ew0KICAidiI6ICIyIiwNCiAgInBzIjogIuazleWbvSIsDQogICJhZGQiOiAiZnIuc2FuZ3l1LnR3IiwNCiAgInBvcnQiOiAiNDQzIiwNCiAgImlkIjogImNlMTRkNzg4LTBmNzktNDkxZS04NWNhLTA1MjQwNjEyZjI4YSIsDQogICJhaWQiOiAiMjMzIiwNCiAgIm5ldCI6ICJ3cyIsDQogICJ0eXBlIjogIm5vbmUiLA0KICAiaG9zdCI6ICJmci5zYW5neXUudHciLA0KICAicGF0aCI6ICIvIiwNCiAgInRscyI6ICJ0bHMiDQp9

My (incorrect) string:

eyJ2IjoiMiIsInBzIjoi5rOV5Zu9IiwiYWRkIjoiZnIuc2FuZ3l1LnR3Iiwi cG9ydCI6IjQ0MyIsImlkIjoiY2UxNGQ3ODgtMGY3OS00OTFlLTg1Y2EtMDUy NDA2MTJmMjhhIiwiYWlkIjoiMjMzIiwibmV0Ijoid3MiLCJ0eXBlIjoibm9u ZSIsImhvc3QiOiJmci5zYW5neXUudHciLCJwYXRoIjoiLyIsInRscyI6InRs cyJ9

I saw the question How to encode a hash using Ruby Base64 module but it didn't work for me.

Upvotes: 1

Views: 1504

Answers (2)

Rafayet Monon
Rafayet Monon

Reputation: 1179

You can use -

Base64.strict_encode64(JSON.pretty_generate(json))

The base64 string it generates is different from what you expect

ewogICJ2IjogIjIiLAogICJwcyI6ICLms5Xlm70iLAogICJhZGQiOiAiZnIuc2FuZ3l1LnR3IiwKICAicG9ydCI6ICI0NDMiLAogICJpZCI6ICJjZTE0ZDc4OC0wZjc5LTQ5MWUtODVjYS0wNTI0MDYxMmYyOGEiLAogICJhaWQiOiAiMjMzIiwKICAibmV0IjogIndzIiwKICAidHlwZSI6ICJub25lIiwKICAiaG9zdCI6ICJmci5zYW5neXUudHciLAogICJwYXRoIjogIi8iLAogICJ0bHMiOiAidGxzIgp9

But the content it generates are same.

Also I tried encoding your json in https://www.base64encode.org/ which generates the same string mentioned above in this answer.

Upvotes: 0

Igor Kapkov
Igor Kapkov

Reputation: 3909

You do it correctly. There are a couple of reasons you don't get your expected output.

JSON.dump(json) generates the following (no formatting):

{"v":"2","ps":"","add":"fr.sangyu.tw","port":"443","id":"ce14d788-0f79-491e-85ca-05240612f28a","aid":"233","net":"ws","type":"none","host":"fr.sangyu.tw","path":"/","tls":"tls"}

You may want to use JSON.pretty_generate(json) which produce:

{
  "v": "2",
  "ps": "",
  "add": "fr.sangyu.tw",
  "port": "443",
  "id": "ce14d788-0f79-491e-85ca-05240612f28a",
  "aid": "233",
  "net": "ws",
  "type": "none",
  "host": "fr.sangyu.tw",
  "path": "/",
  "tls": "tls"
}

Lastly, I don't know which OS you are on or how you got your original expected base64, but they may have different line endings \n vs \r\n, which may cause different base64.

Upvotes: 3

Related Questions