module Base32

Module for encoding and decoding in Base32 per RFC 3548

Constants

TABLE
VERSION

Public Class Methods

chunks(str, size) click to toggle source
# File lib/base32.rb, line 29
def self.chunks(str, size)
  result = []
  bytes = str.bytes
  while bytes.any? do
    result << Chunk.new(bytes.take(size))
    bytes = bytes.drop(size)
  end
  result
end
decode(str) click to toggle source
# File lib/base32.rb, line 43
def self.decode(str)
  chunks(str, 8).collect(&:decode).flatten.join
end
encode(str) click to toggle source
# File lib/base32.rb, line 39
def self.encode(str)
  chunks(str, 5).collect(&:encode).flatten.join
end
random_base32(length=16, padding=true) click to toggle source
# File lib/base32.rb, line 47
def self.random_base32(length=16, padding=true)
  random = ''
  OpenSSL::Random.random_bytes(length).each_byte do |b|
    random << self.table[b % 32]
  end
  padding ? random.ljust((length / 8.0).ceil * 8, '=') : random
end
table() click to toggle source
# File lib/base32.rb, line 60
def self.table
  @table || TABLE
end
table=(table) click to toggle source
# File lib/base32.rb, line 55
def self.table=(table)
  raise ArgumentError, "Table must have 32 unique characters" unless self.table_valid?(table)
  @table = table
end
table_valid?(table) click to toggle source
# File lib/base32.rb, line 64
def self.table_valid?(table)
  table.bytes.to_a.size == 32 && table.bytes.to_a.uniq.size == 32
end