Module: Yubikey::ModHex

Defined in:
lib/yubikey/modhex.rb

Constant Summary collapse

TRANS =
'cbdefghijklnrtuv'.split(//)

Class Method Summary collapse

Class Method Details

.decode(modhex_string) ⇒ Object

Decode a ModHex string into binary data

Raises:

  • (ArgumentError)

6
7
8
9
10
11
12
13
14
15
# File 'lib/yubikey/modhex.rb', line 6

def self.decode(modhex_string)
  raise ArgumentError, "ModHex string length is not even" unless modhex_string.length % 2 == 0
  
  chars = 'cbdefghijklnrtuv'
  result = ""
  modhex_string.scan(/../).each do |c|
    result += (chars.index(c[0]) * 16 + chars.index(c[1])).chr
  end
  result
end

.encode(string) ⇒ Object

Encode a binary string into ModHex


18
19
20
21
22
23
24
25
26
27
# File 'lib/yubikey/modhex.rb', line 18

def self.encode(string)
  result = ''
  
  string.each_byte do |b|
    result <<= TRANS[(b >> 4) & 0xF]
    result <<= TRANS[b & 0xF]
  end
  
  result
end