Last active
February 10, 2018 08:37
-
-
Save ardbytes/3bf97164563359cdf16607ef4bf1ce04 to your computer and use it in GitHub Desktop.
Encode text to base64
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# References: | |
# | |
# https://en.wikipedia.org/wiki/Base64 | |
require 'base64' | |
TABLE = ('A'..'Z').to_a + ('a'..'z').to_a + ("0".."9").to_a + ['+','/'] | |
class String | |
def bit_string | |
bytes.collect do |byte| | |
byte.to_s(2).rjust(8, "0") | |
end.join | |
end | |
end | |
def pad_len(str) | |
if str.length % 24 == 0 | |
0 | |
else | |
24 - (str.length % 24) | |
end | |
end | |
def add_padding(bit_string) | |
bit_string + "0" * pad_len(bit_string) | |
end | |
def _encode(text) | |
if text == "000000" | |
"=" | |
else | |
TABLE[text.to_i(2)] | |
end | |
end | |
def encode(text) | |
text = add_padding(text.bit_string) | |
result = "" | |
while text.length != 0 | |
result += _encode(text.slice!(0,6)) | |
end | |
result | |
end | |
def _decode(text) | |
out_char_len = 4 | |
if text[-1] == "=" | |
out_char_len = 3 | |
text[-1] = "" | |
end | |
if text[-1] == "=" | |
out_char_len = 2 | |
text[-1] = "" | |
end | |
bit_string = text.length.times.collect do |i| | |
TABLE.index(text[i]).to_s(2).rjust(6, "0") | |
end.join | |
out_char_len.times.collect do |i| | |
if bit_string[0+(i*8)...8+(i*8)].to_i(2) > 0 | |
bit_string[0+(i*8)...8+(i*8)].to_i(2).chr | |
end | |
end.join | |
end | |
def decode(text) | |
result = "" | |
while text.length >= 4 | |
result += _decode(text.slice!(0,4)) | |
end | |
result | |
end | |
text = "Olá" | |
puts encode(text) == Base64.strict_encode64(text) | |
puts encode(text) | |
puts decode(encode(text)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment