secrets.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector Ltd
  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. """
  16. Injectable secrets module for Synapse.
  17. See https://docs.python.org/3/library/secrets.html#module-secrets for the API
  18. used in Python 3.6, and the API emulated in Python 2.7.
  19. """
  20. import sys
  21. # secrets is available since python 3.6
  22. if sys.version_info[0:2] >= (3, 6):
  23. import secrets
  24. class Secrets:
  25. def token_bytes(self, nbytes=32):
  26. return secrets.token_bytes(nbytes)
  27. def token_hex(self, nbytes=32):
  28. return secrets.token_hex(nbytes)
  29. else:
  30. import binascii
  31. import os
  32. class Secrets:
  33. def token_bytes(self, nbytes=32):
  34. return os.urandom(nbytes)
  35. def token_hex(self, nbytes=32):
  36. return binascii.hexlify(self.token_bytes(nbytes)).decode("ascii")