=begin Copyright (c) 2020 Marek Küthe This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. =end module BaseX Base64CodingTable = { 0 => "A", 1 => "B", 2 => "C", 3 => "D", 4 => "E", 5 => "F", 6 => "G", 7 => "H", 8 => "I", 9 => "J", 10 => "K", 11 => "L", 12 => "M", 13 => "N", 14 => "O", 15 => "P", 16 => "Q", 17 => "R", 18 => "S", 19 => "T", 20 => "U", 21 => "V", 22 => "W", 23 => "X", 24 => "Y", 25 => "Z", 26 => "a", 27 => "b", 28 => "c", 29 => "d", 30 => "e", 31 => "f", 32 => "g", 33 => "h", 34 => "i", 35 => "j", 36 => "k", 37 => "l", 38 => "m", 39 => "n", 40 => "o", 41 => "p", 42 => "q", 43 => "r", 44 => "s", 45 => "t", 46 => "u", 47 => "v", 48 => "w", 49 => "x", 50 => "y", 51 => "z", 52 => "0",53 => "1",54 => "2", 55 => "3",56 => "4",57 => "5", 58 => "6",59 => "7",60 => "8", 61 => "9", 62 => "+", 63 => "/", :padding => "=" } Base32CodingTable = { 0 => "A", 1 => "B", 2 => "C", 3 => "D", 4 => "E", 5 => "F", 6 => "G", 7 => "H", 8 => "I", 9 => "J", 10 => "K", 11 => "L", 12 => "M", 13 => "N", 14 => "O", 15 => "P", 16 => "Q", 17 => "R", 18 => "S", 19 => "T", 20 => "U", 21 => "V", 22 => "W", 23 => "X", 24 => "Y", 25 => "Z", 26 => "2", 27 => "3", 28 => "4", 29 => "5", 30 => "6", 31 => "7", :padding => "=" } def self.encode str, table = Base64CodingTable, base = 64 bn = (base-1).to_s(2).length binstr = String.new str.each_byte { |b| tmp = b.to_s(2) tmp = ("0" * (8 - tmp.length)) + tmp binstr << tmp } padd = binstr.length % 3 binstr += "0000" if padd == 1 res = String.new for i in (0...binstr.length).step bn res << table[binstr[i...i+bn].to_i 2] end res += table[:padding] * padd return res end def self.decode str, table = Base64CodingTable, base = 64 itable = table.invert bn = (base-1).to_s(2).length padd = str.count table[:padding] str = str[0...-padd] if padd != 0 binstr = String.new str.each_char { |c| tmp = itable[c].to_s 2 tmp = ("0" * (bn - tmp.length)) + tmp binstr << tmp } res = String.new for i in (0...binstr.length).step 8 res << binstr[i...i+8].to_i(2).chr end return res.delete("\x00") end end # p BaseX.decode "KRSXG5A", BaseX::Base32CodingTable, 32