1# Copyright 2021 Google LLC 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS-IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14 15# [START python-jwt-jwkset-example] 16"""A utility for generating the public JWK set from the public keyset. 17""" 18 19from absl import app 20from absl import flags 21from absl import logging 22import tink 23from tink import jwt 24 25 26_PUBLIC_KEYSET_PATH = flags.DEFINE_string( 27 'public_keyset_path', None, 28 'Path to the public keyset in Tink JSON format.') 29_PUBLIC_JWK_SET_PATH = flags.DEFINE_string( 30 'public_jwk_set_path', None, 'Path to public keyset in JWK format.') 31 32 33def main(argv): 34 del argv # Unused. 35 36 # Initialise Tink 37 jwt.register_jwt_signature() 38 39 # Read the keyset into a KeysetHandle 40 with open(_PUBLIC_KEYSET_PATH.value, 'rt') as keyset_file: 41 try: 42 text = keyset_file.read() 43 public_keyset_handle = tink.read_no_secret_keyset_handle( 44 tink.JsonKeysetReader(text)) 45 except tink.TinkError as e: 46 logging.exception('Error reading keyset: %s', e) 47 return 1 48 49 # Export Public Keyset as JWK set 50 public_jwk_set = jwt.jwk_set_from_public_keyset_handle(public_keyset_handle) 51 with open(_PUBLIC_JWK_SET_PATH.value, 'wt') as public_jwk_set_file: 52 public_jwk_set_file.write(public_jwk_set) 53 logging.info('The public JWK set has been written to %s', 54 _PUBLIC_JWK_SET_PATH.value) 55 56 57if __name__ == '__main__': 58 flags.mark_flags_as_required(['public_keyset_path', 'public_jwk_set_path']) 59 app.run(main) 60 61# [END python-jwt-jwkset-example] 62