Debian Codegraph @

lib/Crypto/Math/_IntegerCustom.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2018, Helder Eijs <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 from ._IntegerNative import IntegerNative
32
33 from Crypto.Util.number import long_to_bytes, bytes_to_long
34
35 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
36 create_string_buffer,
37 get_raw_buffer, backend,
38 c_size_t, c_ulonglong)
39
40
41 from Crypto.Random.random import getrandbits
42
43 c_defs = """
44 int monty_pow(uint8_t *out,
45 const uint8_t *base,
46 const uint8_t *exp,
47 const uint8_t *modulus,
48 size_t len,
49 uint64_t seed);
50
51 int monty_multiply(uint8_t *out,
52 const uint8_t *term1,
53 const uint8_t *term2,
54 const uint8_t *modulus,
55 size_t len);
56 """
57
58
59 _raw_montgomery = load_pycryptodome_raw_lib("Crypto.Math._modexp", c_defs)
60 implementation = {"library": "custom", "api": backend}
61
62
63 class IntegerCustom(IntegerNative):
64
65 @staticmethod
66 def from_bytes(byte_string, byteorder='big'):
67 if byteorder == 'big':
68 pass
69 elif byteorder == 'little':
70 byte_string = bytearray(byte_string)
71 byte_string.reverse()
72 else:
73 raise ValueError("Incorrect byteorder")
74 return IntegerCustom(bytes_to_long(byte_string))
75
76 def inplace_pow(self, exponent, modulus=None):
77 exp_value = int(exponent)
78 if exp_value < 0:
79 raise ValueError("Exponent must not be negative")
80
81 # No modular reduction
82 if modulus is None:
83 self._value = pow(self._value, exp_value)
84 return self
85
86 # With modular reduction
87 mod_value = int(modulus)
88 if mod_value < 0:
89 raise ValueError("Modulus must be positive")
90 if mod_value == 0:
91 raise ZeroDivisionError("Modulus cannot be zero")
92
93 # C extension only works with odd moduli
94 if (mod_value & 1) == 0:
95 self._value = pow(self._value, exp_value, mod_value)
96 return self
97
98 # C extension only works with bases smaller than modulus
99 if self._value >= mod_value:
100 self._value %= mod_value
101
102 max_len = len(long_to_bytes(max(self._value, exp_value, mod_value)))
103
104 base_b = long_to_bytes(self._value, max_len)
105 exp_b = long_to_bytes(exp_value, max_len)
106 modulus_b = long_to_bytes(mod_value, max_len)
107
108 out = create_string_buffer(max_len)
109
110 error = _raw_montgomery.monty_pow(
111 out,
112 base_b,
113 exp_b,
114 modulus_b,
115 c_size_t(max_len),
116 c_ulonglong(getrandbits(64))
117 )
118
119 if error:
120 raise ValueError("monty_pow failed with error: %d" % error)
121
122 result = bytes_to_long(get_raw_buffer(out))
123 self._value = result
124 return self
125
126 @staticmethod
127 def _mult_modulo_bytes(term1, term2, modulus):
128
129 # With modular reduction
130 mod_value = int(modulus)
131 if mod_value < 0:
132 raise ValueError("Modulus must be positive")
133 if mod_value == 0:
134 raise ZeroDivisionError("Modulus cannot be zero")
135
136 # C extension only works with odd moduli
137 if (mod_value & 1) == 0:
138 raise ValueError("Odd modulus is required")
139
140 # C extension only works with non-negative terms smaller than modulus
141 if term1 >= mod_value or term1 < 0:
142 term1 %= mod_value
143 if term2 >= mod_value or term2 < 0:
144 term2 %= mod_value
145
146 modulus_b = long_to_bytes(mod_value)
147 numbers_len = len(modulus_b)
148 term1_b = long_to_bytes(term1, numbers_len)
149 term2_b = long_to_bytes(term2, numbers_len)
150 out = create_string_buffer(numbers_len)
151
152 error = _raw_montgomery.monty_multiply(
153 out,
154 term1_b,
155 term2_b,
156 modulus_b,
157 c_size_t(numbers_len)
158 )
159 if error:
160 raise ValueError("monty_multiply failed with error: %d" % error)
161
162 return get_raw_buffer(out)