_IntegerCustom.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # ===================================================================
  2. #
  3. # Copyright (c) 2018, Helder Eijs <helderijs@gmail.com>
  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. from ._IntegerNative import IntegerNative
  31. from Crypto.Util.number import long_to_bytes, bytes_to_long
  32. from Crypto.Util._raw_api import (load_pycryptodome_raw_lib,
  33. create_string_buffer,
  34. get_raw_buffer, backend,
  35. c_size_t, c_ulonglong)
  36. from Crypto.Random.random import getrandbits
  37. c_defs = """
  38. int monty_pow(uint8_t *out,
  39. const uint8_t *base,
  40. const uint8_t *exp,
  41. const uint8_t *modulus,
  42. size_t len,
  43. uint64_t seed);
  44. int monty_multiply(uint8_t *out,
  45. const uint8_t *term1,
  46. const uint8_t *term2,
  47. const uint8_t *modulus,
  48. size_t len);
  49. """
  50. _raw_montgomery = load_pycryptodome_raw_lib("Crypto.Math._modexp", c_defs)
  51. implementation = {"library": "custom", "api": backend}
  52. class IntegerCustom(IntegerNative):
  53. @staticmethod
  54. def from_bytes(byte_string, byteorder='big'):
  55. if byteorder == 'big':
  56. pass
  57. elif byteorder == 'little':
  58. byte_string = bytearray(byte_string)
  59. byte_string.reverse()
  60. else:
  61. raise ValueError("Incorrect byteorder")
  62. return IntegerCustom(bytes_to_long(byte_string))
  63. def inplace_pow(self, exponent, modulus=None):
  64. exp_value = int(exponent)
  65. if exp_value < 0:
  66. raise ValueError("Exponent must not be negative")
  67. # No modular reduction
  68. if modulus is None:
  69. self._value = pow(self._value, exp_value)
  70. return self
  71. # With modular reduction
  72. mod_value = int(modulus)
  73. if mod_value < 0:
  74. raise ValueError("Modulus must be positive")
  75. if mod_value == 0:
  76. raise ZeroDivisionError("Modulus cannot be zero")
  77. # C extension only works with odd moduli
  78. if (mod_value & 1) == 0:
  79. self._value = pow(self._value, exp_value, mod_value)
  80. return self
  81. # C extension only works with bases smaller than modulus
  82. if self._value >= mod_value:
  83. self._value %= mod_value
  84. max_len = len(long_to_bytes(max(self._value, exp_value, mod_value)))
  85. base_b = long_to_bytes(self._value, max_len)
  86. exp_b = long_to_bytes(exp_value, max_len)
  87. modulus_b = long_to_bytes(mod_value, max_len)
  88. out = create_string_buffer(max_len)
  89. error = _raw_montgomery.monty_pow(
  90. out,
  91. base_b,
  92. exp_b,
  93. modulus_b,
  94. c_size_t(max_len),
  95. c_ulonglong(getrandbits(64))
  96. )
  97. if error:
  98. raise ValueError("monty_pow failed with error: %d" % error)
  99. result = bytes_to_long(get_raw_buffer(out))
  100. self._value = result
  101. return self
  102. @staticmethod
  103. def _mult_modulo_bytes(term1, term2, modulus):
  104. # With modular reduction
  105. mod_value = int(modulus)
  106. if mod_value < 0:
  107. raise ValueError("Modulus must be positive")
  108. if mod_value == 0:
  109. raise ZeroDivisionError("Modulus cannot be zero")
  110. # C extension only works with odd moduli
  111. if (mod_value & 1) == 0:
  112. raise ValueError("Odd modulus is required")
  113. # C extension only works with non-negative terms smaller than modulus
  114. if term1 >= mod_value or term1 < 0:
  115. term1 %= mod_value
  116. if term2 >= mod_value or term2 < 0:
  117. term2 %= mod_value
  118. modulus_b = long_to_bytes(mod_value)
  119. numbers_len = len(modulus_b)
  120. term1_b = long_to_bytes(term1, numbers_len)
  121. term2_b = long_to_bytes(term2, numbers_len)
  122. out = create_string_buffer(numbers_len)
  123. error = _raw_montgomery.monty_multiply(
  124. out,
  125. term1_b,
  126. term2_b,
  127. modulus_b,
  128. c_size_t(numbers_len)
  129. )
  130. if error:
  131. raise ValueError("monty_multiply failed with error: %d" % error)
  132. return get_raw_buffer(out)