UnsignedBigInteger.cpp 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. dbg() << "WARNING: bigint subtraction creates a negative number!";
  71. return UnsignedBigInteger::create_invalid();
  72. }
  73. u8 borrow = 0;
  74. for (size_t i = 0; i < other.length(); ++i) {
  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. UnsignedBigInteger UnsignedBigInteger::shift_left(size_t num_bits) const
  117. {
  118. // We can only do shift operations on individual words
  119. // where the shift amount is <= size of word (32).
  120. // But we do know how to shift by a multiple of word size (e.g 64=32*2)
  121. // So we first shift the result by how many whole words fit in 'num_bits'
  122. UnsignedBigInteger temp_result = shift_left_by_n_words(num_bits / UnsignedBigInteger::BITS_IN_WORD);
  123. // And now we shift by the leftover amount of bits
  124. num_bits %= UnsignedBigInteger::BITS_IN_WORD;
  125. UnsignedBigInteger result(temp_result);
  126. for (size_t i = 0; i < temp_result.length(); ++i) {
  127. u32 current_word_of_temp_result = temp_result.shift_left_get_one_word(num_bits, i);
  128. result.m_words[i] = current_word_of_temp_result;
  129. }
  130. // Shifting the last word can produce a carry
  131. u32 carry_word = temp_result.shift_left_get_one_word(num_bits, temp_result.length());
  132. if (carry_word != 0) {
  133. result = result.add(UnsignedBigInteger(carry_word).shift_left_by_n_words(temp_result.length()));
  134. }
  135. return result;
  136. }
  137. UnsignedBigInteger UnsignedBigInteger::shift_left_by_n_words(const size_t number_of_words) const
  138. {
  139. // shifting left by N words means just inserting N zeroes to the beginning of the words vector
  140. UnsignedBigInteger result;
  141. for (size_t i = 0; i < number_of_words; ++i) {
  142. result.m_words.append(0);
  143. }
  144. for (size_t i = 0; i < length(); ++i) {
  145. result.m_words.append(m_words[i]);
  146. }
  147. return result;
  148. }
  149. /**
  150. * Returns the word at a requested index in the result of a shift operation
  151. */
  152. u32 UnsignedBigInteger::shift_left_get_one_word(const size_t num_bits, const size_t result_word_index) const
  153. {
  154. // "<= length()" (rather than length() - 1) is intentional,
  155. // The result inedx of length() is used when calculating the carry word
  156. ASSERT(result_word_index <= length());
  157. ASSERT(num_bits <= UnsignedBigInteger::BITS_IN_WORD);
  158. u32 result = 0;
  159. // we need to check for "num_bits != 0" since shifting right by 32 is apparently undefined behaviour!
  160. if (result_word_index > 0 && num_bits != 0) {
  161. result += m_words[result_word_index - 1] >> (UnsignedBigInteger::BITS_IN_WORD - num_bits);
  162. }
  163. if (result_word_index < length() && num_bits < 32) {
  164. result += m_words[result_word_index] << num_bits;
  165. }
  166. return result;
  167. }
  168. bool UnsignedBigInteger::operator==(const UnsignedBigInteger& other) const
  169. {
  170. if (trimmed_length() != other.trimmed_length()) {
  171. return false;
  172. }
  173. if (is_invalid() != other.is_invalid()) {
  174. return false;
  175. }
  176. for (size_t i = 0; i < trimmed_length(); ++i) {
  177. if (m_words[i] != other.words()[i])
  178. return false;
  179. }
  180. return true;
  181. }
  182. bool UnsignedBigInteger::operator<(const UnsignedBigInteger& other) const
  183. {
  184. if (trimmed_length() < other.trimmed_length()) {
  185. return true;
  186. }
  187. if (trimmed_length() > other.trimmed_length()) {
  188. return false;
  189. }
  190. size_t length = trimmed_length();
  191. if (length == 0) {
  192. return false;
  193. }
  194. return m_words[length - 1] < other.m_words[length - 1];
  195. }
  196. size_t UnsignedBigInteger::trimmed_length() const
  197. {
  198. size_t num_leading_zeroes = 0;
  199. for (int i = length() - 1; i >= 0; --i, ++num_leading_zeroes) {
  200. if (m_words[i] != 0)
  201. break;
  202. }
  203. return length() - num_leading_zeroes;
  204. }
  205. UnsignedBigInteger UnsignedBigInteger::create_invalid()
  206. {
  207. UnsignedBigInteger invalid(0);
  208. invalid.invalidate();
  209. return invalid;
  210. }
  211. }