BigW Consortium Gitlab

rsa_token.rb 752 Bytes
Newer Older
1
module JSONWebToken
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
  class RSAToken < Token
    attr_reader :key_file

    def initialize(key_file)
      super()
      @key_file = key_file
    end

    def encoded
      headers = {
        kid: kid
      }
      JWT.encode(payload, key, 'RS256', headers)
    end

    private

    def key_data
      @key_data ||= File.read(key_file)
    end

    def key
      @key ||= OpenSSL::PKey::RSA.new(key_data)
    end

27 28 29 30
    def public_key
      key.public_key
    end

31
    def kid
32 33 34 35 36 37 38 39
      # calculate sha256 from DER encoded ASN1
      kid = Digest::SHA256.digest(public_key.to_der)

      # we encode only 30 bytes with base32
      kid = Base32.encode(kid[0..29])

      # insert colon every 4 characters
      kid.scan(/.{4}/).join(':')
40 41 42
    end
  end
end