randombytes.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # Copyright 2013 Donald Stufft and individual contributors
  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. from nacl import exceptions as exc
  15. from nacl._sodium import ffi, lib
  16. randombytes_SEEDBYTES: int = lib.randombytes_seedbytes()
  17. def randombytes(size: int) -> bytes:
  18. """
  19. Returns ``size`` number of random bytes from a cryptographically secure
  20. random source.
  21. :param size: int
  22. :rtype: bytes
  23. """
  24. buf = ffi.new("unsigned char[]", size)
  25. lib.randombytes(buf, size)
  26. return ffi.buffer(buf, size)[:]
  27. def randombytes_buf_deterministic(size: int, seed: bytes) -> bytes:
  28. """
  29. Returns ``size`` number of deterministically generated pseudorandom bytes
  30. from a seed
  31. :param size: int
  32. :param seed: bytes
  33. :rtype: bytes
  34. """
  35. if len(seed) != randombytes_SEEDBYTES:
  36. raise exc.TypeError(
  37. "Deterministic random bytes must be generated from 32 bytes"
  38. )
  39. buf = ffi.new("unsigned char[]", size)
  40. lib.randombytes_buf_deterministic(buf, size, seed)
  41. return ffi.buffer(buf, size)[:]