Skip to content
nov edited this page Jun 23, 2016 · 4 revisions

JSON Web Key (JWK)

Encoding

You can initiate JSON::JWK instance from an instance of

  • String
  • Hash
  • OpenSSL::PKey::RSA
  • OpenSSL::PKey::EC

JSON::JWK instance generated from String is automatically detected as kty=oct (shared key).

jwk = JSON::JWK.new 'shared-key'
jwk[:kty] # => :oct
jwk[:k]   # => 'shared-key'

Hash input is to specify each JWK element directly.

JSON::JWK.new(
  kty: :RSA,
  e: 'AQAB',
  n: 'AK8ppaAGn6N3jDic2...'
) # => RSA public key

OpenSSL::PKey::RSA and OpenSSL::PKey::EC are for kty=RSA and kty=EC, and both public and private key are supported.

private_key = OpenSSL::PKey::RSA.generate(2048)
public_key = private_key.public_key
JSON::JWK.new(private_key) # => JWK including RSA private key components
JSON::JWK.new(public_key)

This gem also defines OpenSSL::PKey::RSA#to_jwk and OpenSSL::PKey::EC#to_jwk.

private_key = OpenSSL::PKey::RSA.generate(2048)
private_key.to_jwk

You can set kid or any extensional attributes by passing option hash as 2nd argument.
If explicit kid isn't given, this gem tries to caluculate JWK thumbprint value and set it as the default kid.

JSON::JWK.new(
  private_key,
  kid: 'default'
)

If the input is a Hash, put all extensional attributes in the 1st hash.

JSON::JWK.new(
  kty: :RSA,
  e: 'AQAB',
  n: 'AK8ppaAGn6N3jDic2...',
  kid: 'default'
)

Decoding

JSON::JWK.new(hash) should works.

If you want convert an JSON::JWK instance to OpenSSL::PKey::RSA or OpenSSL::PKey::EC instance, call JSON::JWK#to_key.

jwk = JSON::JWK.new(
  kty: :RSA,
  e: 'AQAB',
  n: 'AK8ppaAGn6N3jDic2...'
)
jwk.to_key # => OpenSSL::PKey::RSA`

JSON::JWK.decode also does JSON::JWK.new(input).to_key internally for backward compatibility.

Thumbprint

[RFC7638] JSON Web Key (JWK) Thumbprint is also supported.

Just call JSON::JWK#thumbprint.

jwk = JSON::JWK.new public_key
jwk.thumbprint
Clone this wiki locally