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
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.
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.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With