Class: URLcrypt::Chunk

Inherits:
Object
  • Object
show all
Defined in:
lib/URLcrypt.rb

Instance Method Summary collapse

Constructor Details

#initialize(bytes) ⇒ Chunk

Returns a new instance of Chunk.



14
15
16
# File 'lib/URLcrypt.rb', line 14

def initialize(bytes)
  @bytes = bytes
end

Instance Method Details

#decodeObject



18
19
20
21
22
23
24
25
# File 'lib/URLcrypt.rb', line 18

def decode
  bytes = @bytes.take_while {|c| c != 61} # strip padding
  bytes = bytes.find_all{|b| !TABLE.index(b.chr).nil? } # remove invalid characters
  n = (bytes.length * 5.0 / 8.0).floor
  p = bytes.length < 8 ? 5 - (n * 8) % 5 : 0
  c = bytes.inject(0) {|m,o| (m << 5) + TABLE.index(o.chr)} >> p
  (0..n-1).to_a.reverse.collect {|i| ((c >> i * 8) & 0xff).chr}
end

#encodeObject



27
28
29
30
31
32
33
# File 'lib/URLcrypt.rb', line 27

def encode
  n = (@bytes.length * 8.0 / 5.0).ceil
  p = n < 8 ? 5 - (@bytes.length * 8) % 5 : 0
  c = @bytes.inject(0) {|m,o| (m << 8) + o} << p
  [(0..n-1).to_a.reverse.collect {|i| TABLE[(c >> i * 5) & 0x1f].chr},
   ("=" * (8-n))] # TODO: remove '=' padding generation
end