Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/oscrypto/util.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

25 statements  

1# coding: utf-8 

2from __future__ import unicode_literals, division, absolute_import, print_function 

3 

4import sys 

5 

6from ._errors import pretty_message 

7from ._types import type_name, byte_cls 

8 

9if sys.platform == 'darwin': 

10 from ._mac.util import rand_bytes 

11elif sys.platform == 'win32': 

12 from ._win.util import rand_bytes 

13else: 

14 from ._openssl.util import rand_bytes 

15 

16 

17__all__ = [ 

18 'constant_compare', 

19 'rand_bytes', 

20] 

21 

22 

23def constant_compare(a, b): 

24 """ 

25 Compares two byte strings in constant time to see if they are equal 

26 

27 :param a: 

28 The first byte string 

29 

30 :param b: 

31 The second byte string 

32 

33 :return: 

34 A boolean if the two byte strings are equal 

35 """ 

36 

37 if not isinstance(a, byte_cls): 

38 raise TypeError(pretty_message( 

39 ''' 

40 a must be a byte string, not %s 

41 ''', 

42 type_name(a) 

43 )) 

44 

45 if not isinstance(b, byte_cls): 

46 raise TypeError(pretty_message( 

47 ''' 

48 b must be a byte string, not %s 

49 ''', 

50 type_name(b) 

51 )) 

52 

53 if len(a) != len(b): 

54 return False 

55 

56 if sys.version_info < (3,): 

57 a = [ord(char) for char in a] 

58 b = [ord(char) for char in b] 

59 

60 result = 0 

61 for x, y in zip(a, b): 

62 result |= x ^ y 

63 return result == 0