3

I want to encode a url (http://www.someurl.com) so that I can add it as a parameter to a GET call:

domain.com/encoded_url

Once received on the other end, I need to be able to decode the url, however, security is not an issue. I rather stick to a simple cipher (must be able to handle special characters like ':' and '?') since the more advanced ciphers produce encoded strings that do not pass as valid URI strings and can't be passed as URL parameters.

What kind of cipher implemented in Ruby would work best for this purpose?

James Conr
  • 65
  • 2
  • 6

2 Answers2

12

Use Base64.urlsafe_encode64

Base64 is a good idea to use, Ruby provides URL safe implementation of it, because the default will produce characters like + and =. urlsafe_encode64 will use '-' instead of '+' and '_' instead of '+' so they can be passed like URL parameters.

require "base64"

encoded_url = Base64.urlsafe_encode64('http://www.someurl.com', ) #=> "aHR0cDovL3d3dy5zb21ldXJsLmNvbQ=="
decoded_url = Base64.urlsafe_decode64(encoded_url) #=> "http://www.someurl.com"

https://apidock.com/ruby/Base64/urlsafe_encode64

Yarin
  • 173,523
  • 149
  • 402
  • 512
daremkd
  • 8,244
  • 6
  • 40
  • 66
  • This is the better answer because urlsafe_encode64 will respect the uri spec on reserved tokens as you mention. – DataDao Oct 26 '14 at 11:58
  • what would be js equivalent of `Base64.urlsafe_decode64(encoded_url)` ? – Nirav Gandhi Jun 10 '15 at 04:57
  • Note that result can still contain '=' unless you turn padding off: `encoded_url = Base64.urlsafe_encode64('http://www.someurl.com', padding:false)` – Yarin Sep 09 '22 at 19:14
2

If you really need to encode it and security is not an issue, just use Base64 and then URI escape it. But there's no need to, just uri escape it.

str = Base64.encode64(url)

encoded_str = URI.encode(str)

btw, this is a semi-possible duplicate

Ruby url encoding string

Community
  • 1
  • 1
gmaliar
  • 5,294
  • 1
  • 28
  • 36