-
Notifications
You must be signed in to change notification settings - Fork 0
/
SHEInt.cpp
2389 lines (2193 loc) · 65.6 KB
/
SHEInt.cpp
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
//
// implement basic integer operations for Homomorphic values
//
#include <iostream>
#include "SHEInt.h"
#include "SHEKey.h"
#include "SHEUtil.h"
#include "SHEMagic.h"
#include <helib/helib.h>
#include <helib/binaryArith.h>
#include <helib/binaryCompare.h>
#include <helib/intraSlot.h>
#include "helibio.h"
#ifdef DEBUG
SHEPrivateKey *SHEInt::debugPrivKey = nullptr;
#endif
std::ostream *SHEInt::log = nullptr;
uint64_t SHEInt::nextTmp = 0;
SHEIntLabelHash SHEInt::labelHash;
SHERecryptCounters SHEInt::recryptCounters = { 0 };
static std::vector<helib::Ctxt> &
sheInt_Encrypt(const SHEPublicKey &pubKey,
std::vector<helib::Ctxt> &encryptedData,
uint64_t myint, int bitSize)
{
const helib::PubKey &helibPubKey = pubKey.getPublicKey();
helib::Ctxt ctxtTemplate(helibPubKey);
const helib::EncryptedArray &ea = pubKey.getEncryptedArray();
encryptedData = std::vector<helib::Ctxt>(bitSize,ctxtTemplate);
for (int i=0; i < bitSize; i++) {
std::vector<long> vec(ea.size());
for (auto& slot: vec) {
slot = (myint >> i) & 1;
}
ea.encrypt(encryptedData[i], helibPubKey, vec);
}
return encryptedData;
}
SHEInt::SHEInt(const SHEPublicKey &pubKey_, uint64_t myInt,
int bitSize_, bool isUnsigned_, const char *label) :
pubKey(&pubKey_), bitSize(bitSize_),
isUnsigned(isUnsigned_)
{
if (label) labelHash[this]=label;
isExplicitZero = !myInt;
// if myInt is zero, delay creating the encrypted data. The rest of the
// functions will recognize an isExplicitZero
if (myInt) {
sheInt_Encrypt(*pubKey, encryptedData, myInt, bitSize);
}
}
SHEInt::SHEInt(const SHEInt &model, uint64_t myInt,const char *label)
: pubKey(model.pubKey)
{
if (label) labelHash[this]=label;
bitSize = model.bitSize;
isUnsigned = model.isUnsigned;
isExplicitZero = !myInt;
// if myInt is zero, delay creating the encrypted data. The rest of the
// functions will recognize an isExplicitZero
if (myInt) {
sheInt_Encrypt(*pubKey, encryptedData, myInt, bitSize);
}
}
SHEInt::SHEInt(const SHEPublicKey &pubKey_, const unsigned char *encryptedInt,
int size, const char *label) : pubKey(&pubKey_)
{
if (label) labelHash[this]=label;
std::string s((const char *)encryptedInt, size);
std::stringstream ss(s);
read(ss);
}
SHEInt::SHEInt(const SHEPublicKey &pubKey_, std::istream& str,
const char *label) : pubKey(&pubKey_)
{
if (label) labelHash[this]=label;
readFromJSON(str);
}
// change the size of our encryptedData array. On increase it
// will sign extend, on decrease it will truncate
void SHEInt::reset(int newBitSize, bool newIsUnsigned)
{
isUnsigned = newIsUnsigned;
if (newBitSize == bitSize) {
return;
}
// explicitZero has no encrypted data, just set the bit size
if (isExplicitZero) {
bitSize = newBitSize;
return;
}
// For unsigned, we extend zeros, for signed
// we extend the sign bit. truncation looses
// the high bits.
helib::Ctxt ctxtTemplate(pubKey->getPublicKey());
if (isUnsigned) {
ctxtTemplate.clear();
} else {
ctxtTemplate = encryptedData[bitSize-1];
}
encryptedData.resize(newBitSize, ctxtTemplate);
bitSize = newBitSize;
}
// take an isExplicitZero and expand it to
// a vector<helib::Ctxt> with cleared values
void SHEInt::expandZero(void)
{
if (!isExplicitZero) {
return;
}
helib::Ctxt ctxtTemplate(pubKey->getPublicKey());
ctxtTemplate.clear();
encryptedData.resize(bitSize, ctxtTemplate);
isExplicitZero=false;
}
// do we need to reCrypt before doing more operations.
// bitCapacity uses noise to estimate how many more operations
// we can do, use it to decide if we need to reCrypt.
bool SHEInt::needRecrypt(long level) const
{
// if we are explicit zero, nothing to reencrypt
if (isExplicitZero) {
return false;
}
// first check by level
return level > bitCapacity();
}
// needRecrypt returns true of any of the passed in ints falls below a given
// level
bool SHEInt::needRecrypt(const SHEInt &a, long level) const
{
return needRecrypt(level) || a.needRecrypt(level);
}
bool SHEInt::needRecrypt(const SHEInt &a, const SHEInt &b, long level) const
{
return needRecrypt(level) || a.needRecrypt(level) || b.needRecrypt(level) ;
}
bool SHEInt::needRecrypt(const SHEInt &a, const SHEInt &b, const SHEInt &c,
long level) const
{
return needRecrypt(a, level) || b.needRecrypt(c, level);
}
bool SHEInt::needRecrypt(const SHEInt &a, const SHEInt &b, const SHEInt &c,
const SHEInt &d, long level) const
{
return needRecrypt(a, b, level) || c.needRecrypt(d, level);
}
bool SHEInt::needRecrypt(const SHEInt &a, const SHEInt &b, const SHEInt &c,
const SHEInt &d, const SHEInt &e, long level) const
{
return needRecrypt(a, b, level) || c.needRecrypt(d, e, level);
}
// reCrypt performs a simultaneous bootstrap on all the given integers.
// we skip integers which appear to have a higher capacity then the expected
// result of the bootstrap itself. 'force' overrides this behavior and we
// will unconditionally recrypt everything.
// build a CtPtrs container that holds all the CtrPtrs we wish
// Recrypt
struct CtPtrs_array : helib::CtPtrs
{
// sigh I would prefer to use std::vector, but trying to get the
// allocator right for helib::CtPtrs is non-trivial.
const helib::CtPtrs *a[10];
int nElements;
CtPtrs_array(void) {
for (int i=0; i < 10; i++)
a[i] = nullptr;
nElements=0;
}
void addEntry(const helib::CtPtrs& a_) { a[nElements++] = &a_; }
long size() const override {
long tsize = 0;
for (int i=0; i < nElements; i++) {
tsize += lsize(*a[i]);
}
return tsize;
}
helib::Ctxt *operator[](long i) const override
{
long tsize = 0;
for (int element=0; element < nElements; element++) {
long _lsize = lsize(*a[element]);
long offset = i - tsize;
if (offset < _lsize) {
return (*a[element])[offset];
}
tsize += _lsize;
}
return nullptr; // shouldn't happen
}
};
void SHEInt::reCrypt(SHEInt &a, SHEInt &b, SHEInt &c, SHEInt &d, SHEInt &e,
bool force)
{
if (!force) {
if ((isExplicitZero) || (bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
a.reCrypt(b, c, d, e, false);
return;
}
if ((a.isExplicitZero) || (a.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(b, c, d, e, false);
return;
}
if ((b.isExplicitZero) || (b.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, c, d, e, false);
return;
}
if ((c.isExplicitZero) || (c.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, b, d, e, false);
return;
}
if ((d.isExplicitZero) || (d.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, b, c, e, false);
return;
}
if ((e.isExplicitZero) || (e.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, b, c, d, false);
return;
}
}
if (log) {
(*log) << "[Recrypt(" << (SHEIntSummary)*this << ","
<< (SHEIntSummary) a << ")->" << std::flush;
}
helib::CtPtrs_vectorCt wrapper(encryptedData);
helib::CtPtrs_vectorCt wrapperA(a.encryptedData);
helib::CtPtrs_vectorCt wrapperB(b.encryptedData);
helib::CtPtrs_vectorCt wrapperC(c.encryptedData);
helib::CtPtrs_vectorCt wrapperD(d.encryptedData);
helib::CtPtrs_vectorCt wrapperE(e.encryptedData);
CtPtrs_array matrix;
matrix.addEntry(wrapper);
matrix.addEntry(wrapperA);
matrix.addEntry(wrapperB);
matrix.addEntry(wrapperC);
matrix.addEntry(wrapperD);
matrix.addEntry(wrapperE);
helib::packedRecrypt(matrix,
*(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding(),
pubKey->getEncryptedArray());
reCryptSextupleCounter();
}
void SHEInt::reCrypt(SHEInt &a, SHEInt &b, SHEInt &c, SHEInt &d, bool force)
{
if (!force) {
if ((isExplicitZero) || (bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
a.reCrypt(b, c, d, false);
return;
}
if ((a.isExplicitZero) || (a.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(b, c, d, false);
return;
}
if ((b.isExplicitZero) || (b.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, c, d, false);
return;
}
if ((c.isExplicitZero) || (c.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, b, d, false);
return;
}
if ((d.isExplicitZero) || (d.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, b, c, false);
return;
}
}
if (log) {
(*log) << "[Recrypt(" << (SHEIntSummary)*this << ","
<< (SHEIntSummary) a << ")->" << std::flush;
}
helib::CtPtrs_vectorCt wrapper(encryptedData);
helib::CtPtrs_vectorCt wrapperA(a.encryptedData);
helib::CtPtrs_vectorCt wrapperB(b.encryptedData);
helib::CtPtrs_vectorCt wrapperC(c.encryptedData);
helib::CtPtrs_vectorCt wrapperD(d.encryptedData);
CtPtrs_array matrix;
matrix.addEntry(wrapper);
matrix.addEntry(wrapperA);
matrix.addEntry(wrapperB);
matrix.addEntry(wrapperC);
matrix.addEntry(wrapperD);
helib::packedRecrypt(matrix,
*(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding(),
pubKey->getEncryptedArray());
reCryptQuintupleCounter();
}
void SHEInt::reCrypt(SHEInt &a, SHEInt &b, SHEInt &c, bool force)
{
if (!force) {
if ((isExplicitZero) || (bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
a.reCrypt(b, c, false);
return;
}
if ((a.isExplicitZero) || (a.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(b, c, false);
return;
}
if ((b.isExplicitZero) || (b.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, c, false);
return;
}
if ((c.isExplicitZero) || (c.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, b, false);
return;
}
}
if (log) {
(*log) << "[Recrypt(" << (SHEIntSummary)*this << ","
<< (SHEIntSummary) a << ")->" << std::flush;
}
helib::CtPtrs_vectorCt wrapper(encryptedData);
helib::CtPtrs_vectorCt wrapperA(a.encryptedData);
helib::CtPtrs_vectorCt wrapperB(b.encryptedData);
helib::CtPtrs_vectorCt wrapperC(c.encryptedData);
CtPtrs_array matrix;
matrix.addEntry(wrapper);
matrix.addEntry(wrapperA);
matrix.addEntry(wrapperB);
matrix.addEntry(wrapperC);
helib::packedRecrypt(matrix,
*(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding(),
pubKey->getEncryptedArray());
reCryptQuadrupleCounter();
}
void SHEInt::reCrypt(SHEInt &a, SHEInt &b, bool force)
{
if (!force) {
if ((isExplicitZero) || (bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
a.reCrypt(b, false);
return;
}
if ((a.isExplicitZero) || (a.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(b, false);
return;
}
if ((b.isExplicitZero) || (b.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(a, false);
return;
}
}
if (log) {
(*log) << "[Recrypt(" << (SHEIntSummary)*this << ","
<< (SHEIntSummary) a << ")->" << std::flush;
}
helib::CtPtrs_vectorCt wrapper(encryptedData);
helib::CtPtrs_vectorCt wrapperA(a.encryptedData);
helib::CtPtrs_vectorCt wrapperB(b.encryptedData);
CtPtrs_array matrix;
matrix.addEntry(wrapper);
matrix.addEntry(wrapperA);
matrix.addEntry(wrapperB);
helib::packedRecrypt(matrix,
*(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding(),
pubKey->getEncryptedArray());
reCryptTripleCounter();
}
void SHEInt::reCrypt(SHEInt &a, bool force)
{
if (!force) {
if ((isExplicitZero) || (bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
a.reCrypt(false);
return;
}
if ((a.isExplicitZero) || (a.bitCapacity() > SHEINT_LEVEL_THRESHOLD)) {
reCrypt(false);
return;
}
}
if (log) {
(*log) << "[Recrypt(" << (SHEIntSummary)*this << ","
<< (SHEIntSummary) a << ")->" << std::flush;
}
helib::CtPtrs_vectorCt wrapper(encryptedData);
helib::CtPtrs_vectorCt wrapperA(a.encryptedData);
helib::packedRecrypt(wrapper, wrapperA,
(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding());
reCryptDoubleCounter();
if (log) {
(*log) << "<" << (SHEIntSummary)*this << ","
<< (SHEIntSummary) a << ">]" << std::flush;
}
}
void SHEInt::reCrypt(bool force)
{
// don't check threshold here. If we wound up here with a greater threshold
// it means we have been specifically requested to bootstrap
if (!force && isExplicitZero) {
return;
}
helib::CtPtrs_vectorCt wrapper(encryptedData);
if (log) {
(*log) << "[Recrypt(" << (SHEIntSummary)*this << ")->" << std::flush;
}
helib::packedRecrypt(wrapper,
*(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding(),
pubKey->getEncryptedArray());
reCryptCounter();
if (log) {
(*log) << (SHEIntSummary)*this << "]" << std::flush;
}
}
// verifyArgs can be used before various calls to bring a set of variables up
// to a given level at once.
void SHEInt::verifyArgs(SHEInt &a, SHEInt &b, SHEInt &c, SHEInt &d, SHEInt &e,
long level)
{
if (needRecrypt(a, b, c, d, e, level)) {
reCrypt(a, b, c, d, e, false);
}
}
void SHEInt::verifyArgs(SHEInt &a, SHEInt &b, SHEInt &c, SHEInt &d, long level)
{
if (needRecrypt(a, b, c, d, level)) {
reCrypt(a, b, c, d, false);
}
}
void SHEInt::verifyArgs(SHEInt &a, SHEInt &b, SHEInt &c, long level)
{
if (needRecrypt(a, b, c, level)) {
reCrypt(a, b, c, false);
}
}
void SHEInt::verifyArgs(SHEInt &a, SHEInt &b, long level)
{
if (needRecrypt(a, b, level)) {
reCrypt(a, b, false);
}
}
void SHEInt::verifyArgs(SHEInt &a, long level)
{
if (needRecrypt(a, level)) {
reCrypt(a, false);
}
}
void SHEInt::verifyArgs(long level)
{
if (needRecrypt(level)) {
reCrypt(false);
}
}
///////////////////////////////////////////////////////////////////////////
// input/output operators. /
///////////////////////////////////////////////////////////////////////////
std::ostream& operator<<(std::ostream& str, const SHEInt& a)
{
a.writeToJSON(str);
return str;
}
std::istream& operator>>(std::istream& str, SHEInt& a)
{
a.readFromJSON(str);
return str;
}
std::ostream &operator<<(std::ostream& str, const SHEIntSummary &summary)
{
long level = summary.sheint.bitCapacity();
std::ios_base::fmtflags saveFlags = str.flags();
str << "SHEInt(" << summary.sheint.getLabel() << "," << std::dec
<< summary.sheint.getSize() << ","
<< (char *)(summary.sheint.getUnsigned() ? "U" : "S") << ","
<< (char *)(summary.sheint.getExplicitZero() ? "Z" : "E")
<< "," ;
if (level == LONG_MAX) {
str << "MAX";
} else {
str << level;
}
str.flags(saveFlags);
#ifdef DEBUG
const SHEPrivateKey *privKey = summary.getPrivateKey();
if (privKey) {
str << ":";
if (summary.sheint.isCorrect()) {
uint64_t decrypted = summary.sheint.decryptRaw(*privKey);
if (summary.sheint.getUnsigned()) {
str << decrypted;
} else {
str << (int64_t)decrypted;
}
} else {
str << "NaN";
}
}
#endif
str << ")";
return str;
}
bool SHEInt::isCorrect(void) const
{
if (isExplicitZero) {
return true;
}
for (int i=0; i < bitSize; i++) {
if (!encryptedData[i].isCorrect()) {
return false;
}
}
return true;
}
unsigned char *SHEInt::flatten(int &size, bool ascii) const
{
std::stringstream ss;
if (ascii) {
writeToJSON(ss);
} else {
writeTo(ss);
}
std::string s=ss.str();
size=s.length();
return (unsigned char *)s.data();
}
void SHEInt::writeTo(std::ostream& str) const
{
write_raw_int(str, SHEIntMagic); // magic to say we're a SHEInt
write_raw_int(str, bitSize);
write_raw_int(str, isUnsigned);
// make our explicit zero encrypted now
if (isExplicitZero) {
helib::Ctxt zero_Ctxt(pubKey->getPublicKey());
zero_Ctxt.clear();
for(int i=0; i < bitSize; i++) {
zero_Ctxt.writeTo(str);
}
return;
}
for (int i=0; i <bitSize; i++) {
encryptedData[i].writeTo(str);
}
}
void SHEInt::writeToJSON(std::ostream& str) const
{
helib::executeRedirectJsonError<void>([&]() { str << writeToJSON(); });
}
helib::JsonWrapper SHEInt::writeToJSON(void) const
{
SHEInt target = *this;
if (isExplicitZero) {
// need to make the explicitZero encrypted */
target.expandZero();
}
auto body = [target]() {
json j = {{"bitSize", target.bitSize},
{"isUnsigned", target.isUnsigned},
{"encryptedData", helib::writeVectorToJSON(target.encryptedData)}};
return helib::wrap(helib::toTypedJson<SHEInt>(j));
};
return helib::executeRedirectJsonError<helib::JsonWrapper>(body);
}
SHEInt SHEInt::readFrom(std::istream& str, const SHEPublicKey &pubKey)
{
SHEInt a(pubKey, 0, 1, true);
a.read(str);
return a;
}
SHEInt SHEInt::readFromJSON(std::istream& str, const SHEPublicKey& pubKey)
{
return helib::executeRedirectJsonError<SHEInt>([&]() {
json j;
str >> j;
return readFromJSON(helib::wrap(j), pubKey);
});
}
SHEInt SHEInt::readFromJSON(const helib::JsonWrapper& j,
const SHEPublicKey& pubKey)
{
SHEInt a(pubKey, (uint64_t)0, 1, true);
a.readFromJSON(j);
a.resetNative();
return a;
}
void SHEInt::read(std::istream& str)
{
long magic;
magic = read_raw_int(str);
helib::assertEq<helib::IOError>(magic, SHEIntMagic,
"not an SHEInt on the stream");
bitSize = read_raw_int(str);
isUnsigned = read_raw_int(str);
helib::Ctxt ctxtTemplate(pubKey->getPublicKey());
encryptedData = std::vector<helib::Ctxt>(bitSize,ctxtTemplate);
for (int i=0; i < bitSize; i++) {
encryptedData[i].read(str);
}
isExplicitZero = false;
resetNative();
}
void SHEInt::readFromJSON(std::istream& str)
{
return helib::executeRedirectJsonError<void>([&]() {
json j;
str >> j;
return readFromJSON(helib::wrap(j));
});
}
void SHEInt::readFromJSON(const helib::JsonWrapper& jw)
{
auto body = [&]() {
json j = helib::fromTypedJson<SHEInt>(unwrap(jw));
this->bitSize = j.at("bitSize");
this->isUnsigned = j.at("isUnsigned");
// Using inplace parts deserialization as read_raw_vector will do a
// resize, then reads the parts in-place, so may re-use memory.
const helib::PubKey &helibPubKey = pubKey->getPublicKey();
helib::Ctxt templateCtxt(helibPubKey);
helib::readVectorFromJSON(j.at("encryptedData"),
this->encryptedData, templateCtxt);
this->isExplicitZero = false;
// sanity-check
helib::assertEq(this->bitSize, (int) this->encryptedData.size(),
"bitSize and the size of the encryptedData does not match");
};
helib::executeRedirectJsonError<void>(body);
}
///////////////////////////////////////////////////////////////////////////
// General helpers
///////////////////////////////////////////////////////////////////////////
uint64_t SHEInt::decryptRaw(const SHEPrivateKey &privKey) const
{
if (isExplicitZero) {
return 0;
}
uint64_t result;
std::vector<long> decrypted_result;
helib::CtPtrs_vectorCt wrapper((std::vector<helib::Ctxt>&)encryptedData);
helib::decryptBinaryNums(decrypted_result, wrapper, privKey.getPrivateKey(),
pubKey->getEncryptedArray());
result = decrypted_result.back();
if (!isUnsigned) {
// sign extend for signed values
uint64_t sign=(result >> (bitSize-1)) & 1;
for (int i=bitSize; i < 64; i++) {
result |= (sign << i);
}
}
return result;
}
uint64_t SHEInt::decryptBit(const SHEPrivateKey &privKey, helib::Ctxt &ctxt) const
{
std::vector<long> slots;
const helib::EncryptedArray& ea=pubKey->getEncryptedArray();
ea.decrypt(ctxt,privKey.getPrivateKey(), slots);
return slots[ea.sizeOfDimension(ea.dimension()-1)];
}
long SHEInt::bitCapacity(void) const
{
if (isExplicitZero) {
return LONG_MAX;
}
helib::CtPtrs_vectorCt wrapper((std::vector<helib::Ctxt>&)encryptedData);
return helib::findMinBitCapacity(wrapper);
}
double SHEInt::securityLevel(void) const
{
return pubKey->securityLevel();
}
///////////////////////////////////////////////////////////////////////////
// Single bit helpers /
///////////////////////////////////////////////////////////////////////////
//
// select a singe bit (Ctxt) based on the this logical operator (this is
// the bit equivalent of select, except on Ctxt values).
static helib::Ctxt selectBit(const helib::Ctxt &sel,
const helib::Ctxt &trueBit,
const helib::Ctxt &falseBit)
{
helib::Ctxt negate_cond(sel);
negate_cond.addConstant(NTL::ZZX(1L));
helib::Ctxt result(trueBit);
helib::Ctxt result_(falseBit);
result.multiplyBy(sel);
result_.multiplyBy(negate_cond);
result += result_;
return result;
}
helib::Ctxt SHEInt::selectBit(const helib::Ctxt &trueBit,
const helib::Ctxt &falseBit) const
{
return ::selectBit(encryptedData[0], trueBit, falseBit);
}
//
// return the bit indexed by and encrypted 'index+offset'. This is equivalent to
// encryptedArray[i], except 'i' is encrypted. The use of the unencrypted
// offset allows the caller to use offset as the loop variable rather than
// the encrypted index. This allows us to not need to update the encrypted
// offset every step of the loop which saves time and capacity.
// If the array index is outside 0..biSize-1 then defaultBit is returned
//
helib::Ctxt SHEInt::selectArrayBit(const SHEInt &index, int offset,
int direction,
const helib::Ctxt &defaultBit) const
{
SHEInt thisBit(*pubKey, 0, 1, true);
helib::Ctxt selectedBit = defaultBit;
for (int i=0; i < bitSize; i++) {
int cmpIndex= direction?offset-i:i-offset;
if (selectedBit.bitCapacity() < SHEINT_DEFAULT_LEVEL_TRIGGER) {
// it's posible we hit the capacity mid loop, recrypt if necessary
const helib::PubKey &publicKey = pubKey->getPublicKey();
if (log) {
(*log) << " -reCrypting selectedBit(" << selectedBit.bitCapacity()
<< ") at bit " << i << " of" << bitSize << std::endl;
}
publicKey.reCrypt(selectedBit);
reCryptBitCounter();
}
selectedBit = (index == cmpIndex).selectBit(encryptedData[i],
selectedBit);
}
return selectedBit;
}
///////////////////////////////////////////////////////////////////////////
// Mathematic helpers. /
///////////////////////////////////////////////////////////////////////////
// caller must ensure that the bit size of this, a, and result are all equal
SHEInt &SHEInt::addRaw(const SHEInt &a, SHEInt &result) const
{
helib::CtPtrs_vectorCt wrapper(result.encryptedData);
if (log) {
(*log) << (SHEIntSummary)*this << ".addRaw(" << (SHEIntSummary) a << ","
<< (SHEIntSummary)result << ")=" << std::flush;
}
helib::addTwoNumbers(wrapper,
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)encryptedData),
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)a.encryptedData),
result.bitSize,
(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding());
//result.encryptedData is now set
result.isExplicitZero = false;
if (log) (*log) << (SHEIntSummary)result << std::endl;
return result;
}
SHEInt &SHEInt::cmpRaw(const SHEInt &a, SHEInt >, SHEInt <) const
{
if (log) {
(*log) << (SHEIntSummary)*this << ".cmpRaw(" << (SHEIntSummary) a << ","
<< (SHEIntSummary)gt << "," << (SHEIntSummary)lt << ") ->" << std::flush;
}
helib::compareTwoNumbers(gt.encryptedData[0], lt.encryptedData[0],
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)encryptedData),
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)a.encryptedData),
!isUnsigned,
(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding());
if (log) (*log) << "gt=" <<(SHEIntSummary)gt << "lt=" << (SHEIntSummary)lt << std::endl;
return gt;
}
// caller must ensure that the bit size of this, a, and result are all equal
SHEInt &SHEInt::subRaw(const SHEInt &a, SHEInt &result) const
{
helib::CtPtrs_vectorCt wrapper(result.encryptedData);
if (log) {
(*log) << (SHEIntSummary)*this << ".subRaw(" << (SHEIntSummary) a << ","
<< (SHEIntSummary)result << ")=" << std::flush;
}
helib::subtractBinary(wrapper,
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)encryptedData),
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)a.encryptedData),
(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding());
//result.encryptedData is now set
result.isExplicitZero = false;
if (log) (*log) << (SHEIntSummary)result << std::endl;
return result;
}
// no need to have a & b =, result must be = MAX(bitsize, a.bitSize);
SHEInt &SHEInt::mulRaw(const SHEInt &a, SHEInt &result) const
{
helib::CtPtrs_vectorCt wrapper(result.encryptedData);
if (isUnsigned == a.isUnsigned) {
// If the input values are both unsigned or both signed,
// multTwoNumbers can handle the result
result.isUnsigned = isUnsigned;
if (log) {
(*log) << (SHEIntSummary)*this << ".mulRaw(" << (SHEIntSummary) a <<
"," << (SHEIntSummary)result << ")=" << std::flush;
}
helib::multTwoNumbers(wrapper,
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)encryptedData),
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)a.encryptedData),
!isUnsigned,
result.bitSize,
(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding());
if (log) (*log) << (SHEIntSummary)result << std::endl;
//result.encryptedData is now set
} else {
SHEInt m1(*this);
SHEInt m2(a);
// One operand is unsigned, the other is signed
// extending the values by 1 puts a zero in the high bit
// for unsigned operands, and signed extends for signed operands.
// we can then safely use multTwoNumbers for signed operations
// and get the correct result (which will be signed)
m1.reset(bitSize+1,isUnsigned);
m2.reset(a.bitSize+1,isUnsigned);
result.isUnsigned = false;
if (log) {
(*log) << (SHEIntSummary)*this << ".mulRaw-mixed("
<< (SHEIntSummary) a << ","
<< (SHEIntSummary)result << ")=" << std::flush;
}
helib::multTwoNumbers(wrapper,
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)encryptedData),
helib::CtPtrs_vectorCt((std::vector<helib::Ctxt>&)a.encryptedData),
true,
result.bitSize,
(std::vector<helib::zzX> *)pubKey->getUnpackSlotEncoding());
if (log) (*log) << (SHEIntSummary)result << std::endl;
//result.encryptedData is now set
}
result.isExplicitZero = false;
return result;
}
// we do the shift by hand rather than use the binaryArithm library here
// because we want to implement shift in place. NOTE: shifts using an
// integer are relatively fast (no Homomorphic operations) and does not
// reduce capacity!
void SHEInt::leftShift(uint64_t shift)
{
// shift of zero is a noop
if (isExplicitZero) {
return;
}
// allow in place shift, first targets should be the lost bits
for (int i=bitSize-1; i >= shift ; i--) {
encryptedData[i] = encryptedData[i - shift];
}
for (int i=0; i < shift; i++) {
encryptedData[i].clear();
}
}
// the binaryArithm library doesn't have a right shift
void SHEInt::rightShift(uint64_t shift)
{
// shift of zero is a noop
if (isExplicitZero) {
return;
}
// allow in place shift, first targets should be the lost bits
for (int i=0; i < bitSize - shift; i++) {
encryptedData[i] = encryptedData[i+shift];
}
if (!isUnsigned) {
// arithmetic shift, preserving the sign bit
for (int i=bitSize-shift; i < bitSize-1; i++) {
encryptedData[i] = encryptedData[bitSize-1];
}
} else {
for (int i=bitSize-shift; i < bitSize; i++) {
encryptedData[i].clear();
}
}
}
//
// Shift by an encrypted shift index requires logical operaters.
// Note: unlike integer shifts, these are more expensive in both time
// (O(bitSize^2) single bit multiplies and a xor) and capacity.
SHEInt &SHEInt::leftShift(const SHEInt &shift, SHEInt &result) const
{
// walk down the possible shifts and return the one that matches
result = SHEInt(*this, (uint64_t)0);
for (int i=0; i < bitSize; i++) {
result = (i==shift).select(*this << i, result);
}
return result;
}
SHEInt &SHEInt::rightShift(const SHEInt &shift, SHEInt &result) const
{
// walk down the possible shifts and return the one that matches
result = SHEInt(*this, (uint64_t)0);
if (!isUnsigned) {
result=isNegative().select(-1,result);
}
for (int i=0; i < bitSize; i++) {
result = (i==shift).select(*this >> i, result);
}
return result;
}
// this shift takes in account of the sign of shift and reverses
// fields if it's negative.
SHEInt SHEInt::rightShiftSigned(const SHEInt &shift) const
{
// walk down the possible shifts and return the one that matches
// if none matches, the result is zero
SHEInt result(*this, (uint64_t)0);
// If shift is unsigned, reduce to just a normal rightShift
if (shift.isUnsigned) {
return rightShift(shift,result);
}
// If this is signed and negative, default result of a right
// shift (shift is positive) is -1, not zero.
if (!isUnsigned) {
result=(isNegative() & !shift.isNegative()).select(-1,result);
}
// handle the no shift case first
result = shift.isZero().select(*this, result);
// now check each positive an negative shift up to bitsize
for (int i=1; i < bitSize; i++) {
result = (i==shift).select(*this >> i, result);
result = (-i==shift).select(*this << i, result);
}
return result;
}
// this shift takes in account of the sign of shift and reverses
// fields if it's negative.
SHEInt SHEInt::leftShiftSigned(const SHEInt &shift) const
{
// walk down the possible shifts and return the one that matches
// if none matches, the result is zero
SHEInt result(*this, (uint64_t)0);
// If shift is unsigned, reduce to just a normal leftShift
if (shift.isUnsigned) {
return leftShift(shift,result);
}
// If this is signed and negative, default result of a right
// shift (shift is negative) is -1, not zero.
if (!isUnsigned) {
result=(isNegative() & shift.isNegative()).select(-1,result);
}
// handle the no shift case first
result = shift.isZero().select(*this, result);
// now check each positive an negative shift up to bitsize
for (int i=1; i < bitSize; i++) {
result = (i==shift).select(*this << i, result);
result = (-i==shift).select(*this >> i, result);