/
jwk.rb
55 lines (46 loc) · 1.41 KB
/
jwk.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
module JWT
class JWK
extend Forwardable
attr_reader :keypair
def_delegators :keypair, :private?, :public_key
BINARY = 2
def initialize(keypair)
supported_key!(keypair)
@keypair = keypair
end
def supported_key!(keypair)
return if keypair.is_a?(OpenSSL::PKey::RSA)
raise JWT::JWKError, "Key of type #{keypair.class.name} not supported"
end
def 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 export
case public_key
when OpenSSL::PKey::RSA
{
kty: 'RSA',
n: Base64.urlsafe_encode64(public_key.n.to_s(BINARY), padding: false),
e: Base64.urlsafe_encode64(public_key.e.to_s(BINARY), padding: false),
kid: kid
}
end
end
class << self
def import(jwk_data)
case jwk_data[:kty]
when 'RSA'
imported_key = OpenSSL::PKey::RSA.new
imported_key.set_key(OpenSSL::BN.new(Base64.urlsafe_decode64(jwk_data[:n]), BINARY),
OpenSSL::BN.new(Base64.urlsafe_decode64(jwk_data[:e]), BINARY),
nil)
self.new(imported_key)
else
raise JWT::JWKError, "Key type #{jwk_data[:kty]} not supported"
end
end
end
end
end