Sha256: 7a12512c49bb851a5fc6d7398d57d150a625849878bb99bec0407ec2f8532912
Contents?: true
Size: 1.56 KB
Versions: 6
Compression:
Stored size: 1.56 KB
Contents
module OTP module Base32 BASE32_ENCODE = %w( A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 2 3 4 5 6 7 ) BASE32_DECODE = { ?A=>0, ?B=>1, ?C=>2, ?D=>3, ?E=>4, ?F=>5, ?G=>6, ?H=>7, ?I=>8, ?J=>9, ?K=>10, ?L=>11, ?M=>12, ?N=>13, ?O=>14, ?P=>15, ?Q=>16, ?R=>17, ?S=>18, ?T=>19, ?U=>20, ?V=>21, ?W=>22, ?X=>23, ?Y=>24, ?Z=>25, ?2=>26, ?3=>27, ?4=>28, ?5=>29, ?6=>30, ?7=>31, ?==>-1, } module_function def encode(bytes) return nil unless bytes ret = "" bytes = bytes.dup.force_encoding("binary") off = 0 while off < bytes.length n = 0 bits = bytes[off, 5] l = bits.length bits << "\0" while bits.length < 5 bits.each_byte{|b| n = (n << 8) | b } 8.times do |i| ret << ((l*8/5 < i) ? ?= : BASE32_ENCODE[(n >> (7-i)*5) & 0x1f]) end off += 5 end return ret end def decode(chars) return nil unless chars ret = "" chars = chars.upcase ret.force_encoding("binary") off = 0 while off < chars.length n = l = 0 bits = chars[off, 8] bits << "=" while bits.length < 8 bits.each_char.with_index do |c, i| d = BASE32_DECODE[c] raise ArgumentError, "invalid char: #{c}" unless d n <<= 5 if d >= 0 n |= d l = i * 5 / 8 end end ret << (0..l).map{|i| (n >> 32 - i * 8) & 0xff }.pack("c*") off += 8 end return ret end end end
Version data entries
6 entries across 6 versions & 1 rubygems
Version | Path |
---|---|
otp-0.0.7 | lib/otp/base32.rb |
otp-0.0.6 | lib/otp/base32.rb |
otp-0.0.5 | lib/otp/base32.rb |
otp-0.0.4 | lib/otp/base32.rb |
otp-0.0.3 | lib/otp/base32.rb |
otp-0.0.2 | lib/otp/base32.rb |