Skip to content

Commit

Permalink
Use the KeyAbstract
Browse files Browse the repository at this point in the history
  • Loading branch information
anakinj committed Oct 1, 2020
1 parent 3f10d36 commit eaa3a76
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 11 deletions.
23 changes: 15 additions & 8 deletions lib/jwt/jwk/rsa.rb
Expand Up @@ -2,17 +2,17 @@

module JWT
module JWK
class RSA
class RSA < KeyAbstract
attr_reader :keypair
attr_reader :jwk_kid

BINARY = 2
KTY = 'RSA'.freeze

def initialize(keypair, kid = nil)
raise ArgumentError, 'keypair must be of type OpenSSL::PKey::RSA' unless keypair.is_a?(OpenSSL::PKey::RSA)
@jwk_kid = kid

@keypair = keypair
@kid = kid
end

def private?
Expand All @@ -24,10 +24,7 @@ def public_key
end

def kid
return jwk_kid if jwk_kid
sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer.new(public_key.n),
OpenSSL::ASN1::Integer.new(public_key.e)])
OpenSSL::Digest::SHA256.hexdigest(sequence.to_der)
@kid ||= generate_kid
end

def export(options = {})
Expand All @@ -38,7 +35,7 @@ def export(options = {})
kid: kid
}

return ret if options[:include_private] != true
return ret unless private? && options[:include_private] == true

ret.merge(
d: encode_open_ssl_bn(keypair.d),
Expand All @@ -50,6 +47,14 @@ def export(options = {})
)
end

private

def generate_kid
sequence = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer.new(public_key.n),
OpenSSL::ASN1::Integer.new(public_key.e)])
OpenSSL::Digest::SHA256.hexdigest(sequence.to_der)
end

def encode_open_ssl_bn(key_part)
::Base64.urlsafe_encode64(key_part.to_s(BINARY), padding: false)
end
Expand All @@ -59,6 +64,8 @@ def import(jwk_data)
self.new(rsa_pkey(*jwk_attrs(jwk_data, :n, :e, :d, :p, :q, :dp, :dq, :qi)), jwk_data[:kid])
end

private

def jwk_attrs(jwk_data, *attrs)
attrs.map do |attr|
decode_open_ssl_bn(jwk_data[attr] || jwk_data[attr.to_s])
Expand Down
6 changes: 3 additions & 3 deletions spec/jwk/rsa_spec.rb
Expand Up @@ -34,7 +34,7 @@
it 'returns a hash with the public parts of the key' do
expect(subject).to be_a Hash
expect(subject).to include(:kty, :n, :e, :kid)
expect(subject).not_to include(:d, :p, :dp, :dq,:qi)
expect(subject).not_to include(:d, :p, :dp, :dq, :qi)
end
end

Expand All @@ -43,7 +43,7 @@
it 'returns a hash with the public parts of the key' do
expect(subject).to be_a Hash
expect(subject).to include(:kty, :n, :e, :kid)
expect(subject).not_to include(:d, :p, :dp, :dq,:qi)
expect(subject).not_to include(:d, :p, :dp, :dq, :qi)
end
end

Expand All @@ -59,7 +59,7 @@
let(:keypair) { rsa_key }
it 'returns a hash with the public AND private parts of the key' do
expect(subject).to be_a Hash
expect(subject).to include(:kty, :n, :e, :kid, :d, :p, :q, :dp, :dq,:qi)
expect(subject).to include(:kty, :n, :e, :kid, :d, :p, :q, :dp, :dq, :qi)
end
end
end
Expand Down

0 comments on commit eaa3a76

Please sign in to comment.