-
Notifications
You must be signed in to change notification settings - Fork 290
Expand file tree
/
Copy pathcryptocontext.h
More file actions
4118 lines (3715 loc) · 175 KB
/
cryptocontext.h
File metadata and controls
4118 lines (3715 loc) · 175 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
//==================================================================================
// BSD 2-Clause License
//
// Copyright (c) 2014-2025, NJIT, Duality Technologies Inc. and other contributors
//
// All rights reserved.
//
// Author TPOC: [email protected]
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//==================================================================================
/*
Control for encryption operations
*/
#ifndef __CRYPTOCONTEXT_H__
#define __CRYPTOCONTEXT_H__
#include "binfhecontext.h"
#include "ciphertext.h"
#include "cryptocontextfactory.h"
#include "cryptocontext-fwd.h"
#include "encoding/plaintextfactory.h"
#include "key/evalkey.h"
#include "key/keypair.h"
#include "scheme/scheme-swch-params.h"
#include "schemebase/base-pke.h"
#include "schemebase/base-scheme.h"
#include "schemerns/rns-cryptoparameters.h"
#include "utils/caller_info.h"
#include "utils/type_name.h"
#include <algorithm>
#include <complex>
#include <functional>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
#ifdef DEBUG_KEY
#include <iostream>
#endif
namespace lbcrypto {
/**
* @class CryptoContextImpl
* @brief A class to simplify access to OpenFHE's PKE functionality.
*
* Functionality is accessed by creating an instance of CryptoContextImpl.
* Various objects are "created" in the instance, but they can only be used with the context in which they were created.
*
* OpenFHE methods are accessed through CryptoContextImpl methods. Guards are implemented to make certain that
* only valid objects that have been created in the context are used
*
* Contexts are created using GenCryptoContext(), and can be serialized and recovered from serialization
*/
template <typename Element>
class CryptoContextImpl : public Serializable {
using IntType = typename Element::Integer;
using ParmType = typename Element::Params;
/**
* @brief Checks if the cryptocontext scheme is CKKS and throws an exception if it is not.
*
* @param functionName the calling function name. __func__ can be used instead
*/
inline void VerifyCKKSScheme(const std::string& functionName) const {
if (!isCKKS(m_schemeId)) {
std::string errMsg = std::string(functionName) +
"() is available for the CKKS scheme only."
" The current scheme is " +
convertToString(m_schemeId);
OPENFHE_THROW(errMsg);
}
}
/**
* @brief VerifyCKKSRealDataType Checks if the CKKS data type is real and throws an exception if it is not.
*
* @param functionName the calling function name. __func__ can be used instead
*/
inline void VerifyCKKSRealDataType(const std::string& functionName) const {
if (GetCKKSDataType() != REAL) {
std::string errMsg =
"Function " + std::string(functionName) + " is available for the real CKKS data types only.";
OPENFHE_THROW(errMsg);
}
}
void SetKSTechniqueInScheme();
const CryptoContext<Element> GetContextForPointer(const CryptoContextImpl<Element>* cc) const {
const auto& contexts = CryptoContextFactory<Element>::GetAllContexts();
for (const auto& ctx : contexts) {
if (cc == ctx.get())
return ctx;
}
OPENFHE_THROW("Cannot find context for the given pointer to CryptoContextImpl");
}
/**
* @brief Constructs CoefPackedEncoding or PackedEncoding in this context
*
* @param encoding encoding type
* @param value the value to encode
* @param depth the multiplicative depth to encode the plaintext at
* @param level the level to encode the plaintext at
* @return new plaintext
*/
Plaintext MakePlaintext(const PlaintextEncodings encoding, const std::vector<int64_t>& value, size_t depth,
uint32_t level) const {
const auto cryptoParams = std::dynamic_pointer_cast<CryptoParametersRNS>(GetCryptoParameters());
if (level > 0) {
size_t numModuli = cryptoParams->GetElementParams()->GetParams().size();
if (!isBFVRNS(m_schemeId)) {
// we throw an exception if level >= numModuli. However, we use multiplicativeDepth in the error message,
// so the user can understand the error more easily.
if (level >= numModuli) {
uint32_t multiplicativeDepth =
(cryptoParams->GetScalingTechnique() == FLEXIBLEAUTOEXT) ? (numModuli - 2) : (numModuli - 1);
std::string errorMsg{"The level value should be less than or equal to "};
errorMsg +=
((cryptoParams->GetScalingTechnique() == FLEXIBLEAUTOEXT) ? "(multiplicativeDepth + 1)." :
"multiplicativeDepth.");
errorMsg += " Currently: level is [" + std::to_string(level) + "] and multiplicativeDepth is [" +
std::to_string(multiplicativeDepth) + "]";
OPENFHE_THROW(errorMsg);
}
}
else {
if ((cryptoParams->GetMultiplicationTechnique() == BEHZ) ||
(cryptoParams->GetMultiplicationTechnique() == HPS)) {
OPENFHE_THROW(
"BFV: Encoding at level > 0 is not currently supported for BEHZ or HPS. Use one of the HPSPOVERQ* methods instead.");
}
if ((cryptoParams->GetEncryptionTechnique() == EXTENDED)) {
OPENFHE_THROW(
"BFV: Encoding at level > 0 is not currently supported for the EXTENDED encryption method. Use the STANDARD encryption method instead.");
}
if (level >= numModuli) {
std::string errorMsg =
"The level value should be less the current number of RNS limbs in the cryptocontext.";
errorMsg += " Currently: level is [" + std::to_string(level) + "] and number of RNS limbs is [" +
std::to_string(numModuli) + "]";
OPENFHE_THROW(errorMsg);
}
}
}
// uses a parameter set with a reduced number of RNS limbs corresponding to the level
std::shared_ptr<ILDCRTParams<DCRTPoly::Integer>> elemParamsPtr;
if (level != 0) {
ILDCRTParams<DCRTPoly::Integer> elemParams = *(cryptoParams->GetElementParams());
for (uint32_t i = 0; i < level; i++) {
elemParams.PopLastParam();
}
elemParamsPtr = std::make_shared<ILDCRTParams<DCRTPoly::Integer>>(elemParams);
}
else {
elemParamsPtr = cryptoParams->GetElementParams();
}
NativeInteger scf{1};
bool setNoiseScaleDeg = false;
auto scaleTech = cryptoParams->GetScalingTechnique();
if (isBGVRNS(m_schemeId) && (scaleTech == FLEXIBLEAUTO || scaleTech == FLEXIBLEAUTOEXT)) {
if (scaleTech == FLEXIBLEAUTOEXT && level == 0) {
scf = cryptoParams->GetScalingFactorIntBig(level);
depth = 1;
setNoiseScaleDeg = true;
}
else
scf = cryptoParams->GetScalingFactorInt(level);
}
Plaintext p = PlaintextFactory::MakePlaintext(value, encoding, elemParamsPtr, this->GetEncodingParams(),
getSchemeId(), depth, level, scf);
if (setNoiseScaleDeg)
p->SetNoiseScaleDeg(2);
return p;
}
/**
* @brief Constructs CoefPackedEncoding, PackedEncoding in this context
*
* @param encoding encoding type
* @param cc the context to create a plaintext with
* @param value the value to encode
* @return new plaintext
*/
template <typename Value1>
static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value) {
return PlaintextFactory::MakePlaintext(value, encoding, cc->GetElementParams(), cc->GetEncodingParams());
}
template <typename Value1, typename Value2>
static Plaintext MakePlaintext(PlaintextEncodings encoding, CryptoContext<Element> cc, const Value1& value,
const Value2& value2) {
return PlaintextFactory::MakePlaintext(encoding, cc->GetElementParams(), cc->GetEncodingParams(), value,
value2);
}
/**
* @brief Gets automorphism keys for a specific secret key tag and an array of specific indices
*
* @param keyTag secret key tag
* @param indexList array of specific indices to retrieve key for
* @return shared_ptr to std::map where the map key/data pair is index/automorphism key
*/
static std::shared_ptr<std::map<uint32_t, EvalKey<Element>>> GetPartialEvalAutomorphismKeyMapPtr(
const std::string& keyTag, const std::vector<uint32_t>& indexList);
// cached evalmult keys, by secret key UID
static std::map<std::string, std::vector<EvalKey<Element>>> s_evalMultKeyMap;
// cached evalautomorphism keys, by secret key UID
static std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>> s_evalAutomorphismKeyMap;
protected:
// crypto parameters
std::shared_ptr<CryptoParametersBase<Element>> m_params{nullptr};
// algorithm used; accesses all crypto methods
std::shared_ptr<SchemeBase<Element>> m_scheme{nullptr};
SCHEME m_schemeId{SCHEME::INVALID_SCHEME};
uint32_t m_keyGenLevel{0};
/**
* @brief TypeCheck makes sure that an operation between two ciphertexts is permitted
*
* @param a ciphertext1
* @param b ciphertext2
*/
void TypeCheck(ConstCiphertext<Element>& a, ConstCiphertext<Element>& b, CALLER_INFO_ARGS_HDR) const {
if (a == nullptr || b == nullptr) {
std::string errorMsg(std::string("Null Ciphertext") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (a->GetCryptoContext().get() != this) {
std::string errorMsg(std::string("Ciphertext was not created in this CryptoContext") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (a->GetCryptoContext() != b->GetCryptoContext()) {
std::string errorMsg(std::string("Ciphertexts were not created in the same CryptoContext") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (a->GetKeyTag() != b->GetKeyTag()) {
std::string errorMsg(std::string("Ciphertexts were not encrypted with same keys") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (a->GetEncodingType() != b->GetEncodingType()) {
std::stringstream ss;
ss << "Ciphertext encoding types " << a->GetEncodingType();
ss << " and " << b->GetEncodingType();
ss << " do not match";
ss << CALLER_INFO;
OPENFHE_THROW(ss.str());
}
}
/**
* @brief TypeCheck makes sure that an operation between a ciphertext and a plaintext is permitted
*
* @param a ciphertext
* @param b plaintext
*/
void TypeCheck(ConstCiphertext<Element>& a, ConstPlaintext& b, CALLER_INFO_ARGS_HDR) const {
if (a == nullptr) {
std::string errorMsg(std::string("Null Ciphertext") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (b == nullptr) {
std::string errorMsg(std::string("Null Plaintext") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (a->GetCryptoContext().get() != this) {
std::string errorMsg(std::string("Ciphertext was not created in this CryptoContext") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (a->GetEncodingType() != b->GetEncodingType()) {
std::stringstream ss;
ss << "Ciphertext encoding type " << a->GetEncodingType();
ss << " and Plaintext encoding type " << b->GetEncodingType();
ss << " do not match";
ss << CALLER_INFO;
OPENFHE_THROW(ss.str());
}
}
bool Mismatched(const CryptoContext<Element> a) const {
return a.get() != this;
}
template <typename T>
void ValidateKey(const T& key, CALLER_INFO_ARGS_HDR) const {
if (key == nullptr) {
std::string errorMsg(std::string("Key is nullptr") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (Mismatched(key->GetCryptoContext())) {
std::string errorMsg(std::string("Key was not generated with the same crypto context") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
}
void ValidateCiphertext(ConstCiphertext<Element>& ciphertext, CALLER_INFO_ARGS_HDR) const {
if (ciphertext == nullptr) {
std::string errorMsg(std::string("Ciphertext is nullptr") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (Mismatched(ciphertext->GetCryptoContext())) {
std::string errorMsg(std::string("Ciphertext was not generated with the same crypto context") +
CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
}
void ValidateSeriesPowers(std::shared_ptr<seriesPowers<Element>> powers, CALLER_INFO_ARGS_HDR) const {
if (powers == nullptr) {
std::string errorMsg(std::string("The object for powers is nullptr") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (powers->powersRe.size() == 0) {
std::string errorMsg(std::string("The powersRe member is empty") + CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
if (Mismatched(powers->powersRe[0]->GetCryptoContext())) {
std::string errorMsg(std::string("Power ciphertext was not generated with the same crypto context") +
CALLER_INFO);
OPENFHE_THROW(errorMsg);
}
}
virtual Plaintext MakeCKKSPackedPlaintextInternal(const std::vector<std::complex<double>>& value,
size_t noiseScaleDeg, uint32_t level,
const std::shared_ptr<ParmType> params, uint32_t slots) const {
VerifyCKKSScheme(__func__);
const auto cryptoParams = std::dynamic_pointer_cast<CryptoParametersRNS>(GetCryptoParameters());
if (level > 0) {
// validation of level: We need to compare it to multiplicativeDepth, but multiplicativeDepth is not
// readily available. so, what we get is numModuli and use it for calculations
size_t numModuli = cryptoParams->GetElementParams()->GetParams().size();
uint32_t multiplicativeDepth =
(cryptoParams->GetScalingTechnique() == FLEXIBLEAUTOEXT) ? (numModuli - 2) : (numModuli - 1);
// we throw an exception if level >= numModuli. however, we use multiplicativeDepth in the error message,
// so the user can understand the error more easily.
if (level >= numModuli) {
std::string errorMsg;
if (cryptoParams->GetScalingTechnique() == FLEXIBLEAUTOEXT)
errorMsg = "The level value should be less than or equal to (multiplicativeDepth + 1).";
else
errorMsg = "The level value should be less than or equal to multiplicativeDepth.";
errorMsg += " Currently: level is [" + std::to_string(level) + "] and multiplicativeDepth is [" +
std::to_string(multiplicativeDepth) + "]";
OPENFHE_THROW(errorMsg);
}
}
double scFact = 0;
if (cryptoParams->GetScalingTechnique() == FLEXIBLEAUTOEXT && level == 0) {
scFact = cryptoParams->GetScalingFactorRealBig(level);
// In FLEXIBLEAUTOEXT mode at level 0, we don't use the noiseScaleDeg in our encoding function,
// so we set it to 1 to make sure it has no effect on the encoding.
noiseScaleDeg = 1;
}
else {
scFact = cryptoParams->GetScalingFactorReal(level);
}
Plaintext p;
if (params == nullptr) {
std::shared_ptr<ILDCRTParams<DCRTPoly::Integer>> elemParamsPtr;
if (level != 0) {
ILDCRTParams<DCRTPoly::Integer> elemParams = *(cryptoParams->GetElementParams());
for (uint32_t i = 0; i < level; i++) {
elemParams.PopLastParam();
}
elemParamsPtr = std::make_shared<ILDCRTParams<DCRTPoly::Integer>>(elemParams);
}
else {
elemParamsPtr = cryptoParams->GetElementParams();
}
// Check if plaintext has got enough slots for data (value)
uint32_t ringDim = elemParamsPtr->GetRingDimension();
size_t valueSize = value.size();
if (valueSize > ringDim / 2) {
OPENFHE_THROW("The size [" + std::to_string(valueSize) +
"] of the vector with values should not be greater than ringDim/2 [" +
std::to_string(ringDim / 2) + "] if the scheme is CKKS");
}
// TODO (dsuponit): we should call a version of MakePlaintext instead of calling Plaintext() directly here
p = Plaintext(std::make_shared<CKKSPackedEncoding>(elemParamsPtr, this->GetEncodingParams(), value,
noiseScaleDeg, level, scFact, slots,
this->GetCKKSDataType()));
}
else {
// Check if plaintext has got enough slots for data (value)
uint32_t ringDim = params->GetRingDimension();
size_t valueSize = value.size();
if (valueSize > ringDim / 2) {
OPENFHE_THROW("The size [" + std::to_string(valueSize) +
"] of the vector with values should not be greater than ringDim/2 [" +
std::to_string(ringDim / 2) + "] if the scheme is CKKS");
}
// TODO (dsuponit): we should call a version of MakePlaintext instead of calling Plaintext() directly here
p = Plaintext(std::make_shared<CKKSPackedEncoding>(params, this->GetEncodingParams(), value, noiseScaleDeg,
level, scFact, slots, this->GetCKKSDataType()));
}
p->Encode();
// In FLEXIBLEAUTOEXT mode, a fresh plaintext at level 0 always has noiseScaleDeg 2.
if (cryptoParams->GetScalingTechnique() == FLEXIBLEAUTOEXT && level == 0) {
p->SetNoiseScaleDeg(2);
}
return p;
}
/**
* @brief Getter for composite degree of the current scheme crypto context.
* @return integer value corresponding to composite degree
*/
uint32_t GetCompositeDegreeFromCtxt() const {
const auto cryptoParams = std::dynamic_pointer_cast<CryptoParametersRNS>(m_params);
if (!cryptoParams) {
std::string errorMsg(std::string("std::dynamic_pointer_cast<CryptoParametersRNS>() failed"));
OPENFHE_THROW(errorMsg);
}
return cryptoParams->GetCompositeDegree();
}
#ifdef DEBUG_KEY
PrivateKey<Element> privateKey;
#endif
public:
#ifdef DEBUG_KEY
/**
* SetPrivateKey() stores the private key in the crypto context.
* GetPrivateKey() gets the private key from the crypto context.
*
* Thees functions are only intended for debugging and should not be used in production systems.
* Please define DEBUG_KEY in openfhe.h to enable them.
*
* If used, one can create a key pair and store the secret key in the crypto context like this:
*
* auto keys = cc->KeyGen();
* cc->SetPrivateKey(keys.secretKey);
*
* After that, anyone in the code can access the secret key by getting the crypto context and doing the following:
*
* auto sk = cc->GetPrivateKey();
*
* The key can be used for decrypting any intermediate ciphertexts for debugging purposes.
*/
void SetPrivateKey(const PrivateKey<Element> privateKey) {
std::cerr << "Warning - SetPrivateKey is only intended to be used for debugging "
"purposes - not for production systems."
<< std::endl;
this->privateKey = privateKey;
}
const PrivateKey<Element>& GetPrivateKey() const {
return this->privateKey;
}
#endif
void setSchemeId(SCHEME schemeTag) {
this->m_schemeId = schemeTag;
}
SCHEME getSchemeId() const {
return this->m_schemeId;
}
/**
* @brief Constructor from raw pointers to parameters and scheme
*
* @param params pointer to CryptoParameters
* @param scheme pointer to Crypto Scheme object
* @param schemeId scheme identifier
*/
// TODO (dsuponit): investigate if we really need 2 constructors for CryptoContextImpl as one of them take regular pointer
// and the other one takes shared_ptr
CryptoContextImpl(CryptoParametersBase<Element>* params = nullptr, SchemeBase<Element>* scheme = nullptr,
SCHEME schemeId = SCHEME::INVALID_SCHEME) {
this->m_params.reset(params);
this->m_scheme.reset(scheme);
this->m_keyGenLevel = 0;
this->m_schemeId = schemeId;
}
/**
* @brief Constructor from shared pointers to parameters and scheme
*
* @param params shared pointer to CryptoParameters
* @param scheme sharedpointer to Crypto Scheme object
* @param schemeId scheme identifier
*/
CryptoContextImpl(std::shared_ptr<CryptoParametersBase<Element>> params,
std::shared_ptr<SchemeBase<Element>> scheme, SCHEME schemeId = SCHEME::INVALID_SCHEME) {
this->m_params = params;
this->m_scheme = scheme;
this->m_keyGenLevel = 0;
this->m_schemeId = schemeId;
}
/**
* @brief Copy constructor
* @param other cryptocontext to copy from
*/
CryptoContextImpl(const CryptoContextImpl<Element>& other) {
m_params = other.m_params;
m_scheme = other.m_scheme;
m_keyGenLevel = 0;
m_schemeId = other.m_schemeId;
}
/**
* @brief Assignment operator
* @param rhs cryptocontext to assign values from
* @return this
*/
CryptoContextImpl<Element>& operator=(const CryptoContextImpl<Element>& rhs) {
m_params = rhs.m_params;
m_scheme = rhs.m_scheme;
m_keyGenLevel = rhs.m_keyGenLevel;
m_schemeId = rhs.m_schemeId;
return *this;
}
/**
* @brief Checks the CryptoContextImpl object health.
* @return true if params and scheme exists in the object
*/
operator bool() const {
return m_params && m_scheme;
}
/**
* @brief Equality comparison operator
*
* @param a cryptocontext object1
* @param b cryptocontext object2
* @return true if the implementations have identical params and scheme
* @attention this is for internal use only
*/
friend bool operator==(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) {
// Identical if the parameters and the schemes are identical... the exact
// same object, OR the same type and the same values
if (a.m_params.get() == b.m_params.get()) {
return true;
}
else {
if (typeid(*a.m_params.get()) != typeid(*b.m_params.get())) {
return false;
}
if (*a.m_params.get() != *b.m_params.get())
return false;
}
if (a.m_scheme.get() == b.m_scheme.get()) {
return true;
}
else {
if (typeid(*a.m_scheme.get()) != typeid(*b.m_scheme.get())) {
return false;
}
if (*a.m_scheme.get() != *b.m_scheme.get())
return false;
}
return true;
}
/**
* @brief Inequality comparison operator
*
* @param a cryptocontext object1
* @param b cryptocontext object2
* @return true if the implementations do not have identical params and scheme
* @attention this is for internal use only
*/
friend bool operator!=(const CryptoContextImpl<Element>& a, const CryptoContextImpl<Element>& b) {
return !(a == b);
}
/**
* @brief Clears various caches within the library
*/
static void ClearStaticMapsAndVectors();
/**
* @brief Release the scheme-level bootstrap precomputations held by this
* CryptoContext (e.g. FHECKKSRNS::m_bootPrecomMap). Lets callers free
* this memory without destroying the context itself, since the
* existing ClearEval*Keys / ReleaseAllContexts APIs leave scheme-level
* caches alive while any user reference keeps the context alive
* (issue #533). No-op for schemes without bootstrap caches.
*/
void ClearBootstrapPrecom() noexcept {
if (m_scheme)
m_scheme->ClearBootstrapPrecom();
}
/**
* @brief Release the bootstrap precomputation entry associated with a
* specific number of slots. Useful for callers who re-use a CryptoContext
* with multiple slot counts and want to free only the stale ones
* (issue #533). No-op if no entry exists for the given slot count or the
* scheme does not cache per-slot bootstrap data.
*/
void ClearBootstrapPrecom(uint32_t slots) noexcept {
if (m_scheme)
m_scheme->ClearBootstrapPrecom(slots);
}
/**
* @brief Release every bootstrap precomputation entry except the one keyed
* by @p keepSlots. Handy for workloads that repeatedly bootstrap a fixed
* slot count but occasionally bootstrap transient slot counts — reclaims
* the transient caches without invalidating the hot path (issue #533).
*/
void ClearBootstrapPrecomExcept(uint32_t keepSlots) noexcept {
if (m_scheme)
m_scheme->ClearBootstrapPrecomExcept(keepSlots);
}
/**
* @brief Release scheme-switch precomputations (intermediate CKKS/FHEW
* contexts, switching keys, and linear-transform plaintexts) held by this
* CryptoContext (issue #533). No-op for schemes that do not support
* CKKS<->FHEW switching.
*/
void ClearSchemeSwitchPrecom() noexcept {
if (m_scheme)
m_scheme->ClearSchemeSwitchPrecom();
}
/**
* @brief Convenience: release all scheme-level caches held by this
* CryptoContext (bootstrap + scheme-switch). This does NOT touch the
* static eval-key maps — call ClearEvalMultKeys / ClearEvalAutomorphismKeys
* for those (issue #533).
*/
void ClearAllCKKSCaches() noexcept {
ClearBootstrapPrecom();
ClearSchemeSwitchPrecom();
}
/**
* @brief Inspectors for scheme-level caches. Return false for schemes that
* do not maintain the corresponding cache, and whenever the cache is empty
* (issue #533). Intended for callers that need to reason about memory
* without reaching into internal types.
*/
bool HasBootstrapPrecom() const noexcept {
return m_scheme && m_scheme->HasBootstrapPrecom();
}
bool HasBootstrapPrecom(uint32_t slots) const noexcept {
return m_scheme && m_scheme->HasBootstrapPrecom(slots);
}
bool HasSchemeSwitchPrecom() const noexcept {
return m_scheme && m_scheme->HasSchemeSwitchPrecom();
}
/**
* @brief Serializes either all EvalMult keys (if keyTag is empty) or the EvalMult keys for keyTag
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param keyTag secret key tag
* @return true on success
*/
template <typename ST>
static bool SerializeEvalMultKey(std::ostream& ser, const ST& sertype, const std::string& keyTag = "") {
const auto& evalMultKeys = CryptoContextImpl<Element>::GetAllEvalMultKeys();
if (keyTag.length() == 0) {
Serial::Serialize(evalMultKeys, ser, sertype);
}
else {
const auto it = evalMultKeys.find(keyTag);
if (it == evalMultKeys.end())
return false; // no such keyTag
std::map<std::string, std::vector<EvalKey<Element>>> omap{{it->first, it->second}};
Serial::Serialize(omap, ser, sertype);
}
return true;
}
/**
* @brief Serializes all EvalMult keys associated with the given CryptoContext
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param cc the CryptoContext whose keys should be serialized
* @return true on success
*/
template <typename ST>
static bool SerializeEvalMultKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc) {
std::map<std::string, std::vector<EvalKey<Element>>> omap;
for (const auto& [key, vec] : CryptoContextImpl<Element>::GetAllEvalMultKeys()) {
if (vec[0]->GetCryptoContext() == cc) {
omap[key] = vec;
}
}
if (omap.empty())
return false;
Serial::Serialize(omap, ser, sertype);
return true;
}
/**
* @brief Deserializes EvalMult keys
*
* @param ser stream to deserialize from
* @param sertype type of serialization
* @return true on success
* @attention Silently replaces any existing matching keys and creates a new CryptoContextImpl if necessary
*/
template <typename ST>
static bool DeserializeEvalMultKey(std::istream& ser, const ST& sertype) {
std::map<std::string, std::vector<EvalKey<Element>>> omap;
Serial::Deserialize(omap, ser, sertype);
// The deserialize call creates all contexts that need to be created...
// so, all we need to do is to insert the keys into the maps for their context(s)
for (auto& [tag, vec] : omap) {
CryptoContextImpl<Element>::InsertEvalMultKey(vec, tag);
}
return true;
}
/**
* @brief Clears the entire EvalMultKey cache
*/
static void ClearEvalMultKeys();
/**
* @brief Clears the EvalMultKey cache for the given keyTag or the entire EvalMultKey cache if keyTag is empty
* @param keyTag secret key tag
*/
static void ClearEvalMultKeys(const std::string& keyTag);
/**
* @brief Clears EvalMultKey cache for the given context
* @param cc the context to clear all EvalMultKey for
*/
static void ClearEvalMultKeys(const CryptoContext<Element>& cc);
/**
* @brief Adds the given vector of keys for the given keyTag to the map of all EvalMult keys
*
* @param evalKeyVec vector of keys
* @param keyTag secret key tag
* @attention Silently replaces any existing matching keys and if keyTag is empty, then the key tag is retrieved from evalKeyVec
*/
static void InsertEvalMultKey(const std::vector<EvalKey<Element>>& evalKeyVec, const std::string& keyTag = "");
/**
* @brief Serializes either all EvalSum keys (if keyTag is empty) or the EvalSum keys for keyTag
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param keyTag secret key tag
* @return true on success
*/
template <typename ST>
static bool SerializeEvalSumKey(std::ostream& ser, const ST& sertype, const std::string& keyTag = "") {
return CryptoContextImpl<Element>::SerializeEvalAutomorphismKey(ser, sertype, keyTag);
}
/**
* @brief Serializes all EvalSum keys associated with the given CryptoContext
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param cc the CryptoContext whose keys should be serialized
* @return true on success
*/
template <typename ST>
static bool SerializeEvalSumKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc) {
return CryptoContextImpl<Element>::SerializeEvalAutomorphismKey(ser, sertype, cc);
}
/**
* @brief Deserializes EvalSum keys
*
* @param ser stream to deserialize from
* @param sertype type of serialization
* @return true on success
* @attention Silently replaces any existing matching keys and creates a new CryptoContextImpl if necessary
*/
template <typename ST>
static bool DeserializeEvalSumKey(std::istream& ser, const ST& sertype) {
return CryptoContextImpl<Element>::DeserializeEvalAutomorphismKey(ser, sertype);
}
/**
* @brief Clears the entire EvalSumKey cache
*/
static void ClearEvalSumKeys();
/**
* @brief Clears the EvalSumKey cache for the given keyTag or the entire EvalSumKey cache if keyTag is empty
* @param keyTag secret key tag
*/
static void ClearEvalSumKeys(const std::string& keyTag);
/**
* @brief Clears EvalSumKey cache for the given context
* @param cc the context to clear all EvalSumKey for
*/
static void ClearEvalSumKeys(const CryptoContext<Element> cc);
/**
* @brief Adds the given map of keys for the given keyTag to the map of all EvalSum keys
*
* @param mapToInsert map of keys
* @param keyTag secret key tag
* @attention Silently replaces any existing matching keys and if keyTag is empty, then the key tag is retrieved from mapToInsert
*/
static void InsertEvalSumKey(const std::shared_ptr<std::map<uint32_t, EvalKey<Element>>> mapToInsert,
std::string keyTag = "") {
CryptoContextImpl<Element>::InsertEvalAutomorphismKey(mapToInsert, keyTag);
}
/**
* @brief Serializes either all EvalAutomorphism keys (if keyTag is empty) or the EvalAutomorphism keys for keyTag
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param keyTag secret key tag
* @return true on success
*/
template <typename ST>
static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, const std::string& keyTag = "") {
// TODO (dsuponit): do we need Serailize/Deserialized to return bool?
std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>>* smap;
std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>> omap;
if (keyTag.length() == 0) {
smap = &CryptoContextImpl<Element>::GetAllEvalAutomorphismKeys();
}
else {
const auto keys = CryptoContextImpl<Element>::GetEvalAutomorphismKeyMapPtr(keyTag);
omap[keyTag] = keys;
smap = &omap;
}
Serial::Serialize(*smap, ser, sertype);
return true;
}
/**
* @brief Serializes all EvalAutomorphism keys associated with the given CryptoContext
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param cc the CryptoContext whose keys should be serialized
* @return true on success
*/
template <typename ST>
static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, const CryptoContext<Element> cc) {
std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>> omap;
for (const auto& k : CryptoContextImpl<Element>::GetAllEvalAutomorphismKeys()) {
if (k.second->begin()->second->GetCryptoContext() == cc) {
omap[k.first] = k.second;
}
}
if (omap.empty())
return false;
Serial::Serialize(omap, ser, sertype);
return true;
}
/**
* @brief Serializes EvalAutomorphism keys for an array of specific indices associated with the given keyTag
*
* @param ser stream to serialize to
* @param sertype type of serialization
* @param keyTag secret key tag
* @param indexList array of specific indices to serialize keys for
* @return true on success
*/
template <typename ST>
static bool SerializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, const std::string& keyTag,
const std::vector<uint32_t>& indexList) {
std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>> keyMap = {
{keyTag, CryptoContextImpl<Element>::GetPartialEvalAutomorphismKeyMapPtr(keyTag, indexList)}};
Serial::Serialize(keyMap, ser, sertype);
return true;
}
/**
* @brief Deserializes EvalAutomorphism keys for an array of specific indices associated with the given keyTag
*
* @param ser stream to deserialize from
* @param sertype type of serialization
* @param keyTag secret key tag
* @param indexList array of specific indices to deserialize keys for
* @return true on success
*/
template <typename ST>
static bool DeserializeEvalAutomorphismKey(std::ostream& ser, const ST& sertype, const std::string& keyTag,
const std::vector<uint32_t>& indexList) {
if (indexList.empty())
OPENFHE_THROW("indexList may not be empty");
if (keyTag.empty())
OPENFHE_THROW("keyTag may not be empty");
std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>> allDeserKeys;
Serial::Deserialize(allDeserKeys, ser, sertype);
const auto& keyMapIt = allDeserKeys.find(keyTag);
if (keyMapIt == allDeserKeys.end()) {
OPENFHE_THROW("Deserialized automorphism keys are not generated for ID [" + keyTag + "].");
}
// create a new map with evalkeys for the specified indices
std::map<uint32_t, EvalKey<Element>> newMap;
for (const uint32_t indx : indexList) {
const auto& key = keyMapIt->find(indx);
if (key == keyMapIt->end()) {
OPENFHE_THROW("No automorphism key generated for index [" + std::to_string(indx) + "] within keyTag [" +
keyTag + "].");
}
newMap[indx] = key->second;
}
CryptoContextImpl<Element>::InsertEvalAutomorphismKey(
std::make_shared<std::map<uint32_t, EvalKey<Element>>>(newMap), keyTag);
return true;
}
/**
* @brief Deserializes EvalAutomorphism keys
*
* @param ser stream to deserialize from
* @param sertype type of serialization
* @return true on success
* @attention Silently replaces any existing matching keys and creates a new CryptoContextImpl if necessary
*/
template <typename ST>
static bool DeserializeEvalAutomorphismKey(std::istream& ser, const ST& sertype) {
std::map<std::string, std::shared_ptr<std::map<uint32_t, EvalKey<Element>>>> keyMap;
Serial::Deserialize(keyMap, ser, sertype);
// The deserialize call created any contexts that needed to be created....
// so all we need to do is put the keys into the maps for their context
for (auto& k : keyMap) {
CryptoContextImpl<Element>::InsertEvalAutomorphismKey(k.second, k.first);
}
return true;
}
/**
* @brief Clears the entire EvalAutomorphismKey cache
*/
static void ClearEvalAutomorphismKeys();