secrets.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. def Secrets():
  25. return secrets
  26. else:
  27. import os
  28. import binascii
  29. class Secrets(object):
  30. def token_bytes(self, nbytes=32):
  31. return os.urandom(nbytes)
  32. def token_hex(self, nbytes=32):
  33. return binascii.hexlify(self.token_bytes(nbytes)).decode("ascii")