_int.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # coding: utf-8
  2. """
  3. Function for calculating the modular inverse. Exports the following items:
  4. - inverse_mod()
  5. Source code is derived from
  6. http://webpages.charter.net/curryfans/peter/downloads.html, but has been heavily
  7. modified to fit into this projects lint settings. The original project license
  8. is listed below:
  9. Copyright (c) 2014 Peter Pearson
  10. Permission is hereby granted, free of charge, to any person obtaining a copy
  11. of this software and associated documentation files (the "Software"), to deal
  12. in the Software without restriction, including without limitation the rights
  13. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  14. copies of the Software, and to permit persons to whom the Software is
  15. furnished to do so, subject to the following conditions:
  16. The above copyright notice and this permission notice shall be included in
  17. all copies or substantial portions of the Software.
  18. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. THE SOFTWARE.
  25. """
  26. from __future__ import unicode_literals, division, absolute_import, print_function
  27. import math
  28. import platform
  29. from .util import int_to_bytes, int_from_bytes
  30. # First try to use ctypes with OpenSSL for better performance
  31. try:
  32. from ._ffi import (
  33. buffer_from_bytes,
  34. bytes_from_buffer,
  35. FFIEngineError,
  36. LibraryNotFoundError,
  37. null,
  38. )
  39. # Some versions of PyPy have segfault issues, so we just punt on PyPy
  40. if platform.python_implementation() == 'PyPy':
  41. raise EnvironmentError()
  42. try:
  43. from ._perf._big_num_ctypes import libcrypto
  44. def inverse_mod(a, p):
  45. """
  46. Compute the modular inverse of a (mod p)
  47. :param a:
  48. An integer
  49. :param p:
  50. An integer
  51. :return:
  52. An integer
  53. """
  54. ctx = libcrypto.BN_CTX_new()
  55. a_bytes = int_to_bytes(abs(a))
  56. p_bytes = int_to_bytes(abs(p))
  57. a_buf = buffer_from_bytes(a_bytes)
  58. a_bn = libcrypto.BN_bin2bn(a_buf, len(a_bytes), null())
  59. if a < 0:
  60. libcrypto.BN_set_negative(a_bn, 1)
  61. p_buf = buffer_from_bytes(p_bytes)
  62. p_bn = libcrypto.BN_bin2bn(p_buf, len(p_bytes), null())
  63. if p < 0:
  64. libcrypto.BN_set_negative(p_bn, 1)
  65. r_bn = libcrypto.BN_mod_inverse(null(), a_bn, p_bn, ctx)
  66. r_len_bits = libcrypto.BN_num_bits(r_bn)
  67. r_len = int(math.ceil(r_len_bits / 8))
  68. r_buf = buffer_from_bytes(r_len)
  69. libcrypto.BN_bn2bin(r_bn, r_buf)
  70. r_bytes = bytes_from_buffer(r_buf, r_len)
  71. result = int_from_bytes(r_bytes)
  72. libcrypto.BN_free(a_bn)
  73. libcrypto.BN_free(p_bn)
  74. libcrypto.BN_free(r_bn)
  75. libcrypto.BN_CTX_free(ctx)
  76. return result
  77. except (LibraryNotFoundError, FFIEngineError):
  78. raise EnvironmentError()
  79. # If there was an issue using ctypes or OpenSSL, we fall back to pure python
  80. except (EnvironmentError, ImportError):
  81. def inverse_mod(a, p):
  82. """
  83. Compute the modular inverse of a (mod p)
  84. :param a:
  85. An integer
  86. :param p:
  87. An integer
  88. :return:
  89. An integer
  90. """
  91. if a < 0 or p <= a:
  92. a = a % p
  93. # From Ferguson and Schneier, roughly:
  94. c, d = a, p
  95. uc, vc, ud, vd = 1, 0, 0, 1
  96. while c != 0:
  97. q, c, d = divmod(d, c) + (c,)
  98. uc, vc, ud, vd = ud - q * uc, vd - q * vc, uc, vc
  99. # At this point, d is the GCD, and ud*a+vd*p = d.
  100. # If d == 1, this means that ud is a inverse.
  101. assert d == 1
  102. if ud > 0:
  103. return ud
  104. else:
  105. return ud + p
  106. def fill_width(bytes_, width):
  107. """
  108. Ensure a byte string representing a positive integer is a specific width
  109. (in bytes)
  110. :param bytes_:
  111. The integer byte string
  112. :param width:
  113. The desired width as an integer
  114. :return:
  115. A byte string of the width specified
  116. """
  117. while len(bytes_) < width:
  118. bytes_ = b'\x00' + bytes_
  119. return bytes_