James Conr
James Conr

Reputation: 75

Simple cipher to encode URL

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?

Upvotes: 3

Views: 3459

Answers (2)

daremkd
daremkd

Reputation: 8424

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

Upvotes: 13

gmaliar
gmaliar

Reputation: 5479

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

Upvotes: 2

Related Questions