Class: JSON::JWK

Inherits:
ActiveSupport::HashWithIndifferentAccess
  • Object
show all
Defined in:
lib/json/jwk.rb

Defined Under Namespace

Classes: Set, UnknownAlgorithm

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(public_key, options = {}) ⇒ JWK

Returns a new instance of JWK.



5
6
7
# File 'lib/json/jwk.rb', line 5

def initialize(public_key, options = {})
  replace encode(public_key, options)
end

Class Method Details

.decode(jwk) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/json/jwk.rb', line 78

def decode(jwk)
  jwk = jwk.with_indifferent_access
  case jwk[:kty].to_s
  when 'RSA'
    e = OpenSSL::BN.new UrlSafeBase64.decode64(jwk[:e]), 2
    n = OpenSSL::BN.new UrlSafeBase64.decode64(jwk[:n]), 2
    key = OpenSSL::PKey::RSA.new
    key.e = e
    key.n = n
    key
  when 'EC'
    if RUBY_VERSION >= '2.0.0'
      key = OpenSSL::PKey::EC.new ecdsa_curve_name_for(jwk[:crv])
      x, y = [jwk[:x], jwk[:y]].collect do |decoded|
        OpenSSL::BN.new UrlSafeBase64.decode64(decoded), 2
      end
      key.public_key = OpenSSL::PKey::EC::Point.new(key.group).mul(x, y)
      key
    else
      raise UnknownAlgorithm.new('ECDSA JWK Decoding requires Ruby 2.0+')
    end
  else
    raise UnknownAlgorithm.new('Unknown Algorithm')
  end
end

.ecdsa_curve_identifier_for(curve_name) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/json/jwk.rb', line 65

def ecdsa_curve_identifier_for(curve_name)
  case curve_name
  when 'prime256v1'
    :'P-256'
  when 'secp384r1'
    :'P-384'
  when 'secp521r1'
    :'P-521'
  else
    raise UnknownAlgorithm.new('Unknown ECDSA Curve')
  end
end

.ecdsa_curve_name_for(curve_identifier) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/json/jwk.rb', line 52

def ecdsa_curve_name_for(curve_identifier)
  case curve_identifier.to_s
  when 'P-256'
    'prime256v1'
  when 'P-384'
    'secp384r1'
  when 'P-521'
    'secp521r1'
  else
    raise UnknownAlgorithm.new('Unknown ECDSA Curve')
  end
end

.new_from_hash_copying_default(hash) ⇒ Object

NOTE: Ugly hack to avoid this ActiveSupport 4.0 bug.

https://github.com/rails/rails/issues/11087


106
107
108
# File 'lib/json/jwk.rb', line 106

def new_from_hash_copying_default(hash)
  superclass.new_from_hash_copying_default hash
end

Instance Method Details

#content_typeObject



9
10
11
# File 'lib/json/jwk.rb', line 9

def content_type
  'application/jwk+json'
end