Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/PyNaCl-1.6.0.dev1-py3.11-linux-x86_64.egg/nacl/bindings/randombytes.py: 36%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

14 statements  

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 

16from nacl import exceptions as exc 

17from nacl._sodium import ffi, lib 

18 

19randombytes_SEEDBYTES: int = lib.randombytes_seedbytes() 

20 

21 

22def 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 

35def 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)[:]