1
0

export_signing_key 2.6 KB

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