Debian Codegraph @

src/nacl/bindings/randombytes.py

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