Advertisement
Narzew

Stesla's Base64 Algorithm

Sep 18th, 2012
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.09 KB | None | 0 0
  1. #**by Stesla
  2. module Base32
  3.   TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
  4.   class Chunk
  5.     def initialize(bytes)
  6.       @bytes = bytes
  7.     end
  8.     def decode
  9.       bytes = @bytes.take_while {|c| c != 61} # strip padding
  10.       n = (bytes.length * 5.0 / 8.0).floor
  11.       p = bytes.length < 8 ? 5 - (n * 8) % 5 : 0
  12.       c = bytes.inject(0) {|m,o| (m << 5) + TABLE.index(o.chr)} >> p
  13.       (0..n-1).to_a.reverse.collect {|i| ((c >> i * 8) & 0xff).chr}
  14.     end
  15.     def encode
  16.       n = (@bytes.length * 8.0 / 5.0).ceil
  17.       p = n < 8 ? 5 - (@bytes.length * 8) % 5 : 0
  18.       c = @bytes.inject(0) {|m,o| (m << 8) + o} << p
  19.       [(0..n-1).to_a.reverse.collect {|i| TABLE[(c >> i * 5) & 0x1f].chr},
  20.        ("=" * (8-n))]
  21.     end
  22.   end
  23.   def self.chunks(str, size)
  24.     result = []
  25.     bytes = str.bytes
  26.     while bytes.any? do
  27.       result << Chunk.new(bytes.take(size))
  28.       bytes = bytes.drop(size)
  29.     end
  30.     result
  31.   end
  32.   def self.encode(str)
  33.     chunks(str, 5).collect(&:encode).flatten.join
  34.   end
  35.   def self.decode(str)
  36.     chunks(str, 8).collect(&:decode).flatten.join
  37.   end
  38. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement