crypto.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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. import logging
  15. from typing import TYPE_CHECKING
  16. import nacl
  17. import signedjson.key
  18. if TYPE_CHECKING:
  19. from configparser import ConfigParser
  20. logger = logging.getLogger(__name__)
  21. class CryptoConfig:
  22. def parse_config(self, cfg: "ConfigParser") -> None:
  23. """
  24. Parse the crypto section of the config
  25. :param cfg: the configuration to be parsed
  26. """
  27. signing_key_str = cfg.get("crypto", "ed25519.signingkey")
  28. signing_key_parts = signing_key_str.split(" ")
  29. self.save_key = False
  30. if signing_key_str == "":
  31. logger.info(
  32. "This server does not yet have an ed25519 signing key. "
  33. "Creating one and saving it in the config file."
  34. )
  35. self.signing_key = signedjson.key.generate_signing_key("0")
  36. self.save_key = True
  37. elif len(signing_key_parts) == 1:
  38. # old format key
  39. logger.info("Updating signing key format: brace yourselves")
  40. self.signing_key = nacl.signing.SigningKey(
  41. signing_key_str, encoder=nacl.encoding.HexEncoder
  42. )
  43. self.signing_key.version = "0"
  44. self.signing_key.alg = signedjson.key.NACL_ED25519
  45. self.save_key = True
  46. else:
  47. self.signing_key = signedjson.key.decode_signing_key_base64(
  48. signing_key_parts[0], signing_key_parts[1], signing_key_parts[2]
  49. )
  50. if self.save_key:
  51. signing_key_str = "%s %s %s" % (
  52. self.signing_key.alg,
  53. self.signing_key.version,
  54. signedjson.key.encode_signing_key_base64(self.signing_key),
  55. )
  56. cfg.set("crypto", "ed25519.signingkey", signing_key_str)