1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904
|
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
#include "gsLargeInt.h"
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Many parameters are gsi_u32* instead of gsLargeInt_t*.
// This was done to allow easy conversion of databuffer to gsLargeInt_t
// Raw buffer destinations must have enough space to store the result
static gsi_bool gsiLargeIntPrint(FILE* logFile, const l_word *data, l_word length);
static gsi_bool gsiLargeIntResize(gsLargeInt_t *lint, l_word length);
static gsi_bool gsiLargeIntStripLeadingZeroes(gsLargeInt_t* lint);
static gsi_bool gsiLargeIntSizePower2(const gsLargeInt_t *src1, const gsLargeInt_t *src2, l_word *lenout);
static gsi_i32 gsiLargeIntCompare(const l_word *data1, l_word len1, const l_word *data2, l_word len2);
static gsi_bool gsiLargeIntKMult(const l_word *data1, const l_word *data2, l_word length, l_word *dest, l_word *lenout, l_word maxlen);
static gsi_bool gsiLargeIntMult (const l_word *data1, l_word length1, const l_word *data2, l_word length2, l_word *dest, l_word *lenout, l_word maxlen);
static gsi_bool gsiLargeIntDiv (const l_word *src1, l_word length1, const gsLargeInt_t *divisor, gsLargeInt_t *dest, gsLargeInt_t *remainder);
// Dest may be data1 or data2 to support in-place arithmetic
static gsi_bool gsiLargeIntAdd (const l_word *data1, l_word length1, const l_word *data2, l_word length2, l_word *dest, l_word *lenout, l_word maxlen);
static gsi_bool gsiLargeIntSub (const l_word *amount, l_word length1, const l_word *from, l_word length2, l_word *dest, l_word *lenout);
// Special division, removes divisor directly from src1, leaving remainder
static gsi_bool gsiLargeIntSubDivide(l_word *src1, l_word length, const l_word *divisor, l_word dlen, gsi_u32 highbit, l_word *quotient);
// Montgomery utilities
//gsi_bool gsiLargeIntSquareM(const gsLargeInt_t *src, const gsLargeInt_t *mod, gsi_u32 modPrime, gsi_u32 R, gsLargeInt_t *dest);
//gsi_bool gsiLargeIntMultM(gsLargeInt_t *src1, gsLargeInt_t *src2, const gsLargeInt_t *mod, gsi_u32 modPrime, gsLargeInt_t *dest);
gsi_bool gsiLargeIntMultM(gsLargeInt_t *src1, gsLargeInt_t *src2, const gsLargeInt_t *mod, gsi_u32 modPrime, gsLargeInt_t *dest);
gsi_bool gsiLargeIntInverseMod(const gsLargeInt_t *mod, l_word *modPrimeOut);
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// execution timing/profiling
#define GS_LINT_TIMING
#ifdef GS_LINT_TIMING
typedef enum
{
GSLintTimerMult, // "regular" multiplication
GSLintTimerMultM, // montgomery
GSLintTimerKMult, // karatsuba
GSLintTimerAdd,
GSLintTimerSub, // subtract
GSLintTimerDiv,
GSLintTimerSubDivide, // atomic divide
GSLintTimerSquareMod,
GSLintTimerPowerMod, // modular exponentiation
GSLintTimerCount
} GSLintTimerID;
typedef struct GSLintTimer
{
gsi_time started;
gsi_time total;
gsi_u32 entries;
gsi_u32 running; // already entered?
} GSLintTimer;
static struct GSLintTimer gTimers[GSLintTimerCount];
static void gsiLargeIntTimerEnter(GSLintTimerID id)
{
if (gTimers[id].running==0)
{
gTimers[id].entries++;
gTimers[id].started = current_time_hires();
gTimers[id].running = 1;
}
}
static void gsiLargeIntTimerExit(GSLintTimerID id)
{
if (gTimers[id].running==1)
{
gTimers[id].total += current_time_hires()-gTimers[id].started;
gTimers[id].running = 0;
}
}
#define GSLINT_ENTERTIMER(id) gsiLargeIntTimerEnter(id)
#define GSLINT_EXITTIMER(id) gsiLargeIntTimerExit(id)
#else
#define GSLINT_ENTERTIMER(id)
#define GSLINT_EXITTIMER(id)
#endif
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
gsi_bool gsLargeIntSetValue(gsLargeInt_t *lint, l_word value)
{
lint->mLength = 1;
lint->mData[0] = value;
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Resize by:
// Padding a GSLINT with leading zeroes.
// or stripping lead zeroes.
// This function will not strip digits other than zero.
gsi_bool gsiLargeIntResize(gsLargeInt_t *lint, l_word length)
{
if (length > GS_LARGEINT_MAX_DIGITS)
return gsi_false;
// strip leading zeroes until length is reached
if (lint->mLength >= length)
{
while(lint->mLength > length && lint->mData[lint->mLength-1]==0)
lint->mLength--; // check each digit to make sure it's zero
if (lint->mLength == length)
return gsi_true;
else
return gsi_false;
}
// otherwise, add zeroes until length is reached
else
{
memset(&lint->mData[lint->mLength], 0, (length-lint->mLength)*sizeof(l_word));
lint->mLength = length;
return gsi_true;
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Makes two GSLINT the same size, the size being a power of 2
// NOTE: Testing next multiple of two, not power of 2
gsi_bool gsiLargeIntSizePower2(const gsLargeInt_t *src1, const gsLargeInt_t *src2, l_word *lenout)
{
unsigned int i = 0;
int len1 = (int)src1->mLength;
int len2 = (int)src2->mLength;
// strip leading zeroes
while(len1>0 && src1->mData[len1-1] == 0)
len1--;
while(len2>0 && src2->mData[len2-1] == 0)
len2--;
// set to longer length
*lenout = (l_word)max(len1, len2);
// search for power of two >= length
// (this length is in digits, not bits)
i=1;
while(i < *lenout)
i = i<<1;
*lenout = (l_word)i;
if (*lenout > GS_LARGEINT_MAX_DIGITS)
return gsi_false;
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Compare two integers
// -1 = data1 < data2
// 0 = data1 = data2
// 1 = data1 > data2
static gsi_i32 gsiLargeIntCompare(const l_word *data1, l_word len1, const l_word *data2, l_word len2)
{
// skip leading whitespace, if any
while(data1[len1-1] == 0 && len1>0)
len1--;
while(data2[len2-1] == 0 && len2>0)
len2--;
if (len1<len2)
return -1;
else if (len1>len2)
return 1;
else
{
// same size, compare digits
while(len1 > 0)
{
if (data1[len1-1] < data2[len1-1])
return -1;
else if (data1[len1-1] > data2[len1-1])
return 1;
len1--;
}
}
return 0; // equal!
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static gsi_bool gsiLargeIntStripLeadingZeroes(gsLargeInt_t* lint)
{
while(lint->mLength >0 && lint->mData[lint->mLength-1]==0)
lint->mLength--;
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Addition may cause overflow
gsi_bool gsLargeIntAdd(const gsLargeInt_t *src1, const gsLargeInt_t *src2, gsLargeInt_t *dest)
{
gsi_bool result = gsiLargeIntAdd(src1->mData, src1->mLength, src2->mData, src2->mLength, dest->mData, &dest->mLength, GS_LARGEINT_MAX_DIGITS);
if (gsi_is_false(result))
memset(dest, 0, sizeof(gsLargeInt_t)); // overflow
return result;
}
// len: In value = maxsize
// Out value = actual size
static gsi_bool gsiLargeIntAdd(const l_word *data1, l_word length1, const l_word *data2, l_word length2, l_word *dest, l_word *lenout, l_word maxlen)
{
gsi_u32 i=0;
l_dword carry = 0; // to hold overflow
gsi_u32 shorterLen = 0;
gsi_u32 longerLen = 0;
//const gsi_u32 *shorterSrc = NULL;
const l_word *longerSrc = NULL;
GSLINT_ENTERTIMER(GSLintTimerAdd);
if (maxlen < length1 || maxlen < length2)
return gsi_false; // dest not large enough, OVERFLOW
if (length1 < length2)
{
shorterLen = length1;
//shorterSrc = data1;
longerLen = length2;
longerSrc = data2;
}
else
{
shorterLen = length2;
//shorterSrc = data2;
longerLen = length1;
longerSrc = data1;
}
// Add digits until the shorterSrc's length is reached
while(i < shorterLen)
{
carry += (l_dword)data1[i] + data2[i];
dest[i] = (l_word)carry;
carry = carry >> GS_LARGEINT_DIGIT_SIZE_BITS; //32;
i++;
}
// Continue adding until carry is zero
while((carry > 0) && (i < longerLen))
{
carry += (l_dword)longerSrc[i];
dest[i] = (l_word)carry;
carry = carry >> GS_LARGEINT_DIGIT_SIZE_BITS; //32;
i++;
}
// Is there still a carry?
// do not perform length check here, so that we can support oversized buffers
if (carry > 0) // && i < GS_LARGEINT_INT_SIZE)
{
if (maxlen <= i)
return gsi_false; // OVERFLOW, no room for extra digit
dest[i++] = (l_word)carry;
carry = 0;
}
// Copy the rest of the bytes straight over (careful of memory overlap)
// this can't happen if there was a carry (see above carry>0 check)
if (i < longerLen)
{
// check overlap
if (&dest[i] != &longerSrc[i])
memcpy(&dest[i], &longerSrc[i], (longerLen-i)*sizeof(l_word));
i = longerLen;
}
*lenout = (l_word)i;
GSLINT_EXITTIMER(GSLintTimerAdd);
if (carry)
return gsi_false; // overflow
else
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Subtraction may cause underflow
// subtracts src1 FROM src2
// strips leading zeroes (gsiLargeIntSub doesn't strip for compatability with karatsuba fixed size numbers)
gsi_bool gsLargeIntSub(const gsLargeInt_t *src1, const gsLargeInt_t *src2, gsLargeInt_t *dest)
{
gsi_bool result = gsiLargeIntSub(src1->mData, src1->mLength, src2->mData, src2->mLength, dest->mData, &dest->mLength);
if (gsi_is_true(result))
gsiLargeIntStripLeadingZeroes(dest);
return result;
}
gsi_bool gsiLargeIntSub(const l_word *src1, l_word length1, const l_word *src2, l_word length2, l_word *dest, l_word *lenout)
{
l_dword borrow = 0; // to hold overflow
gsi_u32 shorterLen = min(length1, length2);
gsi_u32 i=0;
GSLINT_ENTERTIMER(GSLintTimerSub);
//printf("--From: ");
//gsiLargeIntPrint(src2, length2);
//printf("--Subtracting: ");
//gsiLargeIntPrint(src1, length1);
// Subtract digits
while(i < shorterLen)
{
borrow = (l_dword)src2[i] - src1[i] - borrow;
dest[i] = (l_word)borrow;
borrow = borrow>>63; // shift to last bit. This will be 1 if negative, 0 if positive
i++;
}
while(i < length2)
{
borrow = (l_dword)src2[i]-borrow;
dest[i] = (l_word)borrow;
borrow = borrow>>63;
i++;
}
// check for underflow
if (borrow != 0)
{
GSLINT_EXITTIMER(GSLintTimerSub);
return gsi_false;
}
while(length1 > i) // make sure remaining digits are only leading zeroes
{
if (src1[i] != 0)
{
GSLINT_EXITTIMER(GSLintTimerSub);
return gsi_false;
}
i++;
}
// Don't reduce length from subtraction, instead keep leading zeroes
// (do this for ease of use with Karatsuba which requires Power2 length)
*lenout = length2;
GSLINT_EXITTIMER(GSLintTimerSub);
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Multiply using normal method (use KMult when working with LargeInt*LargeInt)
gsi_bool gsLargeIntMult(const gsLargeInt_t *src1, const gsLargeInt_t *src2, gsLargeInt_t *dest)
{
gsi_bool result = gsiLargeIntMult(src1->mData, src1->mLength, src2->mData, src2->mLength, dest->mData, &dest->mLength, GS_LARGEINT_MAX_DIGITS);
if (gsi_is_false(result))
memset(dest, 0, sizeof(gsLargeInt_t)); // overflow
return result;
}
static gsi_bool gsiLargeIntMult(const l_word *data1, l_word length1, const l_word *data2, l_word length2, l_word *dest, l_word *lenout, l_word maxlen)
{
unsigned int i=0;
unsigned int k=0;
gsLargeInt_t temp;
memset(&temp, 0, sizeof(temp));
*lenout = 0;
GSLINT_ENTERTIMER(GSLintTimerMult);
for(i=0; i<length2; i++)
{
// don't have to multiply by 0
if(data2[i] != 0)
{
// multiply data1 by data2[i]
for (k=0; k<length1; k++)
{
// carry starts out as product
// (it is mathematically impossible for carry to overflow
// at the first addition [see below])
l_dword carry = (l_dword)data1[k] * data2[i];
unsigned int digit = (unsigned int)(i+k);
if (digit >= maxlen)
{
GSLINT_EXITTIMER(GSLintTimerMult);
return gsi_false; // overflow
}
while(carry)
{
carry += temp.mData[digit];
temp.mData[digit] = (l_word)carry;
carry = carry >> GS_LARGEINT_DIGIT_SIZE_BITS;
digit++;
if ((digit > maxlen) ||
(digit == maxlen && carry>0))
{
GSLINT_EXITTIMER(GSLintTimerMult);
return gsi_false; // overflow
}
}
if (digit > (gsi_i32)temp.mLength)
temp.mLength = (l_word)digit;
}
}
}
// copy into destination (calculate length at this time)
while(temp.mLength>0 && temp.mData[temp.mLength-1] == 0)
temp.mLength--; // strip leading zeroes
*lenout = temp.mLength;
memcpy(dest, temp.mData, (*lenout)*sizeof(l_word));
GSLINT_EXITTIMER(GSLintTimerMult);
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// divide src1 by divisor
gsi_bool gsLargeIntDiv(const gsLargeInt_t *src1, const gsLargeInt_t *divisor, gsLargeInt_t *dest, gsLargeInt_t *remainder)
{
// call the free-buffer version
return gsiLargeIntDiv(src1->mData, src1->mLength, divisor, dest, remainder);
}
// length1 can be, at most, 2*GS_LARGEINT_INT_SIZE
static gsi_bool gsiLargeIntDiv(const l_word *src, l_word len, const gsLargeInt_t *div, gsLargeInt_t *dest, gsLargeInt_t *remainder)
{
gsi_i32 result = 0; // temp, to store compare result
gsi_i32 divisorHighBit = GS_LARGEINT_DIGIT_SIZE_BITS-1; // pre-calculate this
// Bytes used from src1
int readIndex = 0;
int readLength = 0;
// setup scratch copies
gsLargeInt_t quotient;
l_word scopy[GS_LARGEINT_MAX_DIGITS*2]; // we support double length source for division, when dest is null
l_word scopyLen = len;
const l_word* divisorData = div->mData;
l_word divisorLen = div->mLength;
gsi_bool endLoop = gsi_false;
GSLINT_ENTERTIMER(GSLintTimerDiv);
memset(scopy, 0, sizeof(scopy));
// we only support oversized sources for calculating a remainder
// e.g. dest must be null
if (scopyLen > GS_LARGEINT_MAX_DIGITS && dest != NULL)
return gsi_false;
// strip leading zeroes (from our scratch copies)
while(scopyLen>0 && src[scopyLen-1]==0)
scopyLen--;
while(divisorLen>0 && divisorData[divisorLen-1]==0)
divisorLen--;
memcpy(scopy, src, scopyLen*sizeof(l_word));
memset("ient, 0, sizeof(quotient));
// check the unusual cases
if (scopyLen==0 || divisorLen==0)
{
if (dest)
{
dest->mData[0] = 0;
dest->mLength = 0;
}
if (remainder)
{
remainder->mData[0] = 0;
remainder->mLength = 0;
}
GSLINT_EXITTIMER(GSLintTimerDiv);
if (divisorLen == 0)
return gsi_false; // division by zero
else
return gsi_true; // zero divided, this is legal
}
if (gsiLargeIntCompare(scopy, scopyLen, divisorData, divisorLen)==-1)
{
// divisor is larger than source
if (dest)
{
dest->mLength = 0;
dest->mData[0] = 0;
}
remainder->mLength = scopyLen;
memcpy(remainder->mData, scopy, scopyLen*sizeof(l_word));
GSLINT_EXITTIMER(GSLintTimerDiv);
return gsi_true;
}
// calculate the divisor high bit
while((divisorData[divisorLen-1]&(1<<(gsi_u32)divisorHighBit))==0 && divisorHighBit>=0)
divisorHighBit--;
if (divisorHighBit == -1)
{
GSLINT_EXITTIMER(GSLintTimerDiv);
return gsi_false; // divide by zero
}
divisorHighBit += (divisorLen-1)*GS_LARGEINT_DIGIT_SIZE_BITS;
// position "sliding" window for first interation
// 41529 / [71389]2564
// WARNING: digits are indexed [2][1][0], first byte to read is index[2]
readIndex = (int)(scopyLen - divisorLen);
readLength = (int)divisorLen;
//if (readIndex < 0)
// _asm {int 3}; // overflow readIndex
do
{
result = gsiLargeIntCompare(&scopy[readIndex], (l_word)readLength, divisorData, divisorLen);
if (result == -1)
{
// scopy window is smaller, we'll need an extra digit
if (readIndex > 0)
{
readIndex--;
readLength++;
}
else
{
// no more digits!
endLoop = gsi_true;
}
}
else if (result == 0)
{
// not likely! set digits to zero and slide window
memset(&scopy[readIndex], 0, readLength*sizeof(l_word));
quotient.mData[readIndex] += 1;
if (quotient.mLength < (l_word)(readIndex+readLength))
quotient.mLength = (l_word)(readIndex+readLength);
readIndex -= readLength;
readLength = 1;
if (readIndex < 0)
endLoop = gsi_true;; // no more digits
}
else
{
// subtract directly onto our temp copy, so we don't have to worry about carry values
l_word quotientTemp = 0;
//if (readLength > 0xffff)
// _asm {int 3}
if (gsi_is_false(gsiLargeIntSubDivide(&scopy[readIndex], (l_word)readLength, divisorData, divisorLen, (gsi_u32)divisorHighBit, "ientTemp)))
{
// overflow
GSLINT_EXITTIMER(GSLintTimerDiv);
return gsi_false;
}
quotient.mData[readIndex] = (l_word)(quotient.mData[readIndex] + quotientTemp);
if (quotient.mLength < (l_word)(readIndex+readLength))
quotient.mLength = (l_word)(readIndex+readLength);
// remove new leading zeroes
while(scopy[readIndex+readLength-1] == 0 && readLength>1)
readLength--;
while(scopy[readIndex+readLength-1] == 0 && readIndex>1)
readIndex--;
}
}
while(gsi_is_false(endLoop));
// no more digits, leftover is remainder
if (readIndex >= 0)
{
memcpy(remainder->mData, &scopy[readIndex], readLength*sizeof(l_word));
remainder->mLength = (l_word)readLength;
}
else
{
remainder->mData[0] = 0;
remainder->mLength = 0;
}
// save off quotient, if desired
if (dest)
{
memcpy(dest->mData, quotient.mData, quotient.mLength*sizeof(l_word));
dest->mLength = quotient.mLength;
}
GSLINT_EXITTIMER(GSLintTimerDiv);
return gsi_true;
}
// atomic divide.
// Subtract divisor directly from src.
// Leave remainder in src.
static gsi_bool gsiLargeIntSubDivide(l_word *src, l_word length, const l_word *divisor, l_word dlen,
gsi_u32 highbit, l_word *quotient)
{
l_dword aboveBits = 0;
gsLargeInt_t temp; // stores temporary product before subtraction
gsLargeInt_t quotientCopy; // copy of quotient, length padded for multiplication
GSLINT_ENTERTIMER(GSLintTimerSubDivide);
// assert(src > divisor)
// assert(src < (MAX_DIGIT_VALUE * divisor))
//if(dlen==1 && *divisor==0)
// _asm {int 3} // division by zero
// Q: how many times to subtract?
// A: we estimate by taking the bits in src above the highest bit in divisor
if (length > dlen)
aboveBits = (src[length-2]&divisor[dlen-1]) | ((l_dword)src[length-1]<<GS_LARGEINT_DIGIT_SIZE_BITS);
else
aboveBits = src[length-1];
aboveBits /= divisor[dlen-1];
memset("ientCopy, 0, sizeof(quotientCopy));
quotientCopy.mData[0] = (l_word)(aboveBits);
quotientCopy.mData[1] = (l_word)(aboveBits>>GS_LARGEINT_DIGIT_SIZE_BITS);
// We only support quotients up to MAX_INT
if (quotientCopy.mData[1] != 0)
{
quotientCopy.mData[0] = (l_word)(-1);
quotientCopy.mData[1] = 0;
}
quotientCopy.mLength = 1;
// multiply this value by divisor, and that's how much to subtract
if (gsi_is_false(gsiLargeIntMult(divisor, dlen, quotientCopy.mData, quotientCopy.mLength, temp.mData, &temp.mLength, GS_LARGEINT_MAX_DIGITS)))
{
GSLINT_EXITTIMER(GSLintTimerSubDivide);
return gsi_false; // overflow
}
// while subtraction amount is larger than src, reduce it
while(gsiLargeIntCompare(temp.mData, temp.mLength, src, length)==1)
{
// divide by two
quotientCopy.mData[0] = (l_word)(quotientCopy.mData[0]>>1);
//if (quotientCopy.mData[0] == 0)
// _asm {int 3}
if (gsi_is_false(gsiLargeIntMult(divisor, dlen, quotientCopy.mData, quotientCopy.mLength, temp.mData, &temp.mLength, GS_LARGEINT_MAX_DIGITS)))
{
GSLINT_EXITTIMER(GSLintTimerSubDivide);
return gsi_false; // overflow
}
}
//if (gsiLargeIntCompare(temp.mData, temp.mLength, src, length)==1)
// _asm {int 3} // temp > src, subtraction will cause underflow!
// subtract it
gsiLargeIntSub(temp.mData, temp.mLength, src, length, src, &length);
*quotient = quotientCopy.mData[0];
//if (quotientCopy.mData[1] != 0)
// _asm {int 3}
GSLINT_EXITTIMER(GSLintTimerSubDivide);
GSI_UNUSED(highbit);
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Multiply using Karatsuba
// Karatsuba requires that the sizes be equal and a power of two
gsi_bool gsLargeIntKMult(const gsLargeInt_t *src1, const gsLargeInt_t *src2, gsLargeInt_t *dest)
{
l_word len = 0;
gsi_bool result = gsi_false;
gsLargeInt_t temp; // to prevent issues if (src1 == src2 == dest)
// quick check for multiplication by 0
if (src1->mLength == 0 || src2->mLength == 0)
{
dest->mLength = 0;
return gsi_true;
}
// when length is small it's faster to use "normal" multiplication
if (max(src1->mLength,src2->mLength) < GS_LARGEINT_KARATSUBA_CUTOFF)
return gsLargeIntMult(src1, src2, dest);
// Check for size/length restrictions
result = gsiLargeIntSizePower2(src1, src2, &len);
if (gsi_is_false(result) || len>(GS_LARGEINT_MAX_DIGITS/2))
{
// try regular multiplication
return gsLargeIntMult(src1, src2, dest);
}
// (don't time above section since it defers to Mult)
GSLINT_ENTERTIMER(GSLintTimerKMult);
// clear the temporary dest
memset(&temp, 0, sizeof(gsLargeInt_t));
temp.mLength = 0;
// resize if necessary
if (src1->mLength != len || src2->mLength != len)
{
// size is not correct, make a copy then multiply
gsLargeInt_t src1Copy;
gsLargeInt_t src2Copy;
memcpy(&src1Copy, src1, sizeof(gsLargeInt_t));
memcpy(&src2Copy, src2, sizeof(gsLargeInt_t));
gsiLargeIntResize(&src1Copy, len);
gsiLargeIntResize(&src2Copy, len);
result = gsiLargeIntKMult(src1Copy.mData, src2Copy.mData, len, temp.mData, &temp.mLength, GS_LARGEINT_MAX_DIGITS);
}
else
{
// size is correct, perform multiplication
result = gsiLargeIntKMult(src1->mData, src2->mData, len, temp.mData, &temp.mLength, GS_LARGEINT_MAX_DIGITS);
}
if (gsi_is_true(result))
{
// strip leading zeroes and copy into dest
gsiLargeIntStripLeadingZeroes(&temp);
memcpy(dest, &temp, sizeof(gsLargeInt_t));
}
GSLINT_EXITTIMER(GSLintTimerKMult);
return result;
}
// Utility for Karasuba
static gsi_bool gsiLargeIntKMult(const l_word *data1, const l_word *data2, l_word length,
l_word *dest, l_word *lenout, l_word maxlen)
{
// No timer here, this function is only called from GSLINTKMult
//GSLINT_ENTERTIMER(GSLintTimerKMult);
// "normal" multiplication is faster when length is small
if (length <= GS_LARGEINT_KARATSUBA_CUTOFF)
return gsiLargeIntMult(data1, length, data2, length, dest, lenout, maxlen);
else
{
gsLargeInt_t temp1, temp2, temp3;
l_word halfLen = (l_word)(length>>1);
temp1.mLength = 0;
temp2.mLength = 0;
temp3.mLength = 0;
//printf("Karasuba splitting at %d (1/2 = %d)\r\n", length, halfLen);
// Karatsuba: k = 12*34
// a = (1*3)
// b = (1+2)*(3+4)-a-c
// c = (2*4)
// k = a*B^N+b*B^(N/2)+c = a*100+b*10+c
// Enter the recursive portion
// TH = top half
// BH = bottom half
// Note that since (a*B^N + c) cannot overlap, we can immediately store both in dest
// Compute a. (TH of data1 * TH of data2)
// Stores in TH of dest, so later *B^N isn't necessary
// For the example, this puts 1*3 into the high half 03xx
gsiLargeIntKMult(&data1[halfLen], &data2[halfLen], halfLen, &dest[length], lenout, (l_word)(maxlen-length));
//printf("Calculated A (%d) = ", *lenout);
//gsiLargeIntPrint(&dest[length], *lenout);
// Compute c. (BH of data1 * BH of data2)
// For the example, this puts 2*4 into the low half xx08
gsiLargeIntKMult(data1, data2, halfLen, dest, lenout, maxlen);
//printf("Calculated C (%d) = ", *lenout);
//gsiLargeIntPrint(dest, *lenout);
// Compute b1. (TH of data1 + BH of data1)
gsiLargeIntAdd(&data1[halfLen], halfLen, data1, halfLen, temp1.mData, &temp1.mLength, GS_LARGEINT_MAX_DIGITS);
//printf("Calculated B1 (%d) = ", temp1.mLength);
//gsiLargeIntPrint(temp1.mData, temp1.mLength);
// Compute b2. (TH of data2 + BH of data2)
gsiLargeIntAdd(&data2[halfLen], halfLen, data2, halfLen, temp2.mData, &temp2.mLength, GS_LARGEINT_MAX_DIGITS);
//printf("Calculated B2 (%d) = ", temp2.mLength);
//gsiLargeIntPrint(temp2.mData, temp2.mLength);
// Compute b3. (b1*b2) (*B^N)
// For the example, (1+2)(3+4)*B^N = 21*B^N = 0210
memset(&temp3, 0, sizeof(gsLargeInt_t));
// May require resizing, but don't go above halfLen
if (temp1.mLength > halfLen || temp2.mLength > halfLen)
gsiLargeIntMult(temp1.mData, temp1.mLength, temp2.mData, temp2.mLength, &temp3.mData[halfLen], &temp3.mLength, (l_word)(GS_LARGEINT_MAX_DIGITS-halfLen));
else
{
gsi_bool result = gsiLargeIntSizePower2(&temp1, &temp2, lenout);
if (gsi_is_false(result))
return gsi_false; // could not resize
gsiLargeIntResize(&temp1, *lenout); // pad to new size
gsiLargeIntResize(&temp2, *lenout); // pad to new size
gsiLargeIntKMult(temp1.mData, temp2.mData, *lenout, &temp3.mData[halfLen], &temp3.mLength, (l_word)(GS_LARGEINT_MAX_DIGITS-halfLen));
}
temp3.mLength = (l_word)(temp3.mLength + halfLen); // fix length for temp3
//if (temp3.mLength > GS_LARGEINT_INT_SIZE)
// _asm {int 3} // this should be at most temp1.mLength+temp2.mLength
memset(temp3.mData, 0, halfLen*sizeof(l_word));
//printf("Calculated B3 (%d) = ", temp3.mLength);
//gsiLargeIntPrint(&temp3.mData[halfLen], temp3.mLength-halfLen);
// Compute final b. (b3-a-c) (*B^N)
// Note: The subtraction is in terms of (*B^N)
// For the example, 021x - 03x - 08x = 0100
gsiLargeIntSub(&dest[length], length, &temp3.mData[halfLen], (l_word)(temp3.mLength-halfLen), &temp3.mData[halfLen], &temp3.mLength);
temp3.mLength = (l_word)(temp3.mLength + halfLen);
gsiLargeIntSub( dest , length, &temp3.mData[halfLen], (l_word)(temp3.mLength-halfLen), &temp3.mData[halfLen], &temp3.mLength);
temp3.mLength = (l_word)(temp3.mLength + halfLen);
//printf("Calculated B (%d) = ", temp3.mLength);
//gsiLargeIntPrint(temp3.mData, temp3.mLength);
// Add em up
// Dest already contains A+C, so Add B
// For the example, 0308 + 0100 = 0408 (the correct answer)
gsiLargeIntAdd(dest, (l_word)(length*2), temp3.mData, temp3.mLength, dest, lenout, maxlen);
}
// strip leading zeroes from dest
while(*lenout > 0 && dest[*lenout-1] == 0)
*lenout = (l_word)(*lenout-1);
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
gsi_bool gsLargeIntSquareMod(const gsLargeInt_t *lint, const gsLargeInt_t *mod, gsLargeInt_t *dest)
{
int i = 0;
int k = 0;
int len = (int)lint->mLength; // signed version
l_dword carry = 0;
int oldShiftBit = 0;
int newShiftBit = 0;
gsi_bool result = gsi_false;
unsigned int mask = (unsigned int)1<<(GS_LARGEINT_DIGIT_SIZE_BITS-1);
l_word squareSums[GS_LARGEINT_MAX_DIGITS*2]; // temp dest for square sums
l_word otherSums[GS_LARGEINT_MAX_DIGITS*2]; // temp dest for other sums
l_word squareLen = 0;
l_word otherLen = 0;
GSLINT_ENTERTIMER(GSLintTimerSquareMod);
memset(&squareSums, 0, sizeof(squareSums));
memset(&otherSums, 0, sizeof(otherSums));
// Go through each digit, multiplying with each other digit
// (only do this once per pair, since AB == BA)
// Ex: ABC * ABC, we want AB,AC,BC only
for (i=1; i < len; i++)
{
for(k=0; k < i; k++)
{
carry += (l_dword)lint->mData[i]*lint->mData[k] + otherSums[i+k];
otherSums[i+k] = (l_word)carry;
carry = carry >> GS_LARGEINT_DIGIT_SIZE_BITS;
}
if(carry)
{
otherSums[i+k] = (l_word)carry;
carry = carry >> GS_LARGEINT_DIGIT_SIZE_BITS;
}
}
// Multiply by 2 (because each internal pair appears twice)
for (i=0; i < (2*len); i++)
{
newShiftBit = (otherSums[i] & mask)==mask?1:0; // calc next carry 1 or 0
otherSums[i] = (l_word)((otherSums[i] << 1) + oldShiftBit); // do the shift
oldShiftBit = newShiftBit;
}
// don't worry about left-overy carry because this can't overflow
// maxlen N-digit*N-digit = 2n-digit
// Go through each digit, multiplying with itself
for (i=0; i <len; i++)
{
carry = (l_dword)lint->mData[i] * lint->mData[i];
squareSums[i*2] = (l_word)carry;
squareSums[i*2+1] = (l_word)(carry >> GS_LARGEINT_DIGIT_SIZE_BITS);
}
squareLen = (l_word)(2*len);
otherLen = (l_word)(2*len);
// Add the two together
result = gsiLargeIntAdd(otherSums, otherLen, squareSums, squareLen, squareSums, &squareLen, GS_LARGEINT_MAX_DIGITS*2);
result = gsiLargeIntDiv(squareSums, squareLen, mod, NULL, dest);
GSLINT_EXITTIMER(GSLintTimerSquareMod);
return result;
}
//#define NEWEXP
#ifdef NEWEXP
//#define printf
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Montgomery exponentiation (see HAC 14.94)
//
// SPECIAL NOTE:
// A small public exponent will reduce the load on client encryption.
// (below 65535 is a security risk, so don't go too small)
gsi_bool gsLargeIntPowerMod(const gsLargeInt_t *b, const gsLargeInt_t *p, const gsLargeInt_t *m, gsLargeInt_t *dest)
{
gsLargeInt_t base;
gsLargeInt_t power;
gsLargeInt_t mod;
gsLargeInt_t one;
gsi_u32 expHighBit; // highest bit set in exponent;
int i = 0; // temp / counter
int k = 0; // binary size of our subdigits
int pow2k = 0; // 2^k
int kmask = 0; // 2^k-1
int kdigits = 0; // number of k-sized digits in p
//int leadingZeroBits = 0; // to make p evenly divisible by k
l_word modPrime;
gsLargeInt_t R; // "R" as used in the montgomery exponentiation algorithm.
//gsLargeInt_t Rmod; // R mod n
//gsLargeInt_t R2mod; // R^2 mod n
gsLargeInt_t * lut = NULL;
GSLINT_ENTERTIMER(GSLintTimerPowerMod);
memcpy(&base, b, sizeof(base));
memcpy(&power, p, sizeof(power));
memcpy(&mod, m, sizeof(mod));
memset(&R, 0, sizeof(R));
gsLargeIntSetValue(&one, 1);
// Catch the unusual cases
if (mod.mLength == 0)
{
// mod 0 = undefined
dest->mLength = 0;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
else if (mod.mLength==1 && mod.mData[0]==1)
{
// mod 1 = 0
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
else if (power.mLength == 0)
{
// x^0 = 1
dest->mLength = 1;
dest->mData[0] = 1;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
else if ((mod.mData[0]&1) == 0)
{
// Montgomery only works with odd modulus!
// (rsa modulus is prime1*prime2, which must be odd)
dest->mLength = 0;
dest->mData[0] = 0;
//_asm {int 3}
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// If base is larger than mod, we can (must) reduce it
if (gsiLargeIntCompare(base.mData, base.mLength, mod.mData, mod.mLength)!=-1)
{
gsLargeIntDiv(&base, &mod, NULL, &base);
}
if (base.mLength == 0)
{
// 0^e = 0
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
// find the highest bit set in power
expHighBit=GS_LARGEINT_DIGIT_SIZE_BITS;
while(((1<<(expHighBit-1))&power.mData[power.mLength-1]) == 0)
expHighBit--;
expHighBit += ((power.mLength-1) * GS_LARGEINT_DIGIT_SIZE_BITS); // add in 32 bits for each extra byte
// The previous algorithm used 1-bit digits
// This algorithm uses k-bit digits
// Determine the optimal size for k
k=8; // this will support up to 4096 bit encryption (and probably higher)
while ( (k > 1) &&
(gsi_u32)((k - 1) * (k << ((k - 1) << 1)) / ((1 << k) - k - 1)) >= expHighBit - 1
)
{
--k;
}
pow2k = 1 << k;
kmask = pow2k-1;
kdigits = (expHighBit+(k-1)) / k; // ceiling(expHighBit/k)
// calculate "R" (if mod=5678, R=10000 e.g. One digit higher)
memset(&R, 0, sizeof(R));
R.mLength = (l_word)(mod.mLength+1);
if (R.mLength > GS_LARGEINT_MAX_DIGITS)
return gsi_false; // you need to increase the large int capacity
R.mData[R.mLength-1] = 1; // set first bit one byte higher than mod
// find the multiplicative inverse of mod
gsiLargeIntInverseMod(&mod, &modPrime);
/*
// calculate Rmod (R%mod)
if (gsi_is_false(gsLargeIntDiv(&R, &mod, NULL, &Rmod)))
{
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// calculate R2mod (R^2%mod = (Rmod*Rmod)%mod)
if (gsi_is_false(gsLargeIntSquareMod(&Rmod, &mod, &R2mod)))
{
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
*/
// Allocate space for a table of values that will come up repeatedly
// xwiggle is (br mod n)
// These are the odd powers of xwiggle, x^3, x^5 and so on
// We generate these by repeated multiplications by xwiggle
//if (k >= 3)
{
// no no no[0] = xwiggle^3 (montgomery multiply [2]*[1])
// no no no[1] = xwiggle^5 (montgomery multiply [2]*[3])
// no no no[2] = xwiggle^7 (montgomery multiply [2]*[5])
// allocate space
// ~1k for typical small RSA public exponents (e.g. 65537)
// ~16k for 1024-bit RSA exponent
// ~32k for 2048-bit RSA exponent
// ~64k for 4096-bit RSA exponent
int i=0;
int valuesNeeded = pow2k;//((pow2k/2)-1);
int spaceneeded = sizeof(gsLargeInt_t) * valuesNeeded;
lut = (gsLargeInt_t*)gsimalloc(spaceneeded);
if (lut == NULL)
return gsi_false; // out of memory
memset(lut, 0x00, spaceneeded);
// set first values
// [0] = 1
// [1] = br mod n (normal multiplication)
// [i] = mont([1] * [i-1])
gsLargeIntSetValue(&lut[0], 1);
if (gsi_is_false(gsLargeIntMult(&base, &R, &lut[1])) ||
gsi_is_false(gsLargeIntDiv(&lut[1], &mod, NULL, &lut[1])) )
{
gsifree(lut);
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// fill in the values
for (i=2; i < valuesNeeded; i++)
{
if (gsi_is_false(gsiLargeIntMultM(&lut[1], &lut[i-1], &mod, modPrime, &lut[i])) )
{
gsifree(lut);
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
}
}
// set starting point
if (gsi_is_false(gsLargeIntMult(&base, &R, dest)) || // Normal multiply
gsi_is_false(gsLargeIntDiv(dest, &mod, NULL, dest)) ) // A mod operation
{
gsifree(lut);
return gsi_false;
}
// loop through the k-sized digits
for (i=0; i < kdigits; i++)
{
int bitReadIndex = expHighBit - (i*k); // index of the bit we're reading
int l_index; // = ((bitReadIndex-1)/GS_LARGEINT_DIGIT_SIZE_BITS); // -1 to use zero based indexes
int l_firstbit;
l_dword twodigits;
l_dword mask;
l_word digitval;
l_index = ((bitReadIndex-1)/GS_LARGEINT_DIGIT_SIZE_BITS); // -1 to use zero based indexes
// for first digit, use leading zeroes when necessary
if ((bitReadIndex % k) != 0)
bitReadIndex += k - (bitReadIndex % k); // round up to next k
if (i != 0)
{
if (bitReadIndex - (l_index*GS_LARGEINT_DIGIT_SIZE_BITS)> GS_LARGEINT_DIGIT_SIZE_BITS)
l_index++;
}
if (i==0)
{
// first digit
l_firstbit = l_index * GS_LARGEINT_DIGIT_SIZE_BITS; // first bit of this digit
twodigits = p->mData[l_index];
}
else if (l_index > 0)
{
// middle digits
l_firstbit = (l_index-1) * GS_LARGEINT_DIGIT_SIZE_BITS; // first bit of this digit
twodigits = (l_dword)((l_dword)p->mData[l_index] << GS_LARGEINT_DIGIT_SIZE_BITS) | p->mData[l_index-1];
}
else if (l_index == 0 && p->mLength > 1)
{
// final digit, when there are proceeding digits
l_firstbit = 0;
twodigits = (l_dword)(p->mData[l_index+1] << GS_LARGEINT_DIGIT_SIZE_BITS) | p->mData[l_index];
}
else
{
// final digit, no proceeding digits
l_firstbit = l_index * GS_LARGEINT_DIGIT_SIZE_BITS; // first bit of this digit
twodigits = p->mData[l_index];
}
mask = (l_dword)kmask << (bitReadIndex-l_firstbit-k);
digitval = (l_word)((twodigits & mask) >> (bitReadIndex-l_firstbit-k));
// use digitval to determine how many squaring and multiplication operations we need to perform
{
static int twotab[] =
{0, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0, 7, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 6, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0, 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, 5, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0};
static USHORT oddtab[] =
{0, 1, 1, 3, 1, 5, 3, 7, 1, 9, 5, 11, 3, 13, 7, 15, 1, 17, 9, 19, 5, 21, 11, 23, 3, 25, 13, 27, 7, 29, 15, 31, 1,
33, 17, 35, 9, 37, 19, 39, 5, 41, 21, 43, 11, 45, 23, 47, 3, 49, 25, 51, 13, 53, 27, 55, 7, 57, 29, 59, 15,
61, 31, 63, 1, 65, 33, 67, 17, 69, 35, 71, 9, 73, 37, 75, 19, 77, 39, 79, 5, 81, 41, 83, 21, 85, 43, 87, 11,
89, 45, 91, 23, 93, 47, 95, 3, 97, 49, 99, 25, 101, 51, 103, 13, 105, 53, 107, 27, 109, 55, 111, 7, 113,
57, 115, 29, 117, 59, 119, 15, 121, 61, 123, 31, 125, 63, 127, 1, 129, 65, 131, 33, 133, 67, 135, 17,
137, 69, 139, 35, 141, 71, 143, 9, 145, 73, 147, 37, 149, 75, 151, 19, 153, 77, 155, 39, 157, 79, 159,
5, 161, 81, 163, 41, 165, 83, 167, 21, 169, 85, 171, 43, 173, 87, 175, 11, 177, 89, 179, 45, 181, 91,
183, 23, 185, 93, 187, 47, 189, 95, 191, 3, 193, 97, 195, 49, 197, 99, 199, 25, 201, 101, 203, 51, 205,
103, 207, 13, 209, 105, 211, 53, 213, 107, 215, 27, 217, 109, 219, 55, 221, 111, 223, 7, 225, 113,
227, 57, 229, 115, 231, 29, 233, 117, 235, 59, 237, 119, 239, 15, 241, 121, 243, 61, 245, 123, 247, 31,
249, 125, 251, 63, 253, 127, 255};
//printf("[gsint] Digit %d = %d\r\n", i, digitval);
if (i==0)
{
int counter = 0;
memcpy(dest, &lut[oddtab[digitval]], sizeof(gsLargeInt_t));
//printf("[gsint] Set start to %d\r\n", dest->mData[0]);
for (counter = twotab[digitval]; counter> 0; counter--)
{
if (gsi_is_false(gsiLargeIntMultM(dest,dest, &mod, modPrime, dest)))
{
gsifree(lut);
return gsi_false;
}
//printf("[gsint] First digit, squared to %d\r\n", dest->mData[0]);
}
}
else if (digitval != 0)
{
int counter = 0;
int lutindex = oddtab[digitval]; // we only precalculate the odd powers
//int lutindex = (oddtab[digitval]+1)/2; // we only precalculate the odd powers
for (counter = (int)(k-twotab[digitval]); counter> 0; counter--)
{
if (gsi_is_false(gsiLargeIntMultM(dest,dest, &mod, modPrime, dest)))
{
gsifree(lut);
return gsi_false;
}
//printf("[gsint] Squared to %d\r\n", dest->mData[0]);
}
if (gsi_is_false(gsiLargeIntMultM(dest, &lut[lutindex], &mod, modPrime, dest)))
{
gsifree(lut);
return gsi_false;
}
//printf("[gsint] Mult by [%d](%d) to %d\r\n", lutindex, lut[lutindex].mData[0], dest->mData[0]);
for (counter = twotab[digitval]; counter> 0; counter--)
{
if (gsi_is_false(gsiLargeIntMultM(dest,dest, &mod, modPrime, dest)))
{
gsifree(lut);
return gsi_false;
}
//printf("[gsint] Squared to %d\r\n", dest->mData[0]);
}
}
else
{
int counter = 0;
for (counter = k; counter > 0; counter--)
{
if (gsi_is_false(gsiLargeIntMultM(dest,dest, &mod, modPrime, dest)))
{
gsifree(lut);
return gsi_false;
}
//printf("[gsint] Squared to %d\r\n", dest->mData[0]);
}
}
}
}
// normalize (MultM by 1)
if (gsi_is_false(gsiLargeIntMultM(dest, &one, &mod, modPrime, dest)))
return gsi_false;
gsifree(lut);
return gsi_true;
}
#else
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Montgomery exponentiation (see HAC 14.94)
//
// SPECIAL NOTE:
// A small public exponent will reduce the load on client encryption.
// (below 65535 is a security risk, so don't go too small)
gsi_bool gsLargeIntPowerMod(const gsLargeInt_t *b, const gsLargeInt_t *p, const gsLargeInt_t *m, gsLargeInt_t *dest)
{
int i=0; // temp/counter
int digitNum=0; // temp/counter
int digitBit=0;
l_word modPrime;
gsi_u32 expHighBit; // highest bit set in exponent;
gsLargeInt_t R; // "R" as used in the montgomery exponentiation algorithm.
gsLargeInt_t Rmod; // R%mod
gsLargeInt_t R2mod; // R^2%mod
gsLargeInt_t temp;
gsLargeInt_t xwiggle; // montgomery mult of (x,R2mod)
gsLargeInt_t base;
gsLargeInt_t power;
gsLargeInt_t mod;
GSLINT_ENTERTIMER(GSLintTimerPowerMod);
memset(&R, 0, sizeof(R));
memset(&Rmod, 0, sizeof(Rmod));
memset(&R2mod, 0, sizeof(R2mod));
memset(&temp, 0, sizeof(temp));
memset(&xwiggle, 0, sizeof(xwiggle));
memcpy(&base, b, sizeof(base));
memcpy(&power, p, sizeof(power));
memcpy(&mod, m, sizeof(mod));
gsiLargeIntStripLeadingZeroes(&base);
gsiLargeIntStripLeadingZeroes(&power);
gsiLargeIntStripLeadingZeroes(&mod);
// Catch the unusual cases
if (mod.mLength == 0)
{
// mod 0 = undefined
dest->mLength = 0;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
else if (mod.mLength==1 && mod.mData[0]==1)
{
// mod 1 = 0
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
else if (power.mLength == 0)
{
// x^0 = 1
dest->mLength = 1;
dest->mData[0] = 1;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
else if ((mod.mData[0]&1) == 0)
{
// Montgomery only works with odd modulus!
// (rsa modulus is prime1*prime2, which must be odd)
dest->mLength = 0;
dest->mData[0] = 0;
//_asm {int 3}
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// If base is larger than mod, we can (must) reduce it
if (gsiLargeIntCompare(base.mData, base.mLength, mod.mData, mod.mLength)!=-1)
{
gsLargeIntDiv(&base, &mod, NULL, &base);
}
if (base.mLength == 0)
{
// 0^e = 0
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
// find the highest bit set in power
expHighBit=GS_LARGEINT_DIGIT_SIZE_BITS;
while(((1<<(expHighBit-1))&power.mData[power.mLength-1]) == 0)
expHighBit--;
expHighBit += ((power.mLength-1) * GS_LARGEINT_DIGIT_SIZE_BITS); // add in 32 bits for each extra byte
// On to the tricky tricky!
// 1) We can't compute B^P and later apply the mod; B^P is just too big
// So we have to make modular reductions along the way
// 2) Since modular reduction is essentially a division, we would like
// to use a mod 2^E so that division is just a bit strip.
// ex. (1383 mod 16) = binary(0000010101100111 mod 00010000) = 00000111 = dec 7
// Precalculate some values that will come up repeatedly
// calculate "R" (if mod=5678, R=10000 e.g. One digit higher)
memset(&R, 0, sizeof(R));
R.mLength = (l_word)(mod.mLength+1);
if (R.mLength > GS_LARGEINT_MAX_DIGITS)
return gsi_false; // you need to increase the large int capacity
R.mData[R.mLength-1] = 1; // set first bit one byte higher than mod
// find the multiplicative inverse of mod
gsiLargeIntInverseMod(&mod, &modPrime);
// calculate Rmod (R%mod)
if (gsi_is_false(gsLargeIntDiv(&R, &mod, NULL, &Rmod)))
{
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// calculate R2mod (R^2%mod = (Rmod*Rmod)%mod)
if (gsi_is_false(gsLargeIntSquareMod(&Rmod, &mod, &R2mod)))
{
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// calculate xwiggle
if (gsi_is_false(gsiLargeIntMultM(&base, &R2mod, &mod, modPrime, &xwiggle)))
{
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_false;
}
// loop through the BITS of power
// if the bit is 1, perform a multiplication by xwiggle? (11/2/2006)
// TODO: THIS DOESN'T WORK IF THE HIGHBIT IS EVER ABOVE GS_LARGEINT_DIGIT_SIZE_BITS
memcpy(dest, &Rmod, sizeof(gsLargeInt_t)); // start dest at Rmod
for (i=(int)(expHighBit-1); i>=0; i--)
{
// mont square the current total
gsiLargeIntMultM(dest, dest, &mod, modPrime, dest);
digitNum = (gsi_i32)(i/GS_LARGEINT_DIGIT_SIZE_BITS); // which digit to extract a bit from?
digitBit = (gsi_i32)(i % GS_LARGEINT_DIGIT_SIZE_BITS); // which bit to extract from that digit?
//if ((power.mData[k] & (1<<i))==((l_word)1<<i))
// HACKED DUE TO COMPILER CRASH
// THE REPEATED 1<<digitbit caused the optimizer to 'splode
{
GS_LARGEINT_DIGIT_TYPE digit = power.mData[digitNum];
GS_LARGEINT_DIGIT_TYPE mask = (GS_LARGEINT_DIGIT_TYPE)(1<<digitBit);
GS_LARGEINT_DIGIT_TYPE masked = digit & mask; //(1<<digitBit);
// FORCE COMPILER TO NOT OPTIMIZE THIS
if (mask == masked)
gsiLargeIntMultM(dest, &xwiggle, &mod, modPrime, dest);
}
}
// Since we're working with Montgomery values (x*R2mod)
// we have to adjust back to x
temp.mLength = 1;
temp.mData[0] = 1;
gsiLargeIntMultM(dest, &temp, &mod, modPrime, dest);
GSLINT_EXITTIMER(GSLintTimerPowerMod);
return gsi_true;
}
#endif
#define NEWMULTM
#ifdef NEWMULTM
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Montgomery multiplication
// Computes (src1*src2*r^-1)%mod
gsi_bool gsiLargeIntMultM(gsLargeInt_t *x, gsLargeInt_t *y, const gsLargeInt_t *m, gsi_u32 modPrime, gsLargeInt_t *dest)
{
l_word tempLen = 0;
l_word temp[GS_LARGEINT_MAX_DIGITS*2];
l_word* lasttnptr;
const l_word* lastnptr;
l_word* tptr;
const l_word* nptr;
l_word* tiptr;
l_dword carry = 0;
l_word mi = 0;
l_word logB_r = m->mLength;
memset(temp, 0, sizeof(temp));
if (gsi_is_false(gsiLargeIntMult(x->mData, x->mLength, y->mData, y->mLength, temp, &tempLen, GS_LARGEINT_MAX_DIGITS*2)))
return gsi_false;
lasttnptr = &temp[m->mLength-1];
lastnptr = &m->mData[m->mLength-1];
if (tempLen < m->mLength*2)
{
memset(&temp[tempLen], 0, (m->mLength*2 - tempLen) * GS_LARGEINT_DIGIT_SIZE_BYTES);
//memset(&temp[tempLen], 0, sizeof(temp) - tempLen * GS_LARGEINT_DIGIT_SIZE_BYTES); // safer to clear out the whole thing?
tempLen = (l_word)(m->mLength*2);
}
for (tptr = &temp[0]; tptr <= lasttnptr; tptr++)
{
carry = 0;
mi = (l_word)((l_dword)modPrime * (l_dword)*tptr);
tiptr = tptr;
for (nptr = &m->mData[0]; nptr <= lastnptr; nptr++, tiptr++)
{
carry = (l_dword)mi * (l_dword)*nptr +
(l_dword)*tiptr + (l_dword)(l_word)(carry >> GS_LARGEINT_DIGIT_SIZE_BITS);
*tiptr = (l_word)(carry);
}
// apply the carry value
for (; ((carry >> GS_LARGEINT_DIGIT_SIZE_BITS) > 0) && tiptr <= &temp[tempLen-1]; tiptr++)
{
*tiptr = (l_word)(carry = (l_dword)*tiptr + (l_dword)(l_word)(carry >> GS_LARGEINT_DIGIT_SIZE_BITS));
}
// If we still have a carry, increase the length of temp
if (((carry >> GS_LARGEINT_DIGIT_SIZE_BITS) > 0))
{
*tiptr = (l_word)(carry >> GS_LARGEINT_DIGIT_SIZE_BITS);
tempLen++;
}
}
// **WARNING**
// Bytes from the plain text message may appear within the temporary buffer.
// These bytes should be cleared to prevent bugs where that data may be exposed. (buffer overrun?)
if (gsiLargeIntCompare(&temp[logB_r], tempLen - logB_r, m->mData, m->mLength) != -1)
{
if (gsi_is_false(gsiLargeIntSub(m->mData, m->mLength, &temp[logB_r], tempLen - logB_r, dest->mData, &dest->mLength)))
{
memset(temp, 0, sizeof(temp));
memset(dest, 0, sizeof(gsLargeInt_t));
return gsi_false;
}
}
else
{
memset(dest, 0, sizeof(gsLargeInt_t));
dest->mLength = m->mLength;
memcpy(dest->mData, &temp[logB_r], (tempLen - logB_r)*GS_LARGEINT_DIGIT_SIZE_BYTES);
memset(temp, 0, sizeof(temp));
}
return gsi_true;
}
#else
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Montgomery multiplication
// Computes (src1*src2*r^-1)%mod
// Note:
// This implementation is based on HAC14.36 which has a lot of room for improvement
// FLINT algorithm runs approx 30 times faster.
gsi_bool gsiLargeIntMultM(gsLargeInt_t *x, gsLargeInt_t *y, const gsLargeInt_t *m, gsi_u32 modPrime, gsLargeInt_t *dest)
{
int i=0;
l_dword xiy0;
l_word u = 0;
gsLargeInt_t A;
gsLargeInt_t xiy;
gsLargeInt_t temp;
GSLINT_ENTERTIMER(GSLintTimerMultM);
gsiLargeIntStripLeadingZeroes(x);
gsiLargeIntStripLeadingZeroes(y);
// Check inputs
i=(int)(m->mLength);
while(i>0 && m->mData[i-1]==0)
i--;
if (i==0)
{
// modulus is zero, answer undefined
dest->mData[0] = 0;
dest->mLength = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_false;
}
if (x->mLength==0)
{
// x == 0
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_true;
}
if (y->mLength==0)
{
// y == 0
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_true;
}
// We pad with zeroes so that we don't have to check for overruns in the loop below
// (note: resize will not remove non-zero digits from x or y)
gsiLargeIntResize(x, m->mLength);
gsiLargeIntResize(y, m->mLength);
// Continue with the Multiplication
memset(&A, 0, sizeof(A));
memset(&temp, 0, sizeof(temp));
memset(&xiy, 0, sizeof(xiy));
for (i=0; (gsi_u32)i < m->mLength; i++)
{
xiy0 = (l_dword)x->mData[i]*y->mData[0]; // y[0], NOT y[i] !!
u = (l_word)((xiy0+A.mData[0])*modPrime); // strip bits over the first digit
// A = (A+x[i]*y + u[i]*m)/b
// compute x[i]*y
memset(temp.mData, 0, y->mLength*sizeof(l_word)); // clear out a portion of temp
temp.mData[0] = x->mData[i];
temp.mLength = y->mLength; // xi padded with zeroes
if (gsi_is_false(gsiLargeIntMult(temp.mData, temp.mLength, y->mData, y->mLength, xiy.mData, &xiy.mLength, GS_LARGEINT_MAX_DIGITS)))
{
// overflow
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_false;
}
// compute u[i]*m
memset(temp.mData, 0, m->mLength*sizeof(l_word)); // clear out a portion of temp
temp.mData[0] = u;
temp.mLength = m->mLength;
//if (gsi_is_false(gsiLargeIntMult(temp.mData, temp.mLength, m->mData, m->mLength, temp.mData, &temp.mLength)))
if (gsi_is_false(gsLargeIntKMult(&temp, m, &temp)))
{
// overflow
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_false;
}
// Add both to A
if (gsi_is_false(gsiLargeIntAdd(xiy.mData, xiy.mLength, A.mData, A.mLength, A.mData, &A.mLength, GS_LARGEINT_MAX_DIGITS)))
{
// overflow
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_false;
}
if (gsi_is_false(gsiLargeIntAdd(temp.mData, temp.mLength, A.mData, A.mLength, A.mData, &A.mLength, GS_LARGEINT_MAX_DIGITS)))
{
// overflow
dest->mLength = 0;
dest->mData[0] = 0;
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_false;
}
// Divide by b (e.g. Remove first digit from A)
if (A.mLength > 1)
{
memmove(&A.mData[0], &A.mData[1], (A.mLength-1)*sizeof(l_word));
A.mData[A.mLength-1] = 0;
A.mLength--;
}
else
{
A.mLength = 0;
A.mData[0] = 0;
}
}
//if (A >= m then subtract another m)
if (gsiLargeIntCompare(A.mData, A.mLength, m->mData, m->mLength)!=-1)
gsiLargeIntSub(m->mData, m->mLength, A.mData, A.mLength, dest->mData, &dest->mLength);
else
memcpy(dest, &A, sizeof(A));
GSLINT_EXITTIMER(GSLintTimerMultM);
return gsi_true;
}
#endif
/*
// Computes (src*src*r^-1)%mod
static gsi_bool gsiLargeIntSquareM(const gsLargeInt_t *src, const gsLargeInt_t *mod, gsi_u32 modPrime, gsi_u32 R, gsLargeInt_t *dest)
{
GSI_UNUSED(src);
GSI_UNUSED(mod);
GSI_UNUSED(modPrime);
GSI_UNUSED(R);
GSI_UNUSED(dest);
assert(0);
return gsi_true;
}*/
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Calculate multiplicative inverse of mod, (-mod^-1 mod 2^R)
// ala. Dusse and Kaliski, extended Euclidean algorithm
gsi_bool gsiLargeIntInverseMod(const gsLargeInt_t *mod, l_word *dest)
{
l_dword x=2;
l_dword y=1;
l_dword check = 0;
gsi_u32 i;
for (i = 2; i <= GS_LARGEINT_DIGIT_SIZE_BITS; i++)
{
check = (l_dword)mod->mData[0] * (l_dword)y;
if (x < (check & ((x<<1)-1)))
y += x;
x = x << 1;
}
*dest = (l_word)(x-y);
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
gsi_bool gsLargeIntPrint(FILE* logFile, const gsLargeInt_t *lint)
{
return gsiLargeIntPrint(logFile, lint->mData, lint->mLength);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
gsi_bool gsiLargeIntPrint(FILE* logFile, const l_word *data, l_word length)
{
// this is only specific to NITRO since for other platforms the fprintf will
// resolve to a STDOUT
#if !defined(_NITRO)
while(length >0)
{
fprintf(logFile, "%08X", data[length-1]);
length--;
}
fprintf(logFile, "\r\n");
return gsi_true;
#else
GSI_UNUSED(logFile);
GSI_UNUSED(data);
GSI_UNUSED(length);
return gsi_false;
#endif
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// stream of bytes, big endian. (first byte = most significant digit)
gsi_bool gsLargeIntSetFromHexString(gsLargeInt_t *lint, const char* hexstream)
{
l_word* writePos = lint->mData;
gsi_u32 temp;
int len = 0;
int byteIndex = 0;
GS_ASSERT(hexstream != NULL);
len = (int)strlen(hexstream);
if (len == 0)
{
lint->mLength = 0;
lint->mData[0] = 0;
return gsi_true;
}
if ((len/2) > (GS_LARGEINT_MAX_DIGITS*GS_LARGEINT_DIGIT_SIZE_BYTES))
return gsi_false;
// 2 characters per byte, 4 bytes per integer
lint->mLength = (l_word)((len+(2*GS_LARGEINT_DIGIT_SIZE_BYTES-1))/(2*GS_LARGEINT_DIGIT_SIZE_BYTES));
lint->mData[lint->mLength-1] = 0; // set last byte to zero for left over characters
while(len > 0)
{
if(len >= 2)
sscanf((char*)(hexstream+len-2), "%02x", &temp); // sscanf requires a 4 byte dest
else
sscanf((char*)(hexstream+len-1), "%01x", &temp); // sscanf requires a 4 byte dest
if(byteIndex == 0)
*writePos = 0;
*writePos |= (temp << (byteIndex * 8));
if(++byteIndex == GS_LARGEINT_DIGIT_SIZE_BYTES)
{
writePos++;
byteIndex = 0;
}
len-=min(2,len);
}
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Reverse bytes in a LINT, which are LittleEndian
// ex: Packing an RSA message of which the first bytes are 0x00 0x02
// The first bytes of the packet must become the MSD of the LINT
gsi_bool gsLargeIntReverseBytes(gsLargeInt_t *lint)
{
#if defined(GSI_LITTLE_ENDIAN)
char *left = (char*)&lint->mData[0];
char *right = ((char*)&lint->mData[lint->mLength])-1;
char temp;
#else
l_word *left = lint->mData;
l_word *right = lint->mData + (lint->mLength - 1);
l_word temp;
#endif
if (lint->mLength == 0)
return gsi_true;
while(left < right)
{
temp = *left;
(*left++) = (*right);
(*right--) = temp;
}
return gsi_true;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// hashing is made complicated by differing byte orders
void gsLargeIntAddToMD5(const gsLargeInt_t * _lint, MD5_CTX * md5)
{
int byteLength = 0;
gsi_u8 * dataStart = NULL;
// Create a non-const copy so we can reverse bytes to add to the MD5 hash
gsLargeInt_t lint;
memcpy(&lint, _lint, sizeof(lint));
// first, calculate the byte length
byteLength = (int)gsLargeIntGetByteLength(&lint);
if (byteLength == 0)
return; // no data
dataStart = (gsi_u8*)lint.mData;
if ((byteLength % GS_LARGEINT_DIGIT_SIZE_BYTES) != 0)
dataStart += GS_LARGEINT_DIGIT_SIZE_BYTES - (byteLength % GS_LARGEINT_DIGIT_SIZE_BYTES);
// reverse to big-endian (MS) then hash
gsLargeIntReverseBytes(&lint);
MD5Update(md5, dataStart, (unsigned int)byteLength);
gsLargeIntReverseBytes(&lint);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Length in bytes so leading zeroes can be dropped from hex strings
gsi_u32 gsLargeIntGetByteLength(const gsLargeInt_t *lint)
{
int intSize = (int)lint->mLength;
int byteSize = 0;
int i=0;
l_word mask = 0xFF;
// skip leading zeroes
while(intSize > 0 && lint->mData[intSize-1] == 0)
intSize --;
if (intSize == 0)
return 0; // no data
byteSize = intSize * (gsi_i32)sizeof(l_word);
// subtract bytes for each leading 0x00 byte
mask = 0xFF;
for (i=1; i < GS_LARGEINT_DIGIT_SIZE_BYTES; i++)
{
if (lint->mData[intSize-1] <= mask)
{
byteSize -= sizeof(l_word)-i;
break;
}
mask = (l_word)((mask << 8) | 0xFF);
}
return (gsi_u32)byteSize;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Creates a large int from a byte buffer
// Essentially, constructs the array of digits in appropriate byte order
gsi_bool gsLargeIntSetFromMemoryStream(gsLargeInt_t *lint, const gsi_u8* data, gsi_u32 len)
{
lint->mData[0] = 0;
memcpy(((char*)lint->mData)+(4-len%4)%4, data, len);
// Set length to ceiling of len/digit_size
lint->mLength = (unsigned int)((len+(GS_LARGEINT_DIGIT_SIZE_BYTES-1))/GS_LARGEINT_DIGIT_SIZE_BYTES);
return gsLargeIntReverseBytes(lint);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
gsi_bool gsLargeIntWriteToMemoryStream(const gsLargeInt_t *lint, gsi_u8* data)
{
gsLargeInt_t copy;
memcpy(©, lint, sizeof(gsLargeInt_t));
gsLargeIntReverseBytes(©);
memcpy(data, copy.mData, copy.mLength * GS_LARGEINT_DIGIT_SIZE_BYTES);
return gsi_true;
}
|