export_signing_key 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import argparse
  16. import sys
  17. import time
  18. from typing import Optional
  19. import nacl.signing
  20. from signedjson.key import encode_verify_key_base64, get_verify_key, read_signing_keys
  21. def exit(status: int = 0, message: Optional[str] = None):
  22. if message:
  23. print(message, file=sys.stderr)
  24. sys.exit(status)
  25. def format_plain(public_key: nacl.signing.VerifyKey):
  26. print(
  27. "%s:%s %s"
  28. % (public_key.alg, public_key.version, encode_verify_key_base64(public_key),)
  29. )
  30. def format_for_config(public_key: nacl.signing.VerifyKey, expiry_ts: int):
  31. print(
  32. ' "%s:%s": { key: "%s", expired_ts: %i }'
  33. % (
  34. public_key.alg,
  35. public_key.version,
  36. encode_verify_key_base64(public_key),
  37. expiry_ts,
  38. )
  39. )
  40. if __name__ == "__main__":
  41. parser = argparse.ArgumentParser()
  42. parser.add_argument(
  43. "key_file", nargs="+", type=argparse.FileType("r"), help="The key file to read",
  44. )
  45. parser.add_argument(
  46. "-x",
  47. action="store_true",
  48. dest="for_config",
  49. help="format the output for inclusion in the old_signing_keys config setting",
  50. )
  51. parser.add_argument(
  52. "--expiry-ts",
  53. type=int,
  54. default=int(time.time() * 1000) + 6*3600000,
  55. help=(
  56. "The expiry time to use for -x, in milliseconds since 1970. The default "
  57. "is (now+6h)."
  58. ),
  59. )
  60. args = parser.parse_args()
  61. formatter = (
  62. (lambda k: format_for_config(k, args.expiry_ts))
  63. if args.for_config
  64. else format_plain
  65. )
  66. keys = []
  67. for file in args.key_file:
  68. try:
  69. res = read_signing_keys(file)
  70. except Exception as e:
  71. exit(
  72. status=1,
  73. message="Error reading key from file %s: %s %s"
  74. % (file.name, type(e), e),
  75. )
  76. res = []
  77. for key in res:
  78. formatter(get_verify_key(key))