1
0

export_signing_key 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. % (
  29. public_key.alg,
  30. public_key.version,
  31. encode_verify_key_base64(public_key),
  32. )
  33. )
  34. def format_for_config(public_key: nacl.signing.VerifyKey, expiry_ts: int):
  35. print(
  36. ' "%s:%s": { key: "%s", expired_ts: %i }'
  37. % (
  38. public_key.alg,
  39. public_key.version,
  40. encode_verify_key_base64(public_key),
  41. expiry_ts,
  42. )
  43. )
  44. if __name__ == "__main__":
  45. parser = argparse.ArgumentParser()
  46. parser.add_argument(
  47. "key_file",
  48. nargs="+",
  49. type=argparse.FileType("r"),
  50. help="The key file to read",
  51. )
  52. parser.add_argument(
  53. "-x",
  54. action="store_true",
  55. dest="for_config",
  56. help="format the output for inclusion in the old_signing_keys config setting",
  57. )
  58. parser.add_argument(
  59. "--expiry-ts",
  60. type=int,
  61. default=int(time.time() * 1000) + 6 * 3600000,
  62. help=(
  63. "The expiry time to use for -x, in milliseconds since 1970. The default "
  64. "is (now+6h)."
  65. ),
  66. )
  67. args = parser.parse_args()
  68. formatter = (
  69. (lambda k: format_for_config(k, args.expiry_ts))
  70. if args.for_config
  71. else format_plain
  72. )
  73. keys = []
  74. for file in args.key_file:
  75. try:
  76. res = read_signing_keys(file)
  77. except Exception as e:
  78. exit(
  79. status=1,
  80. message="Error reading key from file %s: %s %s"
  81. % (file.name, type(e), e),
  82. )
  83. res = []
  84. for key in res:
  85. formatter(get_verify_key(key))