Module: K3CloudWebapiSdk::Util::Base64Util

Defined in:
lib/k3cloud_webapi_sdk/util/base64_util.rb

Constant Summary collapse

CHARSET =
('A'..'Z').to_a.join + ('a'..'z').to_a.join + ('0'..'9').to_a.join + '+/'

Class Method Summary collapse

Class Method Details

.decode(base64_str) ⇒ Object

Custom base64 decode



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/k3cloud_webapi_sdk/util/base64_util.rb', line 41

def self.decode(base64_str)
  return [] if !valid_base64_str(base64_str)
  
  # Remove padding for processing
  chars_to_process = base64_str.gsub('=', '')
  
  # Convert to 6-bit chunks
  base64_bytes = chars_to_process.chars.map do |c|
    CHARSET.index(c).to_s(2).rjust(6, '0')
  end
  
  resp = []
  nums = base64_bytes.length / 4
  remain = base64_bytes.length % 4
  
  # Process complete 4-chunk units
  (0...nums).each do |i|
    tmp_unit = base64_bytes[i*4..i*4+3].join('')
    [0, 8, 16].each do |offset|
      value = tmp_unit[offset, 8].to_i(2)
      resp << value
    end
  end
  
  # Handle remaining chunks
  if remain > 0
    remain_part = base64_bytes[nums*4..-1].join('')
    (0...remain-1).each do |i|
      value = remain_part[i*8, 8].to_i(2)
      resp << value
    end
  end
  
  resp
end

.encode(origin_bytes) ⇒ Object

Custom base64 encode (Ruby equivalent of Python’s base64_util.py)



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/k3cloud_webapi_sdk/util/base64_util.rb', line 7

def self.encode(origin_bytes)
  return '' if origin_bytes.nil? || origin_bytes.empty?
  
  # Convert to binary string
  base64_bytes = origin_bytes.bytes.map { |b| b.to_s(2).rjust(8, '0') }
  
  resp = ''
  nums = base64_bytes.length / 3
  remain = base64_bytes.length % 3
  
  # Process complete 3-byte chunks
  (0...nums).each do |i|
    tmp_unit = base64_bytes[i*3..i*3+2].join('')
    [0, 6, 12, 18].each do |offset|
      value = tmp_unit[offset, 6].to_i(2)
      resp << CHARSET[value]
    end
  end
  
  # Handle remaining bytes
  if remain > 0
    remain_part = base64_bytes[nums*3..-1].join('').ljust((3-remain)*8, '0')
    [0, 6, 12, 18].each_with_index do |offset, idx|
      break if idx >= remain + 1
      value = remain_part[offset, 6].to_i(2)
      resp << CHARSET[value]
    end
    resp << '=' * (3 - remain)
  end
  
  resp
end

.valid_base64_str(b_str) ⇒ Object

Validate base64 string



78
79
80
81
# File 'lib/k3cloud_webapi_sdk/util/base64_util.rb', line 78

def self.valid_base64_str(b_str)
  return false if b_str.length % 4 != 0
  b_str.each_char.all? { |m| CHARSET.include?(m) }
end