Debian Codegraph @

ansible_collections/community/crypto/plugins/module_utils/_crypto/math.py

raw
1 # Copyright (c) 2019, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10
11 def binary_exp_mod(f: int, e: int, *, m: int) -> int:
12 """Computes f^e mod m in O(log e) multiplications modulo m."""
13 # Compute len_e = floor(log_2(e))
14 len_e = -1
15 x = e
16 while x > 0:
17 x >>= 1
18 len_e += 1
19 # Compute f**e mod m
20 result = 1
21 for k in range(len_e, -1, -1):
22 result = (result * result) % m
23 if ((e >> k) & 1) != 0:
24 result = (result * f) % m
25 return result
26
27
28 def simple_gcd(a: int, b: int) -> int:
29 """Compute GCD of its two inputs."""
30 while b != 0:
31 a, b = b, a % b
32 return a
33
34
35 def quick_is_not_prime(n: int) -> bool:
36 """Does some quick checks to see if we can poke a hole into the primality of n.
37
38 A result of `False` does **not** mean that the number is prime; it just means
39 that we could not detect quickly whether it is not prime.
40 """
41 if n <= 2:
42 return n < 2
43 # The constant in the next line is the product of all primes < 200
44 prime_product = 7799922041683461553249199106329813876687996789903550945093032474868511536164700810
45 gcd = simple_gcd(n, prime_product)
46 if gcd > 1:
47 if n < 200 and gcd == n:
48 # Explicitly check for all primes < 200
49 return n not in (
50 2,
51 3,
52 5,
53 7,
54 11,
55 13,
56 17,
57 19,
58 23,
59 29,
60 31,
61 37,
62 41,
63 43,
64 47,
65 53,
66 59,
67 61,
68 67,
69 71,
70 73,
71 79,
72 83,
73 89,
74 97,
75 101,
76 103,
77 107,
78 109,
79 113,
80 127,
81 131,
82 137,
83 139,
84 149,
85 151,
86 157,
87 163,
88 167,
89 173,
90 179,
91 181,
92 191,
93 193,
94 197,
95 199,
96 )
97 return True
98 # TODO: maybe do some iterations of Miller-Rabin to increase confidence
99 # (https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test)
100 return False
101
102
103 def count_bytes(no: int) -> int:
104 """
105 Given an integer, compute the number of bytes necessary to store its absolute value.
106 """
107 no = abs(no)
108 if no == 0:
109 return 0
110 return (no.bit_length() + 7) // 8
111
112
113 def count_bits(no: int) -> int:
114 """
115 Given an integer, compute the number of bits necessary to store its absolute value.
116 """
117 no = abs(no)
118 if no == 0:
119 return 0
120 return no.bit_length()
121
122
123 def convert_int_to_bytes(no: int, *, count: int | None = None) -> bytes:
124 """
125 Convert the absolute value of an integer to a byte string in network byte order.
126
127 If ``count`` is provided, it must be sufficiently large so that the integer's
128 absolute value can be represented with these number of bytes. The resulting byte
129 string will have length exactly ``count``.
130
131 The value zero will be converted to an empty byte string if ``count`` is provided.
132 """
133 no = abs(no)
134 if count is None:
135 count = count_bytes(no)
136 return no.to_bytes(count, byteorder="big")
137
138
139 def convert_int_to_hex(no: int, *, digits: int | None = None) -> str:
140 """
141 Convert the absolute value of an integer to a string of hexadecimal digits.
142
143 If ``digits`` is provided, the string will be padded on the left with ``0``s so
144 that the returned value has length ``digits``. If ``digits`` is not sufficient,
145 the string will be longer.
146 """
147 no = abs(no)
148 value = f"{no:x}"
149 if digits is not None and len(value) < digits:
150 value = "0" * (digits - len(value)) + value
151 return value
152
153
154 def convert_bytes_to_int(data: bytes) -> int:
155 """
156 Convert a byte string to an unsigned integer in network byte order.
157 """
158 return int.from_bytes(data, byteorder="big", signed=False)
159
160
161 __all__ = (
162 "binary_exp_mod",
163 "convert_bytes_to_int",
164 "convert_int_to_bytes",
165 "convert_int_to_hex",
166 "count_bits",
167 "count_bytes",
168 "quick_is_not_prime",
169 "simple_gcd",
170 )