keys.h
1 /* Copyright (C) 2012-2020 IBM Corp.
2  * This program is Licensed under the Apache License, Version 2.0
3  * (the "License"); you may not use this file except in compliance
4  * with the License. You may obtain a copy of the License at
5  * http://www.apache.org/licenses/LICENSE-2.0
6  * Unless required by applicable law or agreed to in writing, software
7  * distributed under the License is distributed on an "AS IS" BASIS,
8  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9  * See the License for the specific language governing permissions and
10  * limitations under the License. See accompanying LICENSE file.
11  */
12 
13 #ifndef HELIB_KEYS_H
14 #define HELIB_KEYS_H
23 #include <helib/keySwitching.h>
24 #include <helib/EncodedPtxt.h>
25 
26 namespace helib {
27 
28 #define HELIB_KSS_UNKNOWN (0)
29 // unknown KS strategy
30 
31 #define HELIB_KSS_FULL (1)
32 // all KS matrices
33 
34 #define HELIB_KSS_BSGS (2)
35 // baby step/giant step strategy
36 
37 #define HELIB_KSS_MIN (3)
38 // minimal strategy (for g_i, and for g_i^{-ord_i} for bad dims)
39 
44 class PubKey
45 { // The public key
46  const Context& context; // The context
47 
48 private:
52  Ctxt pubEncrKey;
53 
54  std::vector<double> skBounds;
55  // High-probability bounds on L-infty norm of secret keys
56 
57  std::vector<KeySwitch> keySwitching; // The key-switching matrices
58 
59  // The keySwitchMap structure contains pointers to key-switching matrices
60  // for re-linearizing automorphisms. The entry keySwitchMap[i][n] contains
61  // the index j such that keySwitching[j] is the first matrix one needs to
62  // use when re-linearizing s_i(X^n).
63  std::vector<std::vector<long>> keySwitchMap;
64 
65  NTL::Vec<long> KS_strategy; // NTL Vec's support I/O, which is more convenient
66 
67  // bootstrapping data
68 
69  long recryptKeyID; // index of the bootstrapping key
70  Ctxt recryptEkey; // the key itself, encrypted under key #0
71 
72 public:
77  static constexpr std::string_view typeName = "PubKey";
78 
79  PubKey() = delete;
80 
81  explicit PubKey(const Context& _context);
82 
84  PubKey(const PubKey& other);
85 
87  virtual ~PubKey() = default;
88 
90  virtual void clear();
91 
92  bool operator==(const PubKey& other) const;
93  bool operator!=(const PubKey& other) const;
94 
95  // Access methods
96  const Context& getContext() const;
97  long getPtxtSpace() const;
98  bool keyExists(long keyID) const;
99 
101  double getSKeyBound(long keyID = 0) const;
102 
105  const std::vector<KeySwitch>& keySWlist() const;
106 
109  const KeySwitch& getKeySWmatrix(const SKHandle& from, long toID = 0) const;
110  const KeySwitch& getKeySWmatrix(long fromSPower,
111  long fromXPower,
112  long fromID = 0,
113  long toID = 0) const;
114 
115  bool haveKeySWmatrix(const SKHandle& from, long toID = 0) const;
116 
117  bool haveKeySWmatrix(long fromSPower,
118  long fromXPower,
119  long fromID = 0,
120  long toID = 0) const;
121 
123  const KeySwitch& getAnyKeySWmatrix(const SKHandle& from) const;
124  bool haveAnyKeySWmatrix(const SKHandle& from) const;
125 
128  const KeySwitch& getNextKSWmatrix(long fromXPower, long fromID = 0) const;
129 
131 
134  bool isReachable(long k, long keyID = 0) const;
135 
138  void setKeySwitchMap(long keyId = 0); // Computes the keySwitchMap pointers
139 
142  long getKSStrategy(long dim) const;
143 
146  void setKSStrategy(long dim, int val);
147 
160  // VJS-FIXME: these routine have a number of issues and should
161  // be deprecated in favor of the new EncodedPtxt-based routines
162 
168  long Encrypt(Ctxt& ciphertxt,
169  const NTL::ZZX& plaintxt,
170  long ptxtSpace,
171  bool highNoise) const;
177  long Encrypt(Ctxt& ciphertxt,
178  const zzX& plaintxt,
179  long ptxtSpace,
180  bool highNoise) const;
181 
187  void CKKSencrypt(Ctxt& ciphertxt,
188  const NTL::ZZX& plaintxt,
189  double ptxtSize = 1.0,
190  double scaling = 0.0) const;
196  void CKKSencrypt(Ctxt& ciphertxt,
197  const zzX& plaintxt,
198  double ptxtSize = 1.0,
199  double scaling = 0.0) const;
200 
201  // These methods are overridden by secret-key Encrypt
202  virtual long Encrypt(Ctxt& ciphertxt,
203  const NTL::ZZX& plaintxt,
204  long ptxtSpace = 0) const;
205  virtual long Encrypt(Ctxt& ciphertxt,
206  const zzX& plaintxt,
207  long ptxtSpace = 0) const;
208 
216  template <typename Scheme>
217  void Encrypt(Ctxt& ciphertxt, const Ptxt<Scheme>& plaintxt) const;
218 
219  //=============== new EncodedPtxt interface ==================
220 
221  virtual void Encrypt(Ctxt& ctxt, const EncodedPtxt& eptxt) const;
222  virtual void Encrypt(Ctxt& ctxt, const EncodedPtxt_BGV& eptxt) const;
223  virtual void Encrypt(Ctxt& ctxt, const EncodedPtxt_CKKS& eptxt) const;
224 
225  //============================================================
226 
227  bool isCKKS() const;
228  // NOTE: Is taking the alMod from the context the right thing to do?
229 
230  bool isBootstrappable() const;
231  void reCrypt(Ctxt& ctxt) const; // bootstrap a ciphertext to reduce noise
232  void thinReCrypt(Ctxt& ctxt) const; // bootstrap a "thin" ciphertext, where
233  // slots are assumed to contain constants
234 
235  friend class SecKey;
236  friend std::ostream& operator<<(std::ostream& str, const PubKey& pk);
237  friend std::istream& operator>>(std::istream& str, PubKey& pk);
238 
243  void writeTo(std::ostream& str) const;
244 
251  static PubKey readFrom(std::istream& str, const Context& context);
252 
258  void writeToJSON(std::ostream& str) const;
259 
264  JsonWrapper writeToJSON() const;
265 
273  static PubKey readFromJSON(std::istream& str, const Context& context);
274 
282  static PubKey readFromJSON(const JsonWrapper& j, const Context& context);
283 
289  void readJSON(std::istream& str);
290 
296  void readJSON(const JsonWrapper& j);
297 
298  // defines plaintext space for the bootstrapping encrypted secret key
299  static long ePlusR(long p);
300 
301  // A hack to increase the plaintext space, you'd better
302  // know what you are doing when using it.
303  void hackPtxtSpace(long p2r) { pubEncrKey.ptxtSpace = p2r; }
304 };
305 
310 class SecKey : public PubKey
311 { // The secret key
312 private:
313  friend class KeySwitch;
314  std::vector<DoubleCRT> sKeys; // The secret key(s) themselves
315  explicit SecKey(const PubKey& pk);
316 
317 public:
322  static constexpr std::string_view typeName = "SecKey";
323 
324  // Disable default constructor
325  SecKey() = delete;
326 
327  // Default destructor
328  ~SecKey() override = default;
329 
330  // Constructors just call the ones for the base class
331  explicit SecKey(const Context& _context);
332 
333  bool operator==(const SecKey& other) const;
334  bool operator!=(const SecKey& other) const;
335 
337  void clear() override;
338 
345  long ImportSecKey(const DoubleCRT& sKey,
346  double bound,
347  long ptxtSpace = 0,
348  long maxDegKswitch = 3);
349 
352  long GenSecKey(long ptxtSpace = 0, long maxDegKswitch = 3);
353 
360  void GenKeySWmatrix(long fromSPower,
361  long fromXPower,
362  long fromKeyIdx = 0,
363  long toKeyIdx = 0,
364  long ptxtSpace = 0);
365 
366  // Decryption
367  void Decrypt(NTL::ZZX& plaintxt, const Ctxt& ciphertxt) const;
368 
377  // TODO: document this better (especially the prec parameter)
378  template <typename Scheme>
379  void Decrypt(Ptxt<Scheme>& plaintxt,
380  const Ctxt& ciphertxt,
381  OptLong prec = OptLong()) const;
382 
385  void Decrypt(NTL::ZZX& plaintxt, const Ctxt& ciphertxt, NTL::ZZX& f) const;
386 
388  long skEncrypt(Ctxt& ctxt,
389  const NTL::ZZX& ptxt,
390  long ptxtSpace,
391  long skIdx) const;
392  long skEncrypt(Ctxt& ctxt, const zzX& ptxt, long ptxtSpace, long skIdx) const;
393 
394  // These methods override the public-key Encrypt methods
395  long Encrypt(Ctxt& ciphertxt,
396  const NTL::ZZX& plaintxt,
397  long ptxtSpace = 0) const override;
398  long Encrypt(Ctxt& ciphertxt,
399  const zzX& plaintxt,
400  long ptxtSpace = 0) const override;
401 
402  //=============== new EncodedPtxt interface ==================
403 
404  virtual void Encrypt(Ctxt& ctxt, const EncodedPtxt& eptxt) const override;
405  virtual void Encrypt(Ctxt& ctxt, const EncodedPtxt_BGV& eptxt) const override;
406  virtual void Encrypt(Ctxt& ctxt,
407  const EncodedPtxt_CKKS& eptxt) const override;
408 
409  //============================================================
410 
412  long genRecryptData();
413 
418  const DoubleCRT& getRecryptKey() const { return sKeys[recryptKeyID]; }
419 
420  friend std::ostream& operator<<(std::ostream& str, const SecKey& sk);
421  friend std::istream& operator>>(std::istream& str, SecKey& sk);
422 
427  void writeTo(std::ostream& str) const;
428 
435  static SecKey readFrom(std::istream& str, const Context& context);
436 
442  void writeToJSON(std::ostream& str) const;
443 
448  JsonWrapper writeToJSON() const;
449 
457  static SecKey readFromJSON(std::istream& str, const Context& context);
458 
466  static SecKey readFromJSON(const JsonWrapper& j, const Context& context);
467 
473  void readJSON(std::istream& str);
474 
480  void readJSON(const JsonWrapper& j);
481 
482  // TODO: Add a similar method for binary serialization
483  // This just writes the derived part, not including the public key
484  std::ostream& writeSecKeyDerivedASCII(std::ostream& str) const;
485 };
486 
490 double RLWE(DoubleCRT& c0,
491  DoubleCRT& c1,
492  const DoubleCRT& s,
493  long p,
494  NTL::ZZ* prgSeed = nullptr);
495 
497 double RLWE1(DoubleCRT& c0, const DoubleCRT& c1, const DoubleCRT& s, long p);
498 
499 } // namespace helib
500 
501 #endif // HELIB_KEYS_H
Maintaining the HE scheme parameters.
Definition: Context.h:100
A Ctxt object holds a single ciphertext.
Definition: Ctxt.h:396
Implementing polynomials (elements in the ring R_Q) in double-CRT form.
Definition: DoubleCRT.h:76
Definition: EncodedPtxt.h:21
Definition: EncodedPtxt.h:39
Definition: EncodedPtxt.h:143
Key-switching matrices.
Definition: keySwitching.h:87
Represents the set of long int's plus a distinguished value that can be used to denote "undefined"....
Definition: NumbTh.h:998
An object that mimics the functionality of the Ctxt object, and acts as a convenient entry point for ...
Definition: Ptxt.h:188
The public key.
Definition: keys.h:45
bool operator!=(const PubKey &other) const
Definition: keys.cpp:264
long Encrypt(Ctxt &ciphertxt, const NTL::ZZX &plaintxt, long ptxtSpace, bool highNoise) const
Definition: keys.cpp:351
const KeySwitch & getNextKSWmatrix(long fromXPower, long fromID=0) const
Get the next matrix to use for multi-hop automorphism See Section 3.2.2 in the design document.
Definition: keys.cpp:303
static PubKey readFrom(std::istream &str, const Context &context)
Read from the stream the serialized PubKey object in binary format.
Definition: keys.cpp:916
friend std::istream & operator>>(std::istream &str, PubKey &pk)
Definition: keys.cpp:872
const KeySwitch & getKeySWmatrix(const SKHandle &from, long toID=0) const
Find a key-switching matrix by its indexes. If no such matrix exists it returns a dummy matrix with t...
Definition: keys.cpp:167
void setKSStrategy(long dim, int val)
set KS strategy for dimension dim dim == -1 is Frobenius
Definition: keys.cpp:328
void readJSON(std::istream &str)
In-place read from the stream the serialized public key (PubKey) object using JSON format.
Definition: keys.cpp:1008
void writeTo(std::ostream &str) const
Write out the PubKey object in binary format.
Definition: keys.cpp:881
void Encrypt(Ctxt &ciphertxt, const Ptxt< Scheme > &plaintxt) const
Encrypts a plaintext into a ciphertext.
long getKSStrategy(long dim) const
get KS strategy for dimension dim dim == -1 is Frobenius
Definition: keys.cpp:314
void reCrypt(Ctxt &ctxt) const
Definition: recryption.cpp:367
bool isReachable(long k, long keyID=0) const
Is it possible to re-linearize the automorphism X -> X^k See Section 3.2.2 in the design document (Ke...
Definition: keys.cpp:309
const KeySwitch & getAnyKeySWmatrix(const SKHandle &from) const
Is there a matrix from this key to any base key?
Definition: keys.cpp:188
bool haveAnyKeySWmatrix(const SKHandle &from) const
Definition: keys.cpp:298
static PubKey readFromJSON(std::istream &str, const Context &context)
Read from the stream the serialized public key (PubKey) object using JSON format.
Definition: keys.cpp:992
void setKeySwitchMap(long keyId=0)
Compute the reachability graph of key-switching matrices See Section 3.2.2 in the design document (Ke...
Definition: keys.cpp:115
friend std::ostream & operator<<(std::ostream &str, const PubKey &pk)
Definition: keys.cpp:866
virtual void clear()
Clear all public-key data.
Definition: keys.cpp:105
bool keyExists(long keyID) const
Definition: keys.cpp:268
JsonWrapper writeToJSON() const
Write out the public key (PubKey) object to a JsonWrapper.
Definition: keys.cpp:974
long getPtxtSpace() const
Definition: keys.cpp:267
const Context & getContext() const
Definition: keys.cpp:266
PubKey()=delete
virtual ~PubKey()=default
Default destructor.
bool haveKeySWmatrix(const SKHandle &from, long toID=0) const
Definition: keys.cpp:285
void CKKSencrypt(Ctxt &ciphertxt, const NTL::ZZX &plaintxt, double ptxtSize=1.0, double scaling=0.0) const
Definition: keys.cpp:494
bool isCKKS() const
Definition: keys.cpp:858
static long ePlusR(long p)
void thinReCrypt(Ctxt &ctxt) const
Definition: recryption.cpp:940
bool isBootstrappable() const
Definition: keys.cpp:864
void hackPtxtSpace(long p2r)
Definition: keys.h:303
const std::vector< KeySwitch > & keySWlist() const
Definition: keys.cpp:275
bool operator==(const PubKey &other) const
Definition: keys.cpp:209
double getSKeyBound(long keyID=0) const
The size of the secret key.
Definition: keys.cpp:273
static constexpr std::string_view typeName
Class label to be added to JSON serialization as object type information.
Definition: keys.h:77
A handle, describing the secret-key element that "matches" a part, of the form s^r(X^t).
Definition: Ctxt.h:81
The secret key.
Definition: keys.h:311
bool operator!=(const SecKey &other) const
Definition: keys.cpp:1078
void writeTo(std::ostream &str) const
Write out the SecKey object in binary format.
Definition: keys.cpp:1729
JsonWrapper writeToJSON() const
Write out the secret key (SecKey) object to a JsonWrapper.
Definition: keys.cpp:1775
void GenKeySWmatrix(long fromSPower, long fromXPower, long fromKeyIdx=0, long toKeyIdx=0, long ptxtSpace=0)
Definition: keys.cpp:1152
const DoubleCRT & getRecryptKey() const
Getter method for the recryption key.
Definition: keys.h:418
void Decrypt(NTL::ZZX &plaintxt, const Ctxt &ciphertxt) const
Definition: keys.cpp:1251
~SecKey() override=default
static SecKey readFrom(std::istream &str, const Context &context)
Read from the stream the serialized SecKey object in binary format.
Definition: keys.cpp:1745
long Encrypt(Ctxt &ciphertxt, const NTL::ZZX &plaintxt, long ptxtSpace=0) const override
Definition: keys.cpp:1533
long genRecryptData()
Generate bootstrapping data if needed, returns index of key.
Definition: keys.cpp:1671
SecKey()=delete
long GenSecKey(long ptxtSpace=0, long maxDegKswitch=3)
Definition: keys.cpp:1132
friend std::istream & operator>>(std::istream &str, SecKey &sk)
Definition: keys.cpp:1723
bool operator==(const SecKey &other) const
Definition: keys.cpp:1063
long ImportSecKey(const DoubleCRT &sKey, double bound, long ptxtSpace=0, long maxDegKswitch=3)
Definition: keys.cpp:1092
friend std::ostream & operator<<(std::ostream &str, const SecKey &sk)
Definition: keys.cpp:1708
std::ostream & writeSecKeyDerivedASCII(std::ostream &str) const
Definition: keys.cpp:1715
static SecKey readFromJSON(std::istream &str, const Context &context)
Read from the stream the serialized secret key (SecKey) object using JSON format.
Definition: keys.cpp:1786
void readJSON(std::istream &str)
Read from the stream the serialized secret key (SecKey) object using JSON format.
Definition: keys.cpp:1804
long skEncrypt(Ctxt &ctxt, const NTL::ZZX &ptxt, long ptxtSpace, long skIdx) const
Symmetric encryption using the secret key.
Definition: keys.cpp:1417
void Decrypt(Ptxt< Scheme > &plaintxt, const Ctxt &ciphertxt, OptLong prec=OptLong()) const
Decrypt a ciphertext into a plaintext.
void clear() override
Clear all secret-key data.
Definition: keys.cpp:1080
static constexpr std::string_view typeName
Class label to be added to JSON serialization as object type information.
Definition: keys.h:322
Definition: apiAttributes.h:21
double RLWE(DoubleCRT &c0, DoubleCRT &c1, const DoubleCRT &s, long p, NTL::ZZ *prgSeed=nullptr)
Definition: keys.cpp:69
double RLWE1(DoubleCRT &c0, const DoubleCRT &c1, const DoubleCRT &s, long p)
Same as RLWE, but assumes that c1 is already chosen by the caller.
Definition: keys.cpp:33
NTL::Vec< long > zzX
Definition: zzX.h:24
Definition: JsonWrapper.h:9