Module: Utility::Base64

Included in:
Utility
Defined in:
lib/utility/base64.rb

Constant Summary collapse

CHARS =

Base64 convert in ruby way Usually, we use Base64 module to handle everything of base64 with ‘require ’base64’‘ But now, here is the pure ruby code to do the same thing :D refer: www.webtoolkitonline.com/base64-converter.html

[*'A'..'Z', *'a'..'z', *'0'..'9', '+', '/', '=']

Instance Method Summary collapse

Instance Method Details

#base64decode(input) ⇒ Object

Convert Base64 to a string Example: base64decode(“cnVieQ==”) #=> ruby base64decode(“dXRpbGl0eQ==”) #=> utility base64decode(“5Lit5paH”) #=> 中文



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/utility/base64.rb', line 43

def base64decode(input)
  output = ""
  input = input.gsub(/[^A-Za-z0-9\+\/\=]/, "")
  (0...input.size).step(4) do |i|
    enc1, enc2, enc3, enc4 = input[i..i+3].each_char.map{|c| CHARS.index c} + [0]*3

    chr1 = (enc1 << 2) | (enc2 >> 4)
    chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)
    chr3 = ((enc3 & 3) << 6) | enc4

    output << chr1.chr
    output << chr2.chr if enc3 != 64
    output << chr3.chr if enc4 != 64
  end

  utf8_base64decode output
end

#base64encode(input) ⇒ Object

Convert a string to Base64 Example: base64encode(“ruby”) #=> cnVieQ== base64encode(“utility”) #=> dXRpbGl0eQ== base64encode(“中文”) #=> 5Lit5paH



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/utility/base64.rb', line 15

def base64encode(input)
  output = ""
  input = utf8_base64encode input
  (0...input.size).step(3) do |i|
    chr1, chr2, chr3 = input[i..i+2].each_char.map(&:ord) + [0]*2

    enc1 = chr1 >> 2
    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
    enc4 = chr3 & 63

    if chr2.zero?
      enc3 = enc4 = 64
    elsif chr3.zero?
      enc4 = 64
    end
    output << CHARS.values_at(enc1, enc2, enc3, enc4).join
  end

  output
end