File indexing completed on 2024-05-12 04:45:13

0001 /*
0002 Copyright (C) 1999-2007 The Botan Project. All rights reserved.
0003 
0004 Redistribution and use in source and binary forms, for any use, with or without
0005 modification, is permitted provided that the following conditions are met:
0006 
0007 1. Redistributions of source code must retain the above copyright notice, this
0008 list of conditions, and the following disclaimer.
0009 
0010 2. Redistributions in binary form must reproduce the above copyright notice,
0011 this list of conditions, and the following disclaimer in the documentation
0012 and/or other materials provided with the distribution.
0013 
0014 THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) "AS IS" AND ANY EXPRESS OR IMPLIED
0015 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
0016 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
0017 
0018 IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTOR(S) BE LIABLE FOR ANY DIRECT,
0019 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
0020 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0021 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
0022 LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
0023 OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
0024 ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
0025 */
0026 // LICENSEHEADER_END
0027 namespace QCA { // WRAPNS_LINE
0028 /*************************************************
0029  * BigInt Base Source File                        *
0030  * (C) 1999-2007 The Botan Project                *
0031  *************************************************/
0032 
0033 } // WRAPNS_LINE
0034 #include <botan/bigint.h>
0035 namespace QCA { // WRAPNS_LINE
0036 } // WRAPNS_LINE
0037 #include <botan/mp_core.h>
0038 namespace QCA { // WRAPNS_LINE
0039 } // WRAPNS_LINE
0040 #include <botan/bit_ops.h>
0041 namespace QCA { // WRAPNS_LINE
0042 } // WRAPNS_LINE
0043 #include <botan/parsing.h>
0044 namespace QCA { // WRAPNS_LINE
0045 } // WRAPNS_LINE
0046 #include <botan/util.h>
0047 namespace QCA { // WRAPNS_LINE
0048 
0049 namespace Botan {
0050 
0051 /*************************************************
0052  * Construct a BigInt from a regular number       *
0053  *************************************************/
0054 BigInt::BigInt(u64bit n)
0055 {
0056     set_sign(Positive);
0057 
0058     if (n == 0)
0059         return;
0060 
0061     const u32bit limbs_needed = sizeof(u64bit) / sizeof(word);
0062 
0063     reg.create(4 * limbs_needed);
0064     for (u32bit j = 0; j != limbs_needed; ++j)
0065         reg[j] = (word)((n >> (j * MP_WORD_BITS)) & MP_WORD_MASK);
0066 }
0067 
0068 /*************************************************
0069  * Construct a BigInt of the specified size       *
0070  *************************************************/
0071 BigInt::BigInt(Sign s, u32bit size)
0072 {
0073     reg.create(round_up(size, 8));
0074     signedness = s;
0075 }
0076 
0077 /*************************************************
0078  * Construct a BigInt from a "raw" BigInt         *
0079  *************************************************/
0080 BigInt::BigInt(const BigInt &b)
0081 {
0082     const u32bit b_words = b.sig_words();
0083 
0084     if (b_words) {
0085         reg.create(round_up(b_words, 8));
0086         reg.copy(b.data(), b_words);
0087         set_sign(b.sign());
0088     } else {
0089         reg.create(2);
0090         set_sign(Positive);
0091     }
0092 }
0093 
0094 BigInt &BigInt::operator=(const BigInt &) = default;
0095 
0096 /*************************************************
0097  * Construct a BigInt from a string               *
0098  *************************************************/
0099 BigInt::BigInt(const std::string &str)
0100 {
0101     Base   base     = Decimal;
0102     u32bit markers  = 0;
0103     bool   negative = false;
0104     if (str.length() > 0 && str[0] == '-') {
0105         markers += 1;
0106         negative = true;
0107     }
0108 
0109     if (str.length() > markers + 2 && str[markers] == '0' && str[markers + 1] == 'x') {
0110         markers += 2;
0111         base = Hexadecimal;
0112     } else if (str.length() > markers + 1 && str[markers] == '0') {
0113         markers += 1;
0114         base = Octal;
0115     }
0116 
0117     *this = decode((const byte *)str.data() + markers, str.length() - markers, base);
0118 
0119     if (negative)
0120         set_sign(Negative);
0121     else
0122         set_sign(Positive);
0123 }
0124 
0125 /*************************************************
0126  * Construct a BigInt from an encoded BigInt      *
0127  *************************************************/
0128 BigInt::BigInt(const byte input[], u32bit length, Base base)
0129 {
0130     set_sign(Positive);
0131     *this = decode(input, length, base);
0132 }
0133 
0134 /*************************************************
0135  * Swap this BigInt with another                  *
0136  *************************************************/
0137 void BigInt::swap(BigInt &other)
0138 {
0139     std::swap(reg, other.reg);
0140     std::swap(signedness, other.signedness);
0141 }
0142 
0143 /*************************************************
0144  * Grow the internal storage                      *
0145  *************************************************/
0146 void BigInt::grow_reg(u32bit n) const
0147 {
0148     reg.grow_to(round_up(size() + n, 8));
0149 }
0150 
0151 /*************************************************
0152  * Grow the internal storage                      *
0153  *************************************************/
0154 void BigInt::grow_to(u32bit n) const
0155 {
0156     if (n > size())
0157         reg.grow_to(round_up(n, 8));
0158 }
0159 
0160 /*************************************************
0161  * Comparison Function                            *
0162  *************************************************/
0163 s32bit BigInt::cmp(const BigInt &n, bool check_signs) const
0164 {
0165     if (check_signs) {
0166         if (n.is_positive() && this->is_negative())
0167             return -1;
0168         if (n.is_negative() && this->is_positive())
0169             return 1;
0170         if (n.is_negative() && this->is_negative())
0171             return (-bigint_cmp(data(), sig_words(), n.data(), n.sig_words()));
0172     }
0173     return bigint_cmp(data(), sig_words(), n.data(), n.sig_words());
0174 }
0175 
0176 /*************************************************
0177  * Convert this number to a u32bit, if possible   *
0178  *************************************************/
0179 u32bit BigInt::to_u32bit() const
0180 {
0181     if (is_negative())
0182         throw Encoding_Error("BigInt::to_u32bit: Number is negative");
0183     if (bits() >= 32)
0184         throw Encoding_Error("BigInt::to_u32bit: Number is too big to convert");
0185 
0186     u32bit out = 0;
0187     for (u32bit j = 0; j != 4; ++j)
0188         out = (out << 8) | byte_at(3 - j);
0189     return out;
0190 }
0191 
0192 /*************************************************
0193  * Return byte n of this number                   *
0194  *************************************************/
0195 byte BigInt::byte_at(u32bit n) const
0196 {
0197     const u32bit WORD_BYTES = sizeof(word);
0198     u32bit       word_num = n / WORD_BYTES, byte_num = n % WORD_BYTES;
0199     if (word_num >= size())
0200         return 0;
0201     else
0202         return get_byte(WORD_BYTES - byte_num - 1, reg[word_num]);
0203 }
0204 
0205 /*************************************************
0206  * Return bit n of this number                    *
0207  *************************************************/
0208 bool BigInt::get_bit(u32bit n) const
0209 {
0210     return ((word_at(n / MP_WORD_BITS) >> (n % MP_WORD_BITS)) & 1);
0211 }
0212 
0213 /*************************************************
0214  * Return bits {offset...offset+length}           *
0215  *************************************************/
0216 u32bit BigInt::get_substring(u32bit offset, u32bit length) const
0217 {
0218     if (length > 32)
0219         throw Invalid_Argument("BigInt::get_substring: Substring size too big");
0220 
0221     u64bit piece = 0;
0222     for (u32bit j = 0; j != 8; ++j)
0223         piece = (piece << 8) | byte_at((offset / 8) + (7 - j));
0224 
0225     u64bit mask  = (1 << length) - 1;
0226     u32bit shift = (offset % 8);
0227 
0228     return static_cast<u32bit>((piece >> shift) & mask);
0229 }
0230 
0231 /*************************************************
0232  * Set bit number n                               *
0233  *************************************************/
0234 void BigInt::set_bit(u32bit n)
0235 {
0236     const u32bit which = n / MP_WORD_BITS;
0237     const word   mask  = (word)1 << (n % MP_WORD_BITS);
0238     if (which >= size())
0239         grow_to(which + 1);
0240     reg[which] |= mask;
0241 }
0242 
0243 /*************************************************
0244  * Clear bit number n                             *
0245  *************************************************/
0246 void BigInt::clear_bit(u32bit n)
0247 {
0248     const u32bit which = n / MP_WORD_BITS;
0249     const word   mask  = (word)1 << (n % MP_WORD_BITS);
0250     if (which < size())
0251         reg[which] &= ~mask;
0252 }
0253 
0254 /*************************************************
0255  * Clear all but the lowest n bits                *
0256  *************************************************/
0257 void BigInt::mask_bits(u32bit n)
0258 {
0259     if (n == 0) {
0260         clear();
0261         return;
0262     }
0263     if (n >= bits())
0264         return;
0265 
0266     const u32bit top_word = n / MP_WORD_BITS;
0267     const word   mask     = ((word)1 << (n % MP_WORD_BITS)) - 1;
0268 
0269     if (top_word < size())
0270         for (u32bit j = top_word + 1; j != size(); ++j)
0271             reg[j] = 0;
0272 
0273     reg[top_word] &= mask;
0274 }
0275 
0276 /*************************************************
0277  * Count the significant words                    *
0278  *************************************************/
0279 u32bit BigInt::sig_words() const
0280 {
0281     const word *x       = data();
0282     u32bit      top_set = size();
0283 
0284     while (top_set >= 4) {
0285         word sum = x[top_set - 1] | x[top_set - 2] | x[top_set - 3] | x[top_set - 4];
0286         if (sum)
0287             break;
0288         else
0289             top_set -= 4;
0290     }
0291     while (top_set && (x[top_set - 1] == 0))
0292         top_set--;
0293     return top_set;
0294 }
0295 
0296 /*************************************************
0297  * Count how many bytes are being used            *
0298  *************************************************/
0299 u32bit BigInt::bytes() const
0300 {
0301     return (bits() + 7) / 8;
0302 }
0303 
0304 /*************************************************
0305  * Count how many bits are being used             *
0306  *************************************************/
0307 u32bit BigInt::bits() const
0308 {
0309     if (sig_words() == 0)
0310         return 0;
0311 
0312     u32bit full_words = sig_words() - 1, top_bits = MP_WORD_BITS;
0313     word   top_word = word_at(full_words), mask = MP_WORD_TOP_BIT;
0314 
0315     while (top_bits && ((top_word & mask) == 0)) {
0316         mask >>= 1;
0317         top_bits--;
0318     }
0319 
0320     return (full_words * MP_WORD_BITS + top_bits);
0321 }
0322 
0323 /*************************************************
0324  * Calcluate the size in a certain base           *
0325  *************************************************/
0326 u32bit BigInt::encoded_size(Base base) const
0327 {
0328     static const double LOG_2_BASE_10 = 0.30102999566;
0329 
0330     if (base == Binary)
0331         return bytes();
0332     else if (base == Hexadecimal)
0333         return 2 * bytes();
0334     else if (base == Octal)
0335         return ((bits() + 2) / 3);
0336     else if (base == Decimal)
0337         return (u32bit)((bits() * LOG_2_BASE_10) + 1);
0338     else
0339         throw Invalid_Argument("Unknown base for BigInt encoding");
0340 }
0341 
0342 /*************************************************
0343  * Return true if this number is zero             *
0344  *************************************************/
0345 bool BigInt::is_zero() const
0346 {
0347     for (u32bit j = 0; j != size(); ++j)
0348         if (reg[j])
0349             return false;
0350     return true;
0351 }
0352 
0353 /*************************************************
0354  * Set the sign                                   *
0355  *************************************************/
0356 void BigInt::set_sign(Sign s)
0357 {
0358     if (is_zero())
0359         signedness = Positive;
0360     else
0361         signedness = s;
0362 }
0363 
0364 /*************************************************
0365  * Reverse the value of the sign flag             *
0366  *************************************************/
0367 void BigInt::flip_sign()
0368 {
0369     set_sign(reverse_sign());
0370 }
0371 
0372 /*************************************************
0373  * Return the opposite value of the current sign  *
0374  *************************************************/
0375 BigInt::Sign BigInt::reverse_sign() const
0376 {
0377     if (sign() == Positive)
0378         return Negative;
0379     return Positive;
0380 }
0381 
0382 /*************************************************
0383  * Return the negation of this number             *
0384  *************************************************/
0385 BigInt BigInt::operator-() const
0386 {
0387     BigInt x = (*this);
0388     x.flip_sign();
0389     return x;
0390 }
0391 
0392 /*************************************************
0393  * Return the absolute value of this number       *
0394  *************************************************/
0395 BigInt BigInt::abs() const
0396 {
0397     BigInt x = (*this);
0398     x.set_sign(Positive);
0399     return x;
0400 }
0401 
0402 /*************************************************
0403  * Encode this number into bytes                  *
0404  *************************************************/
0405 void BigInt::binary_encode(byte output[]) const
0406 {
0407     const u32bit sig_bytes = bytes();
0408     for (u32bit j = 0; j != sig_bytes; ++j)
0409         output[sig_bytes - j - 1] = byte_at(j);
0410 }
0411 
0412 /*************************************************
0413  * Set this number to the value in buf            *
0414  *************************************************/
0415 void BigInt::binary_decode(const byte buf[], u32bit length)
0416 {
0417     const u32bit WORD_BYTES = sizeof(word);
0418     reg.create(round_up((length / WORD_BYTES) + 1, 8));
0419 
0420     for (u32bit j = 0; j != length / WORD_BYTES; ++j) {
0421         u32bit top = length - WORD_BYTES * j;
0422         for (u32bit k = WORD_BYTES; k > 0; --k)
0423             reg[j] = (reg[j] << 8) | buf[top - k];
0424     }
0425     for (u32bit j = 0; j != length % WORD_BYTES; ++j)
0426         reg[length / WORD_BYTES] = (reg[length / WORD_BYTES] << 8) | buf[j];
0427 }
0428 
0429 }
0430 } // WRAPNS_LINE