Module: Base32

Defined in:
lib/base32.rb,
lib/version.rb

Overview

Module for encoding and decoding in Base32 per RFC 3548

Defined Under Namespace

Classes: Chunk

Constant Summary collapse

TABLE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.freeze
VERSION =
'0.3.0'

Class Method Summary collapse

Class Method Details

.chunks(str, size) ⇒ Object



29
30
31
32
33
34
35
36
37
# 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) ⇒ Object



43
44
45
# File 'lib/base32.rb', line 43

def self.decode(str)
  chunks(str, 8).collect(&:decode).flatten.join
end

.encode(str) ⇒ Object



39
40
41
# File 'lib/base32.rb', line 39

def self.encode(str)
  chunks(str, 5).collect(&:encode).flatten.join
end

.random_base32(length = 16) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/base32.rb', line 47

def self.random_base32(length=16)
  random = ''
  OpenSSL::Random.random_bytes(length).each_byte do |b|
    random << self.table[b % 32]
  end
  random.ljust((length / 8.0).ceil * 8, '=') # add padding
end

.tableObject



60
61
62
# File 'lib/base32.rb', line 60

def self.table
  @table || TABLE
end

.table=(table) ⇒ Object

Raises:

  • (ArgumentError)


55
56
57
58
# 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) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/base32.rb', line 64

def self.table_valid?(table)
  table.bytes.size == 32 && table.bytes.uniq.size == 32
end