Class: WebAuthn::Encoder

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

Constant Summary collapse

STANDARD_ENCODING =
:base64url

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(encoding = STANDARD_ENCODING) ⇒ Encoder

Returns a new instance of Encoder.



16
17
18
# File 'lib/webauthn/encoder.rb', line 16

def initialize(encoding = STANDARD_ENCODING)
  @encoding = encoding
end

Instance Attribute Details

#encodingObject (readonly)

Returns the value of attribute encoding.



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

def encoding
  @encoding
end

Instance Method Details

#decode(data) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/webauthn/encoder.rb', line 36

def decode(data)
  case encoding
  when :base64
    data.unpack1("m0") # Base64.strict_decode64(data)
  when :base64url
    if !data.end_with?("=") && data.length % 4 != 0 #  Base64.urlsafe_decode64(data)
      data = data.ljust((data.length + 3) & ~3, "=")
      data.tr!("-_", "+/")
    else
      data = data.tr("-_", "+/")
    end
    data.unpack1("m0")
  when nil, false
    data
  else
    raise "Unsupported or unknown encoding: #{encoding}"
  end
end

#encode(data) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/webauthn/encoder.rb', line 20

def encode(data)
  case encoding
  when :base64
    [data].pack("m0") # Base64.strict_encode64(data)
  when :base64url
    data = [data].pack("m0") # Base64.urlsafe_encode64(data, padding: false)
    data.chomp!("==") or data.chomp!("=")
    data.tr!("+/", "-_")
    data
  when nil, false
    data
  else
    raise "Unsupported or unknown encoding: #{encoding}"
  end
end