UnsignedBigInteger.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. /*
  2. * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "UnsignedBigInteger.h"
  27. namespace Crypto {
  28. /**
  29. * Complexity: O(N) where N is the number of words in the larger number
  30. */
  31. UnsignedBigInteger UnsignedBigInteger::add(const UnsignedBigInteger& other) const
  32. {
  33. const UnsignedBigInteger* const longer = (length() > other.length()) ? this : &other;
  34. const UnsignedBigInteger* const shorter = (longer == &other) ? this : &other;
  35. UnsignedBigInteger result;
  36. u8 carry = 0;
  37. for (size_t i = 0; i < shorter->length(); ++i) {
  38. u32 word_addition_result = shorter->m_words[i] + longer->m_words[i];
  39. u8 carry_out = 0;
  40. // if there was a carry, the result will be smaller than any of the operands
  41. if (word_addition_result + carry < shorter->m_words[i]) {
  42. carry_out = 1;
  43. }
  44. if (carry) {
  45. word_addition_result++;
  46. }
  47. carry = carry_out;
  48. result.m_words.append(word_addition_result);
  49. }
  50. for (size_t i = shorter->length(); i < longer->length(); ++i) {
  51. u32 word_addition_result = longer->m_words[i] + carry;
  52. carry = 0;
  53. if (word_addition_result < longer->m_words[i]) {
  54. carry = 1;
  55. }
  56. result.m_words.append(word_addition_result);
  57. }
  58. if (carry) {
  59. result.m_words.append(carry);
  60. }
  61. return result;
  62. }
  63. /**
  64. * Complexity: O(N) where N is the number of words in the larger number
  65. */
  66. UnsignedBigInteger UnsignedBigInteger::sub(const UnsignedBigInteger& other) const
  67. {
  68. UnsignedBigInteger result;
  69. if (*this < other) {
  70. return UnsignedBigInteger::create_invalid();
  71. }
  72. u8 borrow = 0;
  73. for (size_t i = 0; i < other.length(); ++i) {
  74. // This assertion should not fail, because we verified that *this>other at the beginning of the function
  75. ASSERT(!(borrow == 1 && m_words[i] == 0));
  76. if (m_words[i] - borrow < other.m_words[i]) {
  77. u64 after_borrow = static_cast<u64>(m_words[i] - borrow) + (UINT32_MAX + 1);
  78. result.m_words.append(static_cast<u32>(after_borrow - static_cast<u64>(other.m_words[i])));
  79. borrow = 1;
  80. } else {
  81. result.m_words.append(m_words[i] - borrow - other.m_words[i]);
  82. borrow = 0;
  83. }
  84. }
  85. for (size_t i = other.length(); i < length(); ++i) {
  86. ASSERT(!(borrow == 1 && m_words[i] == 0));
  87. result.m_words.append(m_words[i] - borrow);
  88. borrow = 0;
  89. }
  90. return result;
  91. }
  92. /**
  93. * Complexity: O(N^2) where N is the number of words in the larger number
  94. * Multiplcation method:
  95. * An integer is equal to the sum of the powers of two
  96. * according to the indexes of its 'on' bits.
  97. * So to multiple x*y, we go over each '1' bit in x (say the i'th bit),
  98. * and add y<<i to the result.
  99. */
  100. UnsignedBigInteger UnsignedBigInteger::multiply(const UnsignedBigInteger& other) const
  101. {
  102. UnsignedBigInteger result;
  103. // iterate all bits
  104. for (size_t word_index = 0; word_index < length(); ++word_index) {
  105. for (size_t bit_index = 0; bit_index < UnsignedBigInteger::BITS_IN_WORD; ++bit_index) {
  106. // If the bit is off - skip over it
  107. if (!(m_words[word_index] & (1 << bit_index)))
  108. continue;
  109. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  110. auto shift_result = other.shift_left(shift_amount);
  111. result = result.add(shift_result);
  112. }
  113. }
  114. return result;
  115. }
  116. /**
  117. * Complexity: O(N^2) where N is the number of words in the larger number
  118. * Division method:
  119. * We loop over the bits of the divisor, attempting to subtract divisor<<i from the dividend.
  120. * If the result is non-negative, it means that divisor*2^i "fits" in the dividend,
  121. * so we set the ith bit in the quotient and reduce divisor<<i from the dividend.
  122. * When we're done, what's left from the dividend is the remainder.
  123. */
  124. UnsignedDivisionResult UnsignedBigInteger::divide(const UnsignedBigInteger& divisor) const
  125. {
  126. UnsignedBigInteger leftover_dividend(*this);
  127. UnsignedBigInteger quotient;
  128. // iterate all bits
  129. for (int word_index = trimmed_length() - 1; word_index >= 0; --word_index) {
  130. for (int bit_index = UnsignedBigInteger::BITS_IN_WORD - 1; bit_index >= 0; --bit_index) {
  131. const size_t shift_amount = word_index * UnsignedBigInteger::BITS_IN_WORD + bit_index;
  132. UnsignedBigInteger divisor_shifted = divisor.shift_left(shift_amount);
  133. UnsignedBigInteger temp_subtraction_result = leftover_dividend.sub(divisor_shifted);
  134. if (!temp_subtraction_result.is_invalid()) {
  135. leftover_dividend = temp_subtraction_result;
  136. quotient.set_bit_inplace(shift_amount);
  137. }
  138. }
  139. }
  140. return UnsignedDivisionResult { quotient, leftover_dividend };
  141. }
  142. void UnsignedBigInteger::set_bit_inplace(size_t bit_index)
  143. {
  144. const size_t word_index = bit_index / UnsignedBigInteger::BITS_IN_WORD;
  145. const size_t inner_word_index = bit_index % UnsignedBigInteger::BITS_IN_WORD;
  146. for (size_t i = length(); i <= word_index; ++i) {
  147. m_words.append(0);
  148. }
  149. m_words[word_index] |= (1 << inner_word_index);
  150. }
  151. UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  152. {
  153. // We can only do shift operations on individual words
  154. // where the shift amount is <= size of word (32).
  155. // But we do know how to shift by a multiple of word size (e.g 64=32*2)
  156. // So we first shift the result by how many whole words fit in 'num_bits'
  157. UnsignedBigInteger temp_result = shift_left_by_n_words(num_bits / UnsignedBigInteger::BITS_IN_WORD);
  158. // And now we shift by the leftover amount of bits
  159. num_bits %= UnsignedBigInteger::BITS_IN_WORD;
  160. UnsignedBigInteger result(temp_result);
  161. for (size_t i = 0; i < temp_result.length(); ++i) {
  162. u32 current_word_of_temp_result = temp_result.shift_left_get_one_word(num_bits, i);
  163. result.m_words[i] = current_word_of_temp_result;
  164. }
  165. // Shifting the last word can produce a carry
  166. u32 carry_word = temp_result.shift_left_get_one_word(num_bits, temp_result.length());
  167. if (carry_word != 0) {
  168. result = result.add(UnsignedBigInteger(carry_word).shift_left_by_n_words(temp_result.length()));
  169. }
  170. return result;
  171. }
  172. UnsignedBigInteger UnsignedBigInteger::shift_left_by_n_words(const size_t number_of_words) const
  173. {
  174. // shifting left by N words means just inserting N zeroes to the beginning of the words vector
  175. UnsignedBigInteger result;
  176. for (size_t i = 0; i < number_of_words; ++i) {
  177. result.m_words.append(0);
  178. }
  179. for (size_t i = 0; i < length(); ++i) {
  180. result.m_words.append(m_words[i]);
  181. }
  182. return result;
  183. }
  184. /**
  185. * Returns the word at a requested index in the result of a shift operation
  186. */
  187. u32 UnsignedBigInteger::shift_left_get_one_word(const size_t num_bits, const size_t result_word_index) const
  188. {
  189. // "<= length()" (rather than length() - 1) is intentional,
  190. // The result inedx of length() is used when calculating the carry word
  191. ASSERT(result_word_index <= length());
  192. ASSERT(num_bits <= UnsignedBigInteger::BITS_IN_WORD);
  193. u32 result = 0;
  194. // we need to check for "num_bits != 0" since shifting right by 32 is apparently undefined behaviour!
  195. if (result_word_index > 0 && num_bits != 0) {
  196. result += m_words[result_word_index - 1] >> (UnsignedBigInteger::BITS_IN_WORD - num_bits);
  197. }
  198. if (result_word_index < length() && num_bits < 32) {
  199. result += m_words[result_word_index] << num_bits;
  200. }
  201. return result;
  202. }
  203. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  204. {
  205. if (trimmed_length() != other.trimmed_length()) {
  206. return false;
  207. }
  208. if (is_invalid() != other.is_invalid()) {
  209. return false;
  210. }
  211. for (size_t i = 0; i < trimmed_length(); ++i) {
  212. if (m_words[i] != other.words()[i])
  213. return false;
  214. }
  215. return true;
  216. }
  217. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  218. {
  219. if (trimmed_length() < other.trimmed_length()) {
  220. return true;
  221. }
  222. if (trimmed_length() > other.trimmed_length()) {
  223. return false;
  224. }
  225. int length = trimmed_length();
  226. if (length == 0) {
  227. return false;
  228. }
  229. for (int i = length - 1; i >= 0; --i) {
  230. if (m_words[i] == other.m_words[i])
  231. continue;
  232. return m_words[i] < other.m_words[i];
  233. }
  234. return false;
  235. }
  236. size_t UnsignedBigInteger::trimmed_length() const
  237. {
  238. size_t num_leading_zeroes = 0;
  239. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  240. if (m_words[i] != 0)
  241. break;
  242. }
  243. return length() - num_leading_zeroes;
  244. }
  245. UnsignedBigInteger UnsignedBigInteger::create_invalid()
  246. {
  247. UnsignedBigInteger invalid(0);
  248. invalid.invalidate();
  249. return invalid;
  250. }
  251. }