mirrored from https://www.bouncycastle.org/repositories/bc-csharp
-
Notifications
You must be signed in to change notification settings - Fork 594
Expand file tree
/
Copy pathBigInteger.cs
More file actions
3935 lines (3201 loc) · 112 KB
/
BigInteger.cs
File metadata and controls
3935 lines (3201 loc) · 112 KB
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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
#if NETCOREAPP3_0_OR_GREATER
using System.Numerics;
#endif
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
using System.Runtime.InteropServices;
#endif
using System.Runtime.Serialization;
using System.Text;
using Org.BouncyCastle.Crypto.Utilities;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Math
{
[Serializable]
public sealed class BigInteger
: IComparable, IComparable<BigInteger>, IEquatable<BigInteger>
{
// The first few odd primes
/*
3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
233 239 241 251 257 263 269 271 277 281
283 293 307 311 313 317 331 337 347 349
353 359 367 373 379 383 389 397 401 409
419 421 431 433 439 443 449 457 461 463
467 479 487 491 499 503 509 521 523 541
547 557 563 569 571 577 587 593 599 601
607 613 617 619 631 641 643 647 653 659
661 673 677 683 691 701 709 719 727 733
739 743 751 757 761 769 773 787 797 809
811 821 823 827 829 839 853 857 859 863
877 881 883 887 907 911 919 929 937 941
947 953 967 971 977 983 991 997 1009
1013 1019 1021 1031 1033 1039 1049 1051
1061 1063 1069 1087 1091 1093 1097 1103
1109 1117 1123 1129 1151 1153 1163 1171
1181 1187 1193 1201 1213 1217 1223 1229
1231 1237 1249 1259 1277 1279 1283 1289
*/
// Each list has a product < 2^31
internal static readonly int[][] primeLists = new int[][]
{
new int[]{ 3, 5, 7, 11, 13, 17, 19, 23 },
new int[]{ 29, 31, 37, 41, 43 },
new int[]{ 47, 53, 59, 61, 67 },
new int[]{ 71, 73, 79, 83 },
new int[]{ 89, 97, 101, 103 },
new int[]{ 107, 109, 113, 127 },
new int[]{ 131, 137, 139, 149 },
new int[]{ 151, 157, 163, 167 },
new int[]{ 173, 179, 181, 191 },
new int[]{ 193, 197, 199, 211 },
new int[]{ 223, 227, 229 },
new int[]{ 233, 239, 241 },
new int[]{ 251, 257, 263 },
new int[]{ 269, 271, 277 },
new int[]{ 281, 283, 293 },
new int[]{ 307, 311, 313 },
new int[]{ 317, 331, 337 },
new int[]{ 347, 349, 353 },
new int[]{ 359, 367, 373 },
new int[]{ 379, 383, 389 },
new int[]{ 397, 401, 409 },
new int[]{ 419, 421, 431 },
new int[]{ 433, 439, 443 },
new int[]{ 449, 457, 461 },
new int[]{ 463, 467, 479 },
new int[]{ 487, 491, 499 },
new int[]{ 503, 509, 521 },
new int[]{ 523, 541, 547 },
new int[]{ 557, 563, 569 },
new int[]{ 571, 577, 587 },
new int[]{ 593, 599, 601 },
new int[]{ 607, 613, 617 },
new int[]{ 619, 631, 641 },
new int[]{ 643, 647, 653 },
new int[]{ 659, 661, 673 },
new int[]{ 677, 683, 691 },
new int[]{ 701, 709, 719 },
new int[]{ 727, 733, 739 },
new int[]{ 743, 751, 757 },
new int[]{ 761, 769, 773 },
new int[]{ 787, 797, 809 },
new int[]{ 811, 821, 823 },
new int[]{ 827, 829, 839 },
new int[]{ 853, 857, 859 },
new int[]{ 863, 877, 881 },
new int[]{ 883, 887, 907 },
new int[]{ 911, 919, 929 },
new int[]{ 937, 941, 947 },
new int[]{ 953, 967, 971 },
new int[]{ 977, 983, 991 },
new int[]{ 997, 1009, 1013 },
new int[]{ 1019, 1021, 1031 },
new int[]{ 1033, 1039, 1049 },
new int[]{ 1051, 1061, 1063 },
new int[]{ 1069, 1087, 1091 },
new int[]{ 1093, 1097, 1103 },
new int[]{ 1109, 1117, 1123 },
new int[]{ 1129, 1151, 1153 },
new int[]{ 1163, 1171, 1181 },
new int[]{ 1187, 1193, 1201 },
new int[]{ 1213, 1217, 1223 },
new int[]{ 1229, 1231, 1237 },
new int[]{ 1249, 1259, 1277 },
new int[]{ 1279, 1283, 1289 },
};
internal static readonly int[] primeProducts;
private const long IMASK = 0xFFFFFFFFL;
private const ulong UIMASK = 0xFFFFFFFFUL;
private static readonly uint[] ZeroMagnitude = Array.Empty<uint>();
private static readonly byte[] ZeroEncoding = Array.Empty<byte>();
private static readonly BigInteger[] SMALL_CONSTANTS = new BigInteger[17];
public static readonly BigInteger Zero;
public static readonly BigInteger One;
public static readonly BigInteger Two;
public static readonly BigInteger Three;
public static readonly BigInteger Four;
public static readonly BigInteger Five;
public static readonly BigInteger Six;
public static readonly BigInteger Seven;
public static readonly BigInteger Eight;
public static readonly BigInteger Nine;
public static readonly BigInteger Ten;
#if !NETCOREAPP3_0_OR_GREATER
private readonly static byte[] BitLengthTable =
{
0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8
};
#endif
// TODO Parse radix-2 64 bits at a time and radix-8 63 bits at a time
private const int chunk2 = 1, chunk8 = 1, chunk10 = 19, chunk16 = 16;
private static readonly BigInteger radix2, radix2E, radix8, radix8E, radix10, radix10E, radix16, radix16E;
/*
* These are the threshold bit-lengths (of an exponent) where we increase the window size.
* They are calculated according to the expected savings in multiplications.
* Some squares will also be saved on average, but we offset these against the extra storage costs.
*/
private static readonly int[] ExpWindowThresholds = { 7, 25, 81, 241, 673, 1793, 4609, int.MaxValue };
private const int BitsPerByte = 8;
private const int BitsPerInt = 32;
private const int BytesPerInt = 4;
static BigInteger()
{
Zero = new BigInteger(0, ZeroMagnitude, false);
Zero.nBits = 0;
Zero.nBitLength = 0;
SMALL_CONSTANTS[0] = Zero;
for (uint i = 1; i < SMALL_CONSTANTS.Length; ++i)
{
var sc = CreateUValueOf(i);
sc.nBits = Integers.PopCount(i);
sc.nBitLength = BitLen(i);
SMALL_CONSTANTS[i] = sc;
}
One = SMALL_CONSTANTS[1];
Two = SMALL_CONSTANTS[2];
Three = SMALL_CONSTANTS[3];
Four = SMALL_CONSTANTS[4];
Five = SMALL_CONSTANTS[5];
Six = SMALL_CONSTANTS[6];
Seven = SMALL_CONSTANTS[7];
Eight = SMALL_CONSTANTS[8];
Nine = SMALL_CONSTANTS[9];
Ten = SMALL_CONSTANTS[10];
radix2 = Two;
radix2E = radix2.Pow(chunk2);
radix8 = Eight;
radix8E = radix8.Pow(chunk8);
radix10 = Ten;
radix10E = radix10.Pow(chunk10);
radix16 = SMALL_CONSTANTS[16];
radix16E = radix16.Pow(chunk16);
primeProducts = new int[primeLists.Length];
for (int i = 0; i < primeLists.Length; ++i)
{
int[] primeList = primeLists[i];
int product = primeList[0];
for (int j = 1; j < primeList.Length; ++j)
{
product *= primeList[j];
}
primeProducts[i] = product;
}
}
private readonly uint[] magnitude; // array of uints with [0] being the most significant
private readonly int sign; // -1 means -ve; +1 means +ve; 0 means 0;
[NonSerialized]
private int nBits = -1; // cache BitCount() value
[NonSerialized]
private int nBitLength = -1; // cache BitLength() value
[OnDeserialized]
private void OnDeserialized(StreamingContext context)
{
this.nBits = -1;
this.nBitLength = -1;
}
private static int GetBytesLength(int nBits)
{
return (nBits + BitsPerByte - 1) / BitsPerByte;
}
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
private static int GetIntsLength(int nBits)
{
return (nBits + BitsPerInt - 1) / BitsPerInt;
}
#endif
public static BigInteger Arbitrary(int sizeInBits)
{
return new BigInteger(sizeInBits, SecureRandom.ArbitraryRandom);
}
private BigInteger(int signum, uint[] mag, bool checkMag)
{
if (!checkMag)
{
this.sign = signum;
this.magnitude = mag;
return;
}
int i = 0;
while (i < mag.Length && mag[i] == 0)
{
++i;
}
if (i == mag.Length)
{
this.sign = 0;
this.magnitude = ZeroMagnitude;
}
else
{
this.sign = signum;
if (i == 0)
{
this.magnitude = mag;
}
else
{
// strip leading 0 words
this.magnitude = new uint[mag.Length - i];
Array.Copy(mag, i, this.magnitude, 0, this.magnitude.Length);
}
}
}
public BigInteger(string value)
: this(value, 10)
{
}
public BigInteger(string str, int radix)
{
if (str.Length == 0)
throw new FormatException("Zero length BigInteger");
NumberStyles style;
int chunk;
BigInteger r;
BigInteger rE;
switch (radix)
{
case 2:
// Is there anyway to restrict to binary digits?
style = NumberStyles.Integer;
chunk = chunk2;
r = radix2;
rE = radix2E;
break;
case 8:
// Is there anyway to restrict to octal digits?
style = NumberStyles.Integer;
chunk = chunk8;
r = radix8;
rE = radix8E;
break;
case 10:
// This style seems to handle spaces and minus sign already (our processing redundant?)
style = NumberStyles.Integer;
chunk = chunk10;
r = radix10;
rE = radix10E;
break;
case 16:
// TODO Should this be HexNumber?
style = NumberStyles.AllowHexSpecifier;
chunk = chunk16;
r = radix16;
rE = radix16E;
break;
default:
throw new FormatException("Only bases 2, 8, 10, or 16 allowed");
}
int index = 0;
sign = 1;
if (str[0] == '-')
{
if (str.Length == 1)
throw new FormatException("Zero length BigInteger");
sign = -1;
index = 1;
}
// strip leading zeros from the string str
while (index < str.Length && int.Parse(str[index].ToString(), style) == 0)
{
index++;
}
if (index >= str.Length)
{
// zero value - we're done
sign = 0;
magnitude = ZeroMagnitude;
return;
}
//////
// could we work out the max number of ints required to store
// str.Length digits in the given base, then allocate that
// storage in one hit?, then Generate the magnitude in one hit too?
//////
BigInteger b = Zero;
int next = index + chunk;
if (next <= str.Length)
{
do
{
string s = str.Substring(index, chunk);
ulong i = ulong.Parse(s, style);
BigInteger bi = CreateUValueOf(i);
switch (radix)
{
case 2:
// TODO Need this because we are parsing in radix 10 above
if (i >= 2)
throw new FormatException("Bad character in radix 2 string: " + s);
// TODO Parse 64 bits at a time
b = b.ShiftLeft(1);
break;
case 8:
// TODO Need this because we are parsing in radix 10 above
if (i >= 8)
throw new FormatException("Bad character in radix 8 string: " + s);
// TODO Parse 63 bits at a time
b = b.ShiftLeft(3);
break;
case 16:
b = b.ShiftLeft(64);
break;
default:
b = b.Multiply(rE);
break;
}
b = b.Add(bi);
index = next;
next += chunk;
}
while (next <= str.Length);
}
if (index < str.Length)
{
string s = str.Substring(index);
ulong i = ulong.Parse(s, style);
BigInteger bi = CreateUValueOf(i);
if (b.sign > 0)
{
if (radix == 2)
{
// NB: Can't reach here since we are parsing one char at a time
Debug.Assert(false);
// TODO Parse all bits at once
// b = b.ShiftLeft(s.Length);
}
else if (radix == 8)
{
// NB: Can't reach here since we are parsing one char at a time
Debug.Assert(false);
// TODO Parse all bits at once
// b = b.ShiftLeft(s.Length * 3);
}
else if (radix == 16)
{
b = b.ShiftLeft(s.Length << 2);
}
else
{
b = b.Multiply(r.Pow(s.Length));
}
b = b.Add(bi);
}
else
{
b = bi;
}
}
// Note: This is the previous (slower) algorithm
// while (index < value.Length)
// {
// char c = value[index];
// string s = c.ToString();
// int i = int.Parse(s, style);
//
// b = b.Multiply(r).Add(ValueOf(i));
// index++;
// }
magnitude = b.magnitude;
}
public BigInteger(byte[] bytes)
{
this.magnitude = InitBE(bytes, 0, bytes.Length, out this.sign);
}
public BigInteger(byte[] bytes, bool bigEndian)
{
this.magnitude = bigEndian
? InitBE(bytes, 0, bytes.Length, out this.sign)
: InitLE(bytes, 0, bytes.Length, out this.sign);
}
public BigInteger(byte[] bytes, int offset, int length)
{
if (length == 0)
throw new FormatException("Zero length BigInteger");
this.magnitude = InitBE(bytes, offset, length, out this.sign);
}
public BigInteger(byte[] bytes, int offset, int length, bool bigEndian)
{
if (length <= 0)
throw new FormatException("Zero length BigInteger");
this.magnitude = bigEndian
? InitBE(bytes, offset, length, out this.sign)
: InitLE(bytes, offset, length, out this.sign);
}
private static uint[] InitBE(byte[] bytes, int offset, int length, out int sign)
{
// TODO Move this processing into MakeMagnitudeBE (provide sign argument)
if ((sbyte)bytes[offset] >= 0)
{
uint[] magnitude = MakeMagnitudeBE(bytes, offset, length);
sign = magnitude.Length > 0 ? 1 : 0;
return magnitude;
}
sign = -1;
int end = offset + length;
int iBval;
// strip leading sign bytes
for (iBval = offset; iBval < end && ((sbyte)bytes[iBval] == -1); iBval++)
{
}
if (iBval >= end)
return One.magnitude;
int numBytes = end - iBval;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
Span<byte> inverse = numBytes <= 512
? stackalloc byte[numBytes]
: new byte[numBytes];
#else
byte[] inverse = new byte[numBytes];
#endif
int index = 0;
while (index < numBytes)
{
inverse[index++] = (byte)~bytes[iBval++];
}
Debug.Assert(iBval == end);
while (inverse[--index] == byte.MaxValue)
{
inverse[index] = byte.MinValue;
}
inverse[index]++;
return MakeMagnitudeBE(inverse);
}
private static uint[] InitLE(byte[] bytes, int offset, int length, out int sign)
{
int end = offset + length;
// TODO Move this processing into MakeMagnitudeLE (provide sign argument)
if ((sbyte)bytes[end - 1] >= 0)
{
uint[] magnitude = MakeMagnitudeLE(bytes, offset, length);
sign = magnitude.Length > 0 ? 1 : 0;
return magnitude;
}
sign = -1;
// strip leading sign bytes
int last = length;
while (--last >= 0 && bytes[offset + last] == byte.MaxValue)
{
}
if (last < 0)
return One.magnitude;
int numBytes = last + 1;
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
Span<byte> inverse = numBytes <= 512
? stackalloc byte[numBytes]
: new byte[numBytes];
#else
byte[] inverse = new byte[numBytes];
#endif
for (int i = 0; i < numBytes; ++i)
{
inverse[i] = (byte)~bytes[offset + i];
}
int index = 0;
while (inverse[index] == byte.MaxValue)
{
inverse[index++] = byte.MinValue;
}
inverse[index]++;
return MakeMagnitudeLE(inverse);
}
private static uint[] MakeMagnitudeBE(byte[] bytes)
{
return MakeMagnitudeBE(bytes, 0, bytes.Length);
}
private static uint[] MakeMagnitudeBE(byte[] bytes, int offset, int length)
{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
return MakeMagnitudeBE(bytes.AsSpan(offset, length));
#else
int end = offset + length;
// strip leading zeros
int start;
for (start = offset; start < end && bytes[start] == 0; start++)
{
}
int nBytes = end - start;
if (nBytes <= 0)
return ZeroMagnitude;
int nInts = (nBytes + BytesPerInt - 1) / BytesPerInt;
Debug.Assert(nInts > 0);
uint[] magnitude = new uint[nInts];
int first = ((nBytes - 1) % BytesPerInt) + 1;
magnitude[0] = Pack.BE_To_UInt32_Low(bytes, start, first);
Pack.BE_To_UInt32(bytes, start + first, magnitude, 1, nInts - 1);
return magnitude;
#endif
}
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
private static uint[] MakeMagnitudeBE(ReadOnlySpan<byte> bytes)
{
int end = bytes.Length;
// strip leading zeros
int start;
for (start = 0; start < end && bytes[start] == 0; start++)
{
}
int nBytes = end - start;
if (nBytes <= 0)
return ZeroMagnitude;
int nInts = (nBytes + BytesPerInt - 1) / BytesPerInt;
Debug.Assert(nInts > 0);
uint[] magnitude = new uint[nInts];
int first = ((nBytes - 1) % BytesPerInt) + 1;
magnitude[0] = Pack.BE_To_UInt32_Low(bytes.Slice(start, first));
Pack.BE_To_UInt32(bytes.Slice(start + first), magnitude.AsSpan(1));
return magnitude;
}
#endif
private static uint[] MakeMagnitudeLE(byte[] bytes)
{
return MakeMagnitudeLE(bytes, 0, bytes.Length);
}
private static uint[] MakeMagnitudeLE(byte[] bytes, int offset, int length)
{
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
return MakeMagnitudeLE(bytes.AsSpan(offset, length));
#else
// strip leading zeros
int last = length;
while (--last >= 0 && bytes[offset + last] == 0)
{
}
if (last < 0)
return ZeroMagnitude;
int nInts = (last + BytesPerInt) / BytesPerInt;
Debug.Assert(nInts > 0);
uint[] magnitude = new uint[nInts];
int partial = last % BytesPerInt;
int first = partial + 1;
int pos = offset + last - partial;
magnitude[0] = Pack.LE_To_UInt32_Low(bytes, pos, first);
for (int i = 1; i < nInts; ++i)
{
pos -= BytesPerInt;
magnitude[i] = Pack.LE_To_UInt32(bytes, pos);
}
Debug.Assert(pos == offset);
return magnitude;
#endif
}
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
private static uint[] MakeMagnitudeLE(ReadOnlySpan<byte> bytes)
{
// strip leading zeros
int last = bytes.Length;
while (--last >= 0 && bytes[last] == 0)
{
}
if (last < 0)
return ZeroMagnitude;
int nInts = (last + BytesPerInt) / BytesPerInt;
Debug.Assert(nInts > 0);
uint[] magnitude = new uint[nInts];
int partial = last % BytesPerInt;
int first = partial + 1;
int pos = last - partial;
magnitude[0] = Pack.LE_To_UInt32_Low(bytes.Slice(pos, first));
for (int i = 1; i < nInts; ++i)
{
pos -= BytesPerInt;
magnitude[i] = Pack.LE_To_UInt32(bytes, pos);
}
Debug.Assert(pos == 0);
return magnitude;
}
#endif
public BigInteger(int sign, byte[] bytes)
: this(sign, bytes, 0, bytes.Length, true)
{
}
public BigInteger(int sign, byte[] bytes, bool bigEndian)
: this(sign, bytes, 0, bytes.Length, bigEndian)
{
}
public BigInteger(int sign, byte[] bytes, int offset, int length)
: this(sign, bytes, offset, length, true)
{
}
public BigInteger(int sign, byte[] bytes, int offset, int length, bool bigEndian)
{
if (sign < -1 || sign > 1)
throw new FormatException("Invalid sign value");
if (sign == 0)
{
this.sign = 0;
this.magnitude = ZeroMagnitude;
}
else
{
// copy bytes
this.magnitude = bigEndian
? MakeMagnitudeBE(bytes, offset, length)
: MakeMagnitudeLE(bytes, offset, length);
this.sign = this.magnitude.Length < 1 ? 0 : sign;
}
}
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
public BigInteger(int sign, ReadOnlySpan<byte> bytes)
: this(sign, bytes, true)
{
}
public BigInteger(int sign, ReadOnlySpan<byte> bytes, bool bigEndian)
{
if (sign < -1 || sign > 1)
throw new FormatException("Invalid sign value");
if (sign == 0)
{
this.sign = 0;
this.magnitude = ZeroMagnitude;
}
else
{
// copy bytes
this.magnitude = bigEndian
? MakeMagnitudeBE(bytes)
: MakeMagnitudeLE(bytes);
this.sign = this.magnitude.Length < 1 ? 0 : sign;
}
}
#endif
public BigInteger(int sizeInBits, Random random)
{
if (sizeInBits < 0)
throw new ArgumentException("sizeInBits must be non-negative");
this.nBits = -1;
this.nBitLength = -1;
if (sizeInBits == 0)
{
this.sign = 0;
this.magnitude = ZeroMagnitude;
return;
}
int nBytes = GetBytesLength(sizeInBits);
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
Span<byte> b = nBytes <= 512
? stackalloc byte[nBytes]
: new byte[nBytes];
#else
byte[] b = new byte[nBytes];
#endif
random.NextBytes(b);
// strip off any excess bits in the MSB
int xBits = BitsPerByte * nBytes - sizeInBits;
b[0] &= (byte)(255U >> xBits);
this.magnitude = MakeMagnitudeBE(b);
this.sign = this.magnitude.Length < 1 ? 0 : 1;
}
public BigInteger(int bitLength, int certainty, Random random)
{
if (bitLength < 2)
throw new ArithmeticException("bitLength < 2");
this.sign = 1;
this.nBitLength = bitLength;
if (bitLength == 2)
{
this.magnitude = random.Next(2) == 0
? Two.magnitude
: Three.magnitude;
return;
}
int nBytes = GetBytesLength(bitLength);
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
Span<byte> b = nBytes <= 512
? stackalloc byte[nBytes]
: new byte[nBytes];
#else
byte[] b = new byte[nBytes];
#endif
int xBits = BitsPerByte * nBytes - bitLength;
byte mask = (byte)(255U >> xBits);
byte lead = (byte)(1 << (7 - xBits));
for (;;)
{
random.NextBytes(b);
// strip off any excess bits in the MSB
b[0] &= mask;
// ensure the leading bit is 1 (to meet the strength requirement)
b[0] |= lead;
// ensure the trailing bit is 1 (i.e. must be odd)
b[nBytes - 1] |= 1;
this.magnitude = MakeMagnitudeBE(b);
this.nBits = -1;
if (certainty < 1)
break;
if (CheckProbablePrime(certainty, random, true))
break;
for (int j = 1; j < (magnitude.Length - 1); ++j)
{
this.magnitude[j] ^= (uint)random.Next();
if (CheckProbablePrime(certainty, random, true))
return;
}
}
}
public BigInteger Abs()
{
return sign >= 0 ? this : Negate();
}
/**
* return a = a + b - b preserved.
*/
private static uint[] AddMagnitudes(uint[] a, uint[] b)
{
int tI = a.Length - 1;
int vI = b.Length - 1;
ulong m = 0;
while (vI >= 0)
{
m += (ulong)a[tI] + b[vI--];
a[tI--] = (uint)m;
m >>= 32;
}
if (m != 0)
{
while (tI >= 0 && ++a[tI--] == uint.MinValue)
{
}
}
return a;
}
public BigInteger Add(BigInteger value)
{
if (this.sign == 0)
return value;
if (this.sign == value.sign)
return AddToMagnitude(value.magnitude);
if (value.sign == 0)
return this;
if (value.sign < 0)
return Subtract(value.Negate());
return value.Subtract(Negate());
}
private BigInteger AddToMagnitude(uint[] magToAdd)
{
uint[] big, small;
if (this.magnitude.Length < magToAdd.Length)
{
big = magToAdd;
small = this.magnitude;
}
else
{
big = this.magnitude;
small = magToAdd;
}
// Conservatively avoid over-allocation when no overflow possible
uint limit = uint.MaxValue;
if (big.Length == small.Length)
{
limit -= small[0];
}
bool possibleOverflow = big[0] >= limit;
uint[] bigCopy;
if (possibleOverflow)
{
bigCopy = new uint[big.Length + 1];
big.CopyTo(bigCopy, 1);
}
else
{
bigCopy = (uint[])big.Clone();
}