forked from OpenCryptoProject/JCMathLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjcmathlib_v1.0.1.java
4063 lines (3606 loc) · 192 KB
/
jcmathlib_v1.0.1.java
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
// Merged file class by JavaPresso (https://github.com/petrs/JavaPresso)
// TODO: Change 'your_package' to your real package name as necessary
// TODO: Add 'import your_package.jcmathlib.*;' to access all classes as usual
package your_package;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.Util;
import javacard.security.CryptoException;
import javacard.security.ECPrivateKey;
import javacard.security.ECPublicKey;
import javacard.security.KeyAgreement;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;
import javacard.security.MessageDigest;
import javacard.security.RSAPublicKey;
import javacard.security.Signature;
import javacardx.crypto.Cipher;
public class jcmathlib {
/**
*
* @author Petr Svenda
*/
public static class Base_Helper {
final ResourceManager rm;
/**
* Helper flag which signalizes that code is executed inside simulator
* (during tests). Is used to address simulator specific behaviour
* workaround if required.
*/
public boolean bIsSimulator = false;
public Base_Helper(ResourceManager resman) {
rm = resman;
}
/**
* Lock/reserve provided object for subsequent use. Used to protect
* corruption of pre-allocated shared objects in different, potentially
* nested, operations. Must be unlocked later on.
*
* @param objToLock array to be locked
* @throws SW_ALREADYLOCKED if already locked (is already in use by other
* operation)
*/
/*
public void lock(Object objToLock) {
rm.locker.lock(objToLock);
}
*/
public void lock(byte[] objToLock) {
rm.locker.lock(objToLock);
}
/**
* Unlock/release object from use. Used to protect corruption of
* pre-allocated objects used in different nested operations. Must be locked
* before.
*
* @param objToUnlock object to unlock
* @throws SW_NOTLOCKED_BIGNAT if was not locked before (inconsistence in
* lock/unlock sequence)
*/
/*
public void unlock(Object objToUnlock) {
rm.locker.unlock(objToUnlock);
}
*/
public void unlock(byte[] objToUnlock) {
rm.locker.unlock(objToUnlock);
}
/**
* Unlocks all locked objects
*/
public void unlockAll() {
rm.locker.unlockAll();
}
/**
* Check if provided object is logically locked
*
* @param objToUnlock object to be checked
* @return true of array is logically locked, false otherwise
*/
/*
public boolean isLocked(Object objToUnlock) {
return rm.locker.isLocked(objToUnlock);
}
*/
/**
* Allocates new byte[] array with provided length either in RAM or EEPROM
* based on an allocator type. Method updates internal counters of bytes
* allocated with specific allocator. Use {@code getAllocatedInRAM()} or
* {@code getAllocatedInEEPROM} for counters readout.
*
* @param length length of array
* @param allocatorType type of allocator
* @return allocated array
*/
public byte[] allocateByteArray(short length, byte allocatorType) {
return rm.memAlloc.allocateByteArray(length, allocatorType);
}
}
/**
* Credits: Based on Bignat library from OV-chip project https://ovchip.cs.ru.nl/OV-chip_2.0 by Radboud University Nijmegen
*/
/**
*
* @author Vasilios Mavroudis and Petr Svenda
*/
public static class Bignat {
private final Bignat_Helper bnh;
/**
* Configuration flag controlling re-allocation of internal array. If true, internal Bignat buffer can be enlarged during clone
* operation if required (keep false to prevent slow reallocations)
*/
boolean ALLOW_RUNTIME_REALLOCATION = false;
/**
* Configuration flag controlling clearing of shared Bignats on lock as prevention of unwanted leak of sensitive information from previous operation.
* If true, internal storage array is erased once Bignat is locked for use
*/
boolean ERASE_ON_LOCK = false;
/**
* Configuration flag controlling clearing of shared Bignats on unlock as
* prevention of unwanted leak of sensitive information to next operation.
* If true, internal storage array is erased once Bignat is unlocked from use
*/
boolean ERASE_ON_UNLOCK = false;
/**
* Factor for converting digit size into short length. 1 for the short/short
* converting, 4 for the int/long configuration.
*
*/
public static final short size_multiplier = 1;
/**
* Bitmask for extracting a digit out of a longer int/short value. short
* 0xff for the short/short configuration, long 0xffffffffL the int/long
* configuration.
*/
public static final short digit_mask = 0xff;
/**
* Bitmask for the highest bit in a digit. short 0x80 for the short/short
* configuration, long 0x80000000 for the int/long configuration.
*
*/
public static final short digit_first_bit_mask = 0x80;
/**
* Bitmask for the second highest bit in a digit. short 0x40 for the
* short/short configuration, long 0x40000000 for the int/long
* configuration.
*
*/
public static final short digit_second_bit_mask = 0x40;
/**
* Bitmask for the two highest bits in a digit. short 0xC0 for the
* short/short configuration, long 0xC0000000 for the int/long
* configuration.
*
*/
public static final short digit_first_two_bit_mask = 0xC0;
/**
* Size in bits of one digit. 8 for the short/short configuration, 32 for
* the int/long configuration.
*/
public static final short digit_len = 8;
/**
* Size in bits of a double digit. 16 for the short/short configuration, 64
* for the int/long configuration.
*/
private static final short double_digit_len = 16;
/**
* Bitmask for erasing the sign bit in a double digit. short 0x7fff for the
* short/short configuration, long 0x7fffffffffffffffL for the int/long
* configuration.
*/
private static final short positive_double_digit_mask = 0x7fff;
/**
* Bitmask for the highest bit in a double digit.
*/
public static final short highest_digit_bit = (short) (1L << (digit_len - 1));
/**
* The base as a double digit. The base is first value that does not fit
* into a single digit. 2^8 for the short/short configuration and 2^32 for
* the int/long configuration.
*/
public static final short bignat_base = (short) (1L << digit_len);
/**
* Bitmask with just the highest bit in a double digit.
*/
public static final short highest_double_digit_bit = (short) (1L << (double_digit_len - 1));
/**
* Digit array. Elements have type byte.
*/
/**
* Internal storage array for this Bignat. The current version uses byte array with
* intermediate values stored which can be quickly processed with
*/
private byte[] value;
private short size = -1; // Current size of stored Bignat. Current number is encoded in first {@code size} of value array, starting from value[0]
private short max_size = -1; // Maximum size of this Bignat. Corresponds to value.length
private byte allocatorType = JCSystem.MEMORY_TYPE_PERSISTENT; // Memory storage type for value buffer
private boolean bLocked = false; // Logical flag to store info if this Bignat is currently used for some operation. Used as a prevention of unintentional parallel use of same temporary pre-allocated Bignats.
/**
* Construct a Bignat of size {@code size} in shorts. Allocated in EEPROM or RAM based on
* {@code allocatorType}. JCSystem.MEMORY_TYPE_PERSISTENT, in RAM otherwise.
*
* @param size the size of the new Bignat in bytes
* @param allocatorType type of allocator storage
* JCSystem.MEMORY_TYPE_PERSISTENT => EEPROM (slower writes, but RAM is saved)
* JCSystem.MEMORY_TYPE_TRANSIENT_RESET => RAM
* JCSystem.MEMORY_TYPE_TRANSIENT_DESELECT => RAM
* @param bignatHelper {@code Bignat_Helper} class with helper objects
*/
public Bignat(short size, byte allocatorType, Bignat_Helper bignatHelper) {
this.bnh = bignatHelper;
allocate_storage_array(size, allocatorType);
}
/**
* Construct a Bignat with provided array used as internal storage as well as initial value.
* No copy of array is made. If this Bignat is used in operation which modifies the Bignat value,
* content of provided array is changed.
* @param valueBuffer internal storage
* @param bignatHelper {@code Bignat_Helper} class with all relevant settings and helper objects
*/
public Bignat(byte[] valueBuffer, Bignat_Helper bignatHelper) {
this.bnh = bignatHelper;
this.size = (short) valueBuffer.length;
this.max_size = (short) valueBuffer.length;
this.allocatorType = -1; // no allocator
this.value = valueBuffer;
}
/**
* Lock/reserve this bignat for subsequent use.
* Used to protect corruption of pre-allocated temporary Bignats used in different,
* potentially nested operations. Must be unlocked by {@code unlock()} later on.
* @throws SW_ALREADYLOCKED_BIGNAT if already locked (is already in use by other operation)
*/
public void lock() {
if (!bLocked) {
bLocked = true;
if (ERASE_ON_LOCK) {
erase();
}
}
else {
// this Bignat is already locked, raise exception (incorrect sequence of locking and unlocking)
ISOException.throwIt(ReturnCodes.SW_LOCK_ALREADYLOCKED);
}
}
/**
* Unlock/release this bignat from use. Used to protect corruption
* of pre-allocated temporary Bignats used in different nested operations.
* Must be locked before.
*
* @throws SW_NOTLOCKED_BIGNAT if was not locked before (inconsistence in lock/unlock sequence)
*/
public void unlock() {
if (bLocked) {
bLocked = false;
if (ERASE_ON_UNLOCK) {
erase();
}
} else {
// this Bignat is not locked, raise exception (incorrect sequence of locking and unlocking)
ISOException.throwIt(ReturnCodes.SW_LOCK_NOTLOCKED);
}
}
/**
* Return current state of logical lock of this object
* @return true if object is logically locked (reserved), false otherwise
*/
public boolean isLocked() {
return bLocked;
}
/**
* Return this Bignat as byte array. For the short/short configuration
* simply the digit array is returned. For other configurations a new short
* array is allocated and returned. Modifying the returned short array
* therefore might or might not change this bignat.
* IMPORTANT: this function returns directly the underlying storage array.
* Current value of this Bignat can be stored in smaller number of bytes.
* Use {@code getLength()} method to obtain actual size.
*
* @return this bignat as byte array
*/
public byte[] as_byte_array() {
return value;
}
/**
* Serialize this Bignat value into a provided buffer
* @param buffer target buffer
* @param bufferOffset start offset in buffer
* @return number of bytes copied
*/
public short copy_to_buffer(byte[] buffer, short bufferOffset) {
Util.arrayCopyNonAtomic(value, (short) 0, buffer, bufferOffset, size);
return size;
}
/**
* Return the size in digits. Provides access to the internal {@link #size}
* field.
* <P>
* The return value is adjusted by {@link #set_size}.
*
* @return size in digits.
*/
public short length() {
return size;
}
/**
* Sets internal size of Bignat. Previous value are kept so value is either non-destructively trimmed or enlarged.
* @param newSize new size of Bignat. Must be in range of [0, max_size] where max_size was provided during object creation
*/
public void set_size(short newSize) {
if (newSize < 0 || newSize > max_size) {
ISOException.throwIt(ReturnCodes.SW_BIGNAT_RESIZETOLONGER);
}
else {
this.size = newSize;
}
}
/**
* Resize internal length of this Bignat to maximum size given during object
* creation. If required, object is also zeroized
*
* @param bZeroize if true, all bytes of internal array are also set to
* zero. If false, previous value is kept.
*/
public void resize_to_max(boolean bZeroize) {
set_size(max_size);
if (bZeroize) {
zero();
}
}
/**
* Create Bignat with different number of bytes used. Will cause longer number
* to shrink (loss of the more significant bytes) and shorter to be prepended with zeroes
*
* @param new_size new size in bytes
*/
void deep_resize(short new_size) {
if (new_size > this.max_size) {
if (ALLOW_RUNTIME_REALLOCATION) {
allocate_storage_array(new_size, this.allocatorType);
} else {
ISOException.throwIt(ReturnCodes.SW_BIGNAT_REALLOCATIONNOTALLOWED); // Reallocation to longer size not permitted
}
}
if (new_size == this.size) {
// No need to resize enything, same length
}
else {
short this_start, other_start, len;
bnh.lock(bnh.fnc_deep_resize_tmp);
if (this.size >= new_size) {
this_start = (short) (this.size - new_size);
other_start = 0;
len = new_size;
// Shrinking/cropping
Util.arrayCopyNonAtomic(value, this_start, bnh.fnc_deep_resize_tmp, (short) 0, len);
Util.arrayCopyNonAtomic(bnh.fnc_deep_resize_tmp, (short) 0, value, (short) 0, len); // Move bytes in item array towards beggining
// Erase rest of allocated array with zeroes (just as sanitization)
short toErase = (short) (this.max_size - new_size);
if (toErase > 0) {
Util.arrayFillNonAtomic(value, new_size, toErase, (byte) 0);
}
} else {
this_start = 0;
other_start = (short) (new_size - this.size);
len = this.size;
// Enlarging => Insert zeroes at begging, move bytes in item array towards the end
Util.arrayCopyNonAtomic(value, this_start, bnh.fnc_deep_resize_tmp, (short) 0, len);
// Move bytes in item array towards end
Util.arrayCopyNonAtomic(bnh.fnc_deep_resize_tmp, (short) 0, value, other_start, len);
// Fill begin of array with zeroes (just as sanitization)
if (other_start > 0) {
Util.arrayFillNonAtomic(value, (short) 0, other_start, (byte) 0);
}
}
bnh.unlock(bnh.fnc_deep_resize_tmp);
set_size(new_size);
}
}
/**
* Appends zeros in the suffix to reach the defined byte length
* Essentially multiplies the number with 16 (HEX)
* @param targetLength required length including appended zeroes
* @param outBuffer output buffer for value with appended zeroes
* @param outOffset start offset inside outBuffer for write
*/
public void append_zeros(short targetLength, byte[] outBuffer, short outOffset) {
Util.arrayCopyNonAtomic(value, (short) 0, outBuffer, outOffset, this.size); //copy the value
Util.arrayFillNonAtomic(outBuffer, (short) (outOffset + this.size), (short) (targetLength - this.size), (byte) 0); //append zeros
}
/**
* Prepends zeros before the value of this Bignat up to target length.
*
* @param targetLength required length including prepended zeroes
* @param outBuffer output buffer for value with prepended zeroes
* @param outOffset start offset inside outBuffer for write
*/
public void prepend_zeros(short targetLength, byte[] outBuffer, short outOffset) {
short other_start = (short) (targetLength - this.size);
if (other_start > 0) {
Util.arrayFillNonAtomic(outBuffer, outOffset, other_start, (byte) 0); //fill prefix with zeros
}
Util.arrayCopyNonAtomic(value, (short) 0, outBuffer, (short) (outOffset + other_start), this.size); //copy the value
}
/**
* Remove leading zeroes (if any) from Bignat value and decrease size accordingly
*/
public void shrink() {
short i = 0;
for (i = 0; i < this.length(); i++) { // Find first non-zero byte
if (this.value[i] != 0) {
break;
}
}
short new_size = (short)(this.size-i);
if (new_size < 0) {
ISOException.throwIt(ReturnCodes.SW_BIGNAT_INVALIDRESIZE);
}
this.deep_resize(new_size);
}
/**
* Stores zero in this object for currently used subpart given by internal size.
*/
public void zero() {
Util.arrayFillNonAtomic(value, (short) 0, this.size, (byte) 0);
}
/**
* Stores zero in this object for whole internal buffer regardless of current size.
*/
public void zero_complete() {
Util.arrayFillNonAtomic(value, (short) 0, (short) value.length, (byte) 0);
}
/**
* Erase value stored inside this Bignat
*/
public void erase() {
zero_complete();
}
/**
* Stores one in this object. Keeps previous size of this Bignat
* (1 is prepended with required number of zeroes).
*/
public void one() {
this.zero();
value[(short) (size - 1)] = 1;
}
/**
* Stores two in this object. Keeps previous size of this Bignat (2 is
* prepended with required number of zeroes).
*/
public void two() {
this.zero();
value[(short) (size - 1)] = 0x02;
}
public void three() {
this.zero();
value[(short) (size - 1)] = 0x03;
}
public void four() {
this.zero();
value[(short) (size - 1)] = 0x04;
}
public void five() {
this.zero();
value[(short) (size - 1)] = 0x05;
}
public void eight() {
this.zero();
value[(short) (size - 1)] = 0x08;
}
public void ten() {
this.zero();
value[(short) (size - 1)] = 0x0A;
}
public void twentyfive() {
this.zero();
value[(short)(size-1)] = 0x19;
}
public void twentyseven() {
this.zero();
value[(short)(size-1)] = 0x1B;
}
public void athousand() {
this.zero();
value[(short)(size-2)] = (byte)0x03;
value[(short)(size-1)] = (byte)0xE8;
}
/**
* Copies {@code other} into this. No size requirements. If {@code other}
* has more digits then the superfluous leading digits of {@code other} are
* asserted to be zero. If this bignat has more digits than its leading
* digits are correctly initilized to zero. This function will not change size
* attribute of this object.
*
* @param other
* Bignat to copy into this object.
*/
public void copy(Bignat other) {
short this_start, other_start, len;
if (this.size >= other.size) {
this_start = (short) (this.size - other.size);
other_start = 0;
len = other.size;
} else {
this_start = 0;
other_start = (short) (other.size - this.size);
len = this.size;
// Verify here that other have leading zeroes up to other_start
for (short i = 0; i < other_start; i ++) {
if (other.value[i] != 0) {
ISOException.throwIt(ReturnCodes.SW_BIGNAT_INVALIDCOPYOTHER);
}
}
}
if (this_start > 0) {
// if this bignat has more digits than its leading digits are initilized to zero
Util.arrayFillNonAtomic(this.value, (short) 0, this_start, (byte) 0);
}
Util.arrayCopyNonAtomic(other.value, other_start, this.value, this_start, len);
}
/**
* Copies content of {@code other} into this and set size of this to {@code other}.
* The size attribute (returned by length()) is updated. If {@code other}
* is longer than maximum capacity of this, internal buffer is reallocated if enabled
* (ALLOW_RUNTIME_REALLOCATION), otherwise exception is thrown.
* @param other
* Bignat to clone into this object.
*/
public void clone(Bignat other) {
// Reallocate array only if current array cannot store the other value and reallocation is enabled by ALLOW_RUNTIME_REALLOCATION
if (this.max_size < other.length()) {
// Reallocation necessary
if (ALLOW_RUNTIME_REALLOCATION) {
allocate_storage_array(other.length(), this.allocatorType);
}
else {
ISOException.throwIt(ReturnCodes.SW_BIGNAT_REALLOCATIONNOTALLOWED);
}
}
// copy value from other into proper place in this (this can be longer than other so rest of bytes wil be filled with 0)
other.copy_to_buffer(this.value, (short) 0);
if (this.max_size > other.length()) {
Util.arrayFillNonAtomic(this.value, other.length(), (short) (this.max_size - other.length()), (byte) 0);
}
this.size = other.length();
}
/**
* Equality check. Requires that this object and other have the same size or are padded with zeroes.
* Returns true if all digits (except for leading zeroes) are equal.
*
*
* @param other Bignat to compare
* @return true if this and other have the same value, false otherwise.
*/
public boolean same_value(Bignat other) {
short hashLen;
// Compare using hash engine
// The comparison is made with hash of point values instead of directly values.
// This way, offset of first mismatching byte is not leaked via timing side-channel.
bnh.lock(bnh.fnc_same_value_array1);
bnh.lock(bnh.fnc_same_value_hash);
if (this.length() == other.length()) {
// Same length, we can hash directly from BN values
bnh.hashEngine.doFinal(this.value, (short) 0, this.length(), bnh.fnc_same_value_hash, (short) 0);
hashLen = bnh.hashEngine.doFinal(other.value, (short) 0, other.length(), bnh.fnc_same_value_array1, (short) 0);
}
else {
// Different length of bignats - can be still same if prepended with zeroes
// Find the length of longer one and padd other one with starting zeroes
if (this.length() < other.length()) {
this.prepend_zeros(other.length(), bnh.fnc_same_value_array1, (short) 0);
bnh.hashEngine.doFinal(bnh.fnc_same_value_array1, (short) 0, other.length(), bnh.fnc_same_value_hash, (short) 0);
hashLen = bnh.hashEngine.doFinal(other.value, (short) 0, other.length(), bnh.fnc_same_value_array1, (short) 0);
}
else {
other.prepend_zeros(this.length(), bnh.fnc_same_value_array1, (short) 0);
bnh.hashEngine.doFinal(bnh.fnc_same_value_array1, (short) 0, this.length(), bnh.fnc_same_value_hash, (short) 0);
hashLen = bnh.hashEngine.doFinal(this.value, (short) 0, this.length(), bnh.fnc_same_value_array1, (short) 0);
}
}
boolean bResult = Util.arrayCompare(bnh.fnc_same_value_hash, (short) 0, bnh.fnc_same_value_array1, (short) 0, hashLen) == 0;
bnh.unlock(bnh.fnc_same_value_array1);
bnh.unlock(bnh.fnc_same_value_hash);
return bResult;
}
/**
* Addition of big integers x and y stored in byte arrays with specified offset and length.
* The result is stored into x array argument.
* @param x array with first bignat
* @param xOffset start offset in array of {@code x}
* @param xLength length of {@code x}
* @param y array with second bignat
* @param yOffset start offset in array of {@code y}
* @param yLength length of {@code y}
* @return true if carry of most significant byte occurs, false otherwise
*/
public static boolean add(byte[] x, short xOffset, short xLength, byte[] y,
short yOffset, short yLength) {
short result = 0;
short i = (short) (xLength + xOffset - 1);
short j = (short) (yLength + yOffset - 1);
for (; i >= xOffset && j >= 0; i--, j--) {
result = (short) (result + (short) (x[i] & digit_mask) + (short) (y[j] & digit_mask));
x[i] = (byte) (result & digit_mask);
result = (short) ((result >> digit_len) & digit_mask);
}
while (result > 0 && i >= xOffset) {
result = (short) (result + (short) (x[i] & digit_mask));
x[i] = (byte) (result & digit_mask);
result = (short) ((result >> digit_len) & digit_mask);
i--;
}
return result != 0;
}
/**
* Subtracts big integer y from x specified by offset and length.
* The result is stored into x array argument.
* @param x array with first bignat
* @param xOffset start offset in array of {@code x}
* @param xLength length of {@code x}
* @param y array with second bignat
* @param yOffset start offset in array of {@code y}
* @param yLength length of {@code y}
* @return true if carry of most significant byte occurs, false otherwise
*/
public static boolean subtract(byte[] x, short xOffset, short xLength, byte[] y,
short yOffset, short yLength) {
short i = (short) (xLength + xOffset - 1);
short j = (short) (yLength + yOffset - 1);
short carry = 0;
short subtraction_result = 0;
for (; i >= xOffset && j >= yOffset; i--, j--) {
subtraction_result = (short) ((x[i] & digit_mask) - (y[j] & digit_mask) - carry);
x[i] = (byte) (subtraction_result & digit_mask);
carry = (short) (subtraction_result < 0 ? 1 : 0);
}
for (; i >= xOffset && carry > 0; i--) {
if (x[i] != 0) {
carry = 0;
}
x[i] -= 1;
}
return carry > 0;
}
/**
* Substract provided other bignat from this bignat.
* @param other bignat to be substracted from this
*/
public void subtract(Bignat other) {
this.times_minus(other, (short) 0, (short) 1);
}
/**
* Scaled subtraction. Subtracts {@code mult * 2^(}{@link #digit_len}
* {@code * shift) * other} from this.
* <P>
* That is, shifts {@code mult * other} precisely {@code shift} digits to
* the left and subtracts that value from this. {@code mult} must be less
* than {@link #bignat_base}, that is, it must fit into one digit. It is
* only declared as short here to avoid negative values.
* <P>
* {@code mult} has type short.
* <P>
* No size constraint. However, an assertion is thrown, if the result would
* be negative. {@code other} can have more digits than this object, but
* then sufficiently many leading digits must be zero to avoid the
* underflow.
* <P>
* Used in division.
*
* @param other
* Bignat to subtract from this object
* @param shift
* number of digits to shift {@code other} to the left
* @param mult
* of type short, multiple of {@code other} to subtract from this
* object. Must be below {@link #bignat_base}.
*/
public void times_minus(Bignat other, short shift, short mult) {
short akku = 0;
short subtraction_result;
short i = (short) (this.size - 1 - shift);
short j = (short) (other.size - 1);
for (; i >= 0 && j >= 0; i--, j--) {
akku = (short) (akku + (short) (mult * (other.value[j] & digit_mask)));
subtraction_result = (short) ((value[i] & digit_mask) - (akku & digit_mask));
value[i] = (byte) (subtraction_result & digit_mask);
akku = (short) ((akku >> digit_len) & digit_mask);
if (subtraction_result < 0) {
akku++;
}
}
// deal with carry as long as there are digits left in this
while (i >= 0 && akku != 0) {
subtraction_result = (short) ((value[i] & digit_mask) - (akku & digit_mask));
value[i] = (byte) (subtraction_result & digit_mask);
akku = (short) ((akku >> digit_len) & digit_mask);
if (subtraction_result < 0) {
akku++;
}
i--;
}
}
/**
* Quick function for decrement of this bignat value by 1. Faster than {@code substract(Bignat.one())}
*/
public void decrement_one() {
short tmp = 0;
for (short i = (short) (this.size - 1); i >= 0; i--) {
tmp = (short) (this.value[i] & 0xff);
this.value[i] = (byte) (tmp - 1);
if (tmp != 0) {
break; // CTO
}
else {
// need to modify also one byte up, continue with cycle
}
}
}
/**
* Quick function for increment of this bignat value by 1. Faster than
* {@code add(Bignat.one())}
*/
public void increment_one() {
short tmp = 0;
for (short i = (short) (this.size - 1); i >= 0; i--) {
tmp = (short) (this.value[i] & 0xff);
this.value[i] = (byte) (tmp + 1);
if (tmp < 255) {
break; // CTO
} else {
// need to modify also one byte up (carry) , continue with cycle
}
}
}
/**
* Index of the most significant 1 bit.
* <P>
* {@code x} has type short.
* <P>
* Utility method, used in division.
*
* @param x
* of type short
* @return index of the most significant 1 bit in {@code x}, returns
* {@link #double_digit_len} for {@code x == 0}.
*/
private static short highest_bit(short x) {
for (short i = 0; i < double_digit_len; i++) {
if (x < 0) {
return i;
}
x <<= 1;
}
return double_digit_len;
}
/**
* Shift to the left and fill. Takes {@code high} {@code middle} {@code low}
* as 4 digits, shifts them {@code shift} bits to the left and returns the
* most significant {@link #double_digit_len} bits.
* <P>
* Utility method, used in division.
*
*
* @param high
* of type short, most significant {@link #double_digit_len} bits
* @param middle
* of type byte, middle {@link #digit_len} bits
* @param low
* of type byte, least significant {@link #digit_len} bits
* @param shift
* amount of left shift
* @return most significant {@link #double_digit_len} as short
*/
private static short shift_bits(short high, byte middle, byte low,
short shift) {
// shift high
high <<= shift;
// merge middle bits
byte mask = (byte) (digit_mask << (shift >= digit_len ? 0 : digit_len
- shift));
short bits = (short) ((short) (middle & mask) & digit_mask);
if (shift > digit_len) {
bits <<= shift - digit_len;
}
else {
bits >>>= digit_len - shift;
}
high |= bits;
if (shift <= digit_len) {
return high;
}
// merge low bits
mask = (byte) (digit_mask << double_digit_len - shift);
bits = (short) ((((short) (low & mask) & digit_mask) >> double_digit_len - shift));
high |= bits;
return high;
}
/**
* Scaled comparison. Compares this number with {@code other * 2^(}
* {@link #digit_len} {@code * shift)}. That is, shifts {@code other}
* {@code shift} digits to the left and compares then. This bignat and
* {@code other} will not be modified inside this method.
* <P>
*
* As optimization {@code start} can be greater than zero to skip the first
* {@code start} digits in the comparison. These first digits must be zero
* then, otherwise an assertion is thrown. (So the optimization takes only
* effect when <a
* href="../../../overview-summary.html#NO_CARD_ASSERT">NO_CARD_ASSERT</a>
* is defined.)
*
* @param other
* Bignat to compare to
* @param shift
* left shift of other before the comparison
* @param start
* digits to skip at the beginning
* @return true if this number is strictly less than the shifted
* {@code other}, false otherwise.
*/
public boolean shift_lesser(Bignat other, short shift, short start) {
short j;
j = (short) (other.size + shift - this.size + start);
short this_short, other_short;
for (short i = start; i < this.size; i++, j++) {
this_short = (short) (this.value[i] & digit_mask);
if (j >= 0 && j < other.size) {
other_short = (short) (other.value[j] & digit_mask);
}
else {
other_short = 0;
}
if (this_short < other_short) {
return true; // CTO
}
if (this_short > other_short) {
return false;
}
}
return false;
}
/**
* Compares this and other bignat.
* @param other other value to compare with
* @return true if this bignat is smaller, false if bigger or equal
*/
public boolean smaller(Bignat other) {
short index_this = 0;
for (short i = 0; i < this.length(); i++) {
if (this.value[i] != 0x00) {
index_this = i;
}
}
short index_other = 0;
for (short i = 0; i < other.length(); i++) {
if (other.value[i] != 0x00) {
index_other = i;
}
}
if ((short) (this.length() - index_this) < (short) (other.length() - index_other)) {
return true; // CTO
}
short i = 0;
while (i < this.length() && i < other.length()) {
if (((short) (this.value[i] & digit_mask)) < ((short) (other.value[i] & digit_mask))) {
return true; // CTO
}
i = (short) (1 + i);
}
return false;
}
/**
* Comparison of this and other.
*
* @param other
* Bignat to compare with
* @return true if this number is strictly lesser than {@code other}, false
* otherwise.
*/
public boolean lesser(Bignat other) {
return this.shift_lesser(other, (short) 0, (short) 0);
}
/**
* Test equality with zero.
*
* @return true if this bignat equals zero.
*/
public boolean is_zero() {
for (short i = 0; i < size; i++) {
if (value[i] != 0) {
return false; // CTO
}
}
return true;
}
/** Check if stored bignat is odd.
*
* @return true if odd, false if even
*/
public boolean is_odd() {
if ((value[(short) (this.size - 1)] & 1) == 0) {
return false; // CTO
}