Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion with base64 class methods usage

Tags:

ruby

Could anyone help me here to understand when we need to consider the below 4 methods:

strict_decode64(str)
strict_encode64(bin)
urlsafe_encode64(bin)
urlsafe_decode64(str)

From the doc also I didn't get any examples. So examples with explanation might be helpful for me to understand.

Thanks in advance

like image 370
Arup Rakshit Avatar asked Mar 08 '13 19:03

Arup Rakshit


2 Answers

The _encode and _decode do opposite things: the first one converts a normal string into an encoded string, and the second one converts an encoded string into a normal string.

str = "Hello!"
str == decode64(encode64(str)) # This is true

The difference between strict_ and urlsafe_ is the characters that will be used inside the encoded string. When you need to pass your string inside a URL, all characters are not allowed (like / for instance, because it has a special meaning in URLs) so you should use the urlsafe_ version.

like image 53
alestanis Avatar answered Sep 28 '22 00:09

alestanis


An example of usage would be:

require "base64"
Base64.strict_encode64('Stuff to be encoded')
Base64.strict_decode64("U3R1ZmYgdG8gYmUgZW5jb2RlZA==")

Strict means that white spaces / CR/LF are rejected at decode and CR/LF are not added at encode.

Note that if the folowing is accepted:

Base64.decode64("U3R1ZmYgdG8gYmUgZW5jb2RlZA==\n")

with strict the above is not accepted because of the trailing \n (linefeed) and the following line will throw ArgumentError: invalid base64 exception:

Base64.strict_decode64("U3R1ZmYgdG8gYmUgZW5jb2RlZA==\n")

So strict accepts/expects only alphanumeric characters at decode and returns only alphanumeric at encode.

Please try the following and see how one encodes wraps the lines every 60 characters with '\n' (linefeed) and the strict doesn't:

print Base64.encode64('I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines.I will not use spaces and new lines.')


print Base64.strict_encode64('I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines. I will not use spaces and new lines.I will not use spaces and new lines.')
like image 42
Eduard Florinescu Avatar answered Sep 28 '22 02:09

Eduard Florinescu