Skip to content

Commit

Permalink
preserve kid when importing
Browse files Browse the repository at this point in the history
  • Loading branch information
rkmetzl authored and anakinj committed Oct 9, 2020
1 parent ac4f4e8 commit 876f6cd
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/jwt/jwk/rsa.rb
Expand Up @@ -4,13 +4,14 @@ module JWT
module JWK
class RSA
attr_reader :keypair
attr_reader :jwk_kid

BINARY = 2
KTY = 'RSA'.freeze

def initialize(keypair)
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
end

Expand All @@ -23,6 +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)
Expand All @@ -47,15 +49,15 @@ def self.import(jwk_data)

raise JWT::JWKError, 'Key format is invalid for RSA' unless jwk_n && jwk_e

self.new(rsa_pkey(jwk_n, jwk_e))
self.new(rsa_pkey(jwk_n, jwk_e), jwk_data[:kid] || jwk_data['kid'])
end

def self.rsa_pkey(jwk_n, jwk_e)
key = OpenSSL::PKey::RSA.new
key_n = decode_open_ssl_bn(jwk_n)
key_e = decode_open_ssl_bn(jwk_e)

if key.respond_to?(:set_key)
self.new(imported_key)
key.set_key(key_n, key_e, nil)
else
key.n = key_n
Expand Down
7 changes: 7 additions & 0 deletions spec/jwk_spec.rb
Expand Up @@ -33,6 +33,13 @@
expect { subject }.to raise_error(JWT::JWKError)
end
end

context 'when keypair with defined kid is imported' do
it 'returns the predefined kid if jwt_data contains a kid' do
params[:kid] = "CUSTOM_KID"
expect(subject.export).to eq(params)
end
end
end

describe '.new' do
Expand Down

0 comments on commit 876f6cd

Please sign in to comment.