_IntegerCustom.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 Cryptodome.Util.number import long_to_bytes, bytes_to_long
  32. from Cryptodome.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 Cryptodome.Random.random import getrandbits
  37. c_defs = """
  38. int monty_pow(const uint8_t *base,
  39. const uint8_t *exp,
  40. const uint8_t *modulus,
  41. uint8_t *out,
  42. size_t len,
  43. uint64_t seed);
  44. """
  45. _raw_montgomery = load_pycryptodome_raw_lib("Cryptodome.Math._modexp", c_defs)
  46. implementation = {"library": "custom", "api": backend}
  47. class IntegerCustom(IntegerNative):
  48. @staticmethod
  49. def from_bytes(byte_string):
  50. return IntegerCustom(bytes_to_long(byte_string))
  51. def inplace_pow(self, exponent, modulus=None):
  52. exp_value = int(exponent)
  53. if exp_value < 0:
  54. raise ValueError("Exponent must not be negative")
  55. # No modular reduction
  56. if modulus is None:
  57. self._value = pow(self._value, exp_value)
  58. return self
  59. # With modular reduction
  60. mod_value = int(modulus)
  61. if mod_value < 0:
  62. raise ValueError("Modulus must be positive")
  63. if mod_value == 0:
  64. raise ZeroDivisionError("Modulus cannot be zero")
  65. # C extension only works with odd moduli
  66. if (mod_value & 1) == 0:
  67. self._value = pow(self._value, exp_value, mod_value)
  68. return self
  69. # C extension only works with bases smaller than modulus
  70. if self._value >= mod_value:
  71. self._value %= mod_value
  72. max_len = len(long_to_bytes(max(self._value, exp_value, mod_value)))
  73. base_b = long_to_bytes(self._value, max_len)
  74. exp_b = long_to_bytes(exp_value, max_len)
  75. modulus_b = long_to_bytes(mod_value, max_len)
  76. out = create_string_buffer(max_len)
  77. error = _raw_montgomery.monty_pow(
  78. out,
  79. base_b,
  80. exp_b,
  81. modulus_b,
  82. c_size_t(max_len),
  83. c_ulonglong(getrandbits(64))
  84. )
  85. if error:
  86. raise ValueError("monty_pow failed with error: %d" % error)
  87. result = bytes_to_long(get_raw_buffer(out))
  88. self._value = result
  89. return self