aboutsummaryrefslogtreecommitdiffstats
path: root/include/mcl/she.hpp
blob: 3f45dc75e881567b7f75115737f0bd2b2f66c9d5 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
#pragma once
/**
    @file
    @brief somewhat homomorphic encryption with one-time multiplication, based on prime-order pairings
    @author MITSUNARI Shigeo(@herumi)
    see https://github.com/herumi/mcl/blob/master/misc/she/she.pdf
    @license modified new BSD license
    http://opensource.org/licenses/BSD-3-Clause

    David Mandell Freeman:
    Converting Pairing-Based Cryptosystems from Composite-Order Groups to Prime-Order Groups. EUROCRYPT 2010: 44-61
    http://theory.stanford.edu/~dfreeman/papers/subgroups.pdf
    this algorithm reduces public key size compared to the paper by Sakai's idea.

    BGN encryption
    http://theory.stanford.edu/~dfreeman/cs259c-f11/lectures/bgn
*/
#include <cmath>
#include <vector>
#include <iosfwd>
#ifndef MCLBN_FP_UNIT_SIZE
    #define MCLBN_FP_UNIT_SIZE 4
#endif
#if MCLBN_FP_UNIT_SIZE == 4
#include <mcl/bn256.hpp>
namespace mcl {
namespace bn_current = mcl::bn256;
}
#elif MCLBN_FP_UNIT_SIZE == 6
#include <mcl/bn384.hpp>
namespace mcl {
namespace bn_current = mcl::bn384;
}
#elif MCLBN_FP_UNIT_SIZE == 8
#include <mcl/bn512.hpp>
namespace mcl {
namespace bn_current = mcl::bn512;
}
#else
    #error "MCLBN_FP_UNIT_SIZE must be 4, 6, or 8"
#endif

#if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11
#include <random>
#else
#include <cybozu/random_generator.hpp>
#endif
#include <mcl/window_method.hpp>

namespace mcl { namespace she {

namespace local {

#if CYBOZU_CPP_VERSION >= CYBOZU_CPP_VERSION_CPP11
typedef std::random_device RandomDevice;
static thread_local std::random_device g_rg;
#else
static cybozu::RandomGenerator g_rg;
#endif
#ifndef MCLSHE_WIN_SIZE
    #define MCLSHE_WIN_SIZE 10
#endif
const size_t winSize = MCLSHE_WIN_SIZE;

struct KeyCount {
    uint32_t key;
    int32_t count; // power
    bool operator<(const KeyCount& rhs) const
    {
        return key < rhs.key;
    }
    bool isSame(const KeyCount& rhs) const
    {
        return key == rhs.key && count == rhs.count;
    }
};

template<class G, bool = true>
struct InterfaceForHashTable : G {
    static G& castG(InterfaceForHashTable& x) { return static_cast<G&>(x); }
    static const G& castG(const InterfaceForHashTable& x) { return static_cast<const G&>(x); }
    void clear() { clear(castG(*this)); }
    void normalize() { normalize(castG(*this)); }
    static bool isOdd(const G& P) { return P.y.isOdd(); }
    static bool isZero(const G& P) { return P.isZero(); }
    static bool isSameX(const G& P, const G& Q) { return P.x == Q.x; }
    static uint32_t getHash(const G& P) { return uint32_t(*P.x.getUnit()); }
    static void clear(G& P) { P.clear(); }
    static void normalize(G& P) { P.normalize(); }
    static void dbl(G& Q, const G& P) { G::dbl(Q, P); }
    static void neg(G& Q, const G& P) { G::neg(Q, P); }
    static void add(G& R, const G& P, const G& Q) { G::add(R, P, Q); }
    static void mul(G& Q, const G& P, int64_t x) { G::mul(Q, P, x); }
};

/*
    treat Fp12 as EC
    unitary inverse of (a, b) = (a, -b)
    then b.a.a or -b.a.a is odd
*/
template<class G>
struct InterfaceForHashTable<G, false> : G {
    static G& castG(InterfaceForHashTable& x) { return static_cast<G&>(x); }
    static const G& castG(const InterfaceForHashTable& x) { return static_cast<const G&>(x); }
    void clear() { clear(castG(*this)); }
    void normalize() { normalize(castG(*this)); }
    static bool isOdd(const G& x) { return x.b.a.a.isOdd(); }
    static bool isZero(const G& x) { return x.isOne(); }
    static bool isSameX(const G& x, const G& Q) { return x.a == Q.a; }
    static uint32_t getHash(const G& x) { return uint32_t(*x.getFp0()->getUnit()); }
    static void clear(G& x) { x = 1; }
    static void normalize(G&) { }
    static void dbl(G& y, const G& x) { G::sqr(y, x); }
    static void neg(G& Q, const G& P) { G::unitaryInv(Q, P); }
    static void add(G& z, const G& x, const G& y) { G::mul(z, x, y); }
    static void mul(G& z, const G& x, int64_t y) { G::pow(z, x, y); }
};

/*
    HashTable<EC, true> or HashTable<Fp12, false>
*/
template<class G, bool isEC = true>
class HashTable {
    typedef InterfaceForHashTable<G, isEC> I;
    typedef std::vector<KeyCount> KeyCountVec;
    KeyCountVec kcv;
    G P_;
    mcl::fp::WindowMethod<I> wm_;
    G nextP_;
    G nextNegP_;
    size_t tryNum_;
    union ic {
        uint64_t i;
        char c[8];
    };
    static void saveUint64(std::ostream& os, uint64_t v)
    {
        ic ic;
        ic.i = v;
        os.write(ic.c, sizeof(ic));
    }
    static uint64_t loadUint64(std::istream& is)
    {
        ic ic;
        is.read(ic.c, sizeof(ic));
        return ic.i;
    }
    void setWindowMethod()
    {
        const size_t bitSize = G::BaseFp::BaseFp::getBitSize();
        wm_.init(static_cast<const I&>(P_), bitSize, local::winSize);
    }
public:
    HashTable() : tryNum_(0) {}
    bool operator==(const HashTable& rhs) const
    {
        if (kcv.size() != rhs.kcv.size()) return false;
        for (size_t i = 0; i < kcv.size(); i++) {
            if (!kcv[i].isSame(rhs.kcv[i])) return false;
        }
        return P_ == rhs.P_ && nextP_ == rhs.nextP_ && tryNum_ == rhs.tryNum_;
    }
    bool operator!=(const HashTable& rhs) const { return !operator==(rhs); }
    /*
        compute log_P(xP) for |x| <= hashSize * tryNum
    */
    void init(const G& P, size_t hashSize, size_t tryNum = 0)
    {
        if (hashSize == 0) {
            kcv.clear();
            return;
        }
        if (hashSize >= 0x80000000u) throw cybozu::Exception("HashTable:init:hashSize is too large");
        P_ = P;
        tryNum_ = tryNum;
        kcv.resize(hashSize);
        G xP;
        I::clear(xP);
        for (int i = 1; i <= (int)kcv.size(); i++) {
            I::add(xP, xP, P_);
            I::normalize(xP);
            kcv[i - 1].key = I::getHash(xP);
            kcv[i - 1].count = I::isOdd(xP) ? i : -i;
        }
        nextP_ = xP;
        I::dbl(nextP_, nextP_);
        I::add(nextP_, nextP_, P_); // nextP = (hasSize * 2 + 1)P
        I::neg(nextNegP_, nextP_); // nextNegP = -nextP
        /*
            ascending order of abs(count) for same key
        */
        std::stable_sort(kcv.begin(), kcv.end());
        setWindowMethod();
    }
    void setTryNum(size_t tryNum)
    {
        this->tryNum_ = tryNum;
    }
    /*
        log_P(xP)
        find range which has same hash of xP in kcv,
        and detect it
    */
    int basicLog(G xP, bool *ok = 0) const
    {
        if (ok) *ok = true;
        if (I::isZero(xP)) return 0;
        typedef KeyCountVec::const_iterator Iter;
        KeyCount kc;
        I::normalize(xP);
        kc.key = I::getHash(xP);
        kc.count = 0;
        std::pair<Iter, Iter> p = std::equal_range(kcv.begin(), kcv.end(), kc);
        G Q;
        I::clear(Q);
        int prev = 0;
        /*
            check range which has same hash
        */
        while (p.first != p.second) {
            int count = p.first->count;
            int abs_c = std::abs(count);
            assert(abs_c >= prev); // assume ascending order
            bool neg = count < 0;
            G T;
//          I::mul(T, P, abs_c - prev);
            mulByWindowMethod(T, abs_c - prev);
            I::add(Q, Q, T);
            I::normalize(Q);
            if (I::isSameX(Q, xP)) {
                bool QisOdd = I::isOdd(Q);
                bool xPisOdd = I::isOdd(xP);
                if (QisOdd ^ xPisOdd ^ neg) return -count;
                return count;
            }
            prev = abs_c;
            ++p.first;
        }
        if (ok) {
            *ok = false;
            return 0;
        }
        throw cybozu::Exception("HashTable:basicLog:not found");
    }
    /*
        compute log_P(xP)
        call basicLog at most 2 * tryNum
    */
    int64_t log(const G& xP) const
    {
        bool ok;
        int c = basicLog(xP, &ok);
        if (ok) {
            return c;
        }
        G posP = xP, negP = xP;
        int64_t posCenter = 0;
        int64_t negCenter = 0;
        int64_t next = (int64_t)kcv.size() * 2 + 1;
        for (size_t i = 1; i < tryNum_; i++) {
            I::add(posP, posP, nextNegP_);
            posCenter += next;
            c = basicLog(posP, &ok);
            if (ok) {
                return posCenter + c;
            }
            I::add(negP, negP, nextP_);
            negCenter -= next;
            c = basicLog(negP, &ok);
            if (ok) {
                return negCenter + c;
            }
        }
        throw cybozu::Exception("HashTable:log:not found");
    }
    void save(std::ostream& os) const
    {
        saveUint64(os, kcv.size());
        saveUint64(os, tryNum_);
        os.write((const char*)&kcv[0], sizeof(kcv[0]) * kcv.size());
        os << P_.getStr(mcl::IoArray);
    }
    void load(std::istream& is)
    {
        size_t hashSize = size_t(loadUint64(is));
        kcv.resize(hashSize);
        tryNum_ = loadUint64(is);
        is.read((char*)&kcv[0], sizeof(kcv[0]) * kcv.size());
        P_.readStream(is, mcl::IoArray);
        I::mul(nextP_, P_, (hashSize * 2) + 1);
        I::neg(nextNegP_, nextP_);
        setWindowMethod();
    }
    const mcl::fp::WindowMethod<I>& getWM() const { return wm_; }
    /*
        mul(x, P, y);
    */
    template<class T>
    void mulByWindowMethod(G& x, const T& y) const
    {
        wm_.mul(static_cast<I&>(x), y);
    }
};

template<class G>
int log(const G& P, const G& xP)
{
    if (xP.isZero()) return 0;
    if (xP == P) return 1;
    G negT;
    G::neg(negT, P);
    if (xP == negT) return -1;
    G T = P;
    for (int i = 2; i < 100; i++) {
        T += P;
        if (xP == T) return i;
        G::neg(negT, T);
        if (xP == negT) return -i;
    }
    throw cybozu::Exception("she:log:not found");
}

} // mcl::she::local

template<class BN, class Fr>
struct SHET {
    typedef typename BN::G1 G1;
    typedef typename BN::G2 G2;
    typedef typename BN::Fp12 GT;

    class SecretKey;
    class PublicKey;
    class PrecomputedPublicKey;
    // additive HE
    class CipherTextA; // = CipherTextG1 + CipherTextG2
    class CipherTextGT; // multiplicative HE
    class CipherText; // CipherTextA + CipherTextGT

    static G1 P_;
    static G2 Q_;
    static GT ePQ_; // e(P, Q)
    static std::vector<bn_current::Fp6> Qcoeff_;
    static local::HashTable<G1> PhashTbl_;
    static local::HashTable<G2> QhashTbl_;
    static mcl::fp::WindowMethod<G2> Qwm_;
    typedef local::InterfaceForHashTable<GT, false> GTasEC;
    static local::HashTable<GT, false> ePQhashTbl_;
private:
    template<class G>
    class CipherTextAT {
        G S_, T_;
        friend class SecretKey;
        friend class PublicKey;
        friend class PrecomputedPublicKey;
        friend class CipherTextA;
        friend class CipherTextGT;
        bool isZero(const Fr& x) const
        {
            G xT;
            G::mul(xT, T_, x);
            return S_ == xT;
        }
    public:
        void clear()
        {
            S_.clear();
            T_.clear();
        }
        static void add(CipherTextAT& z, const CipherTextAT& x, const CipherTextAT& y)
        {
            /*
                (S, T) + (S', T') = (S + S', T + T')
            */
            G::add(z.S_, x.S_, y.S_);
            G::add(z.T_, x.T_, y.T_);
        }
        static void sub(CipherTextAT& z, const CipherTextAT& x, const CipherTextAT& y)
        {
            /*
                (S, T) - (S', T') = (S - S', T - T')
            */
            G::sub(z.S_, x.S_, y.S_);
            G::sub(z.T_, x.T_, y.T_);
        }
        static void mul(CipherTextAT& z, const CipherTextAT& x, int64_t y)
        {
            G::mul(z.S_, x.S_, y);
            G::mul(z.T_, x.T_, y);
        }
        static void neg(CipherTextAT& y, const CipherTextAT& x)
        {
            G::neg(y.S_, x.S_);
            G::neg(y.T_, x.T_);
        }
        void add(const CipherTextAT& c) { add(*this, *this, c); }
        void sub(const CipherTextAT& c) { sub(*this, *this, c); }
        std::istream& readStream(std::istream& is, int ioMode)
        {
            S_.readStream(is, ioMode);
            T_.readStream(is, ioMode);
            return is;
        }
        void getStr(std::string& str, int ioMode = 0) const
        {
            const char *sep = fp::getIoSeparator(ioMode);
            str = S_.getStr(ioMode);
            str += sep;
            str += T_.getStr(ioMode);
        }
        void setStr(const std::string& str, int ioMode = 0)
        {
            std::istringstream is(str);
            readStream(is, ioMode);
        }
        std::string getStr(int ioMode = 0) const
        {
            std::string str;
            getStr(str, ioMode);
            return str;
        }
        friend std::istream& operator>>(std::istream& is, CipherTextAT& self)
        {
            return self.readStream(is, fp::detectIoMode(G::getIoMode(), is));
        }
        friend std::ostream& operator<<(std::ostream& os, const CipherTextAT& self)
        {
            return os << self.getStr(fp::detectIoMode(G::getIoMode(), os));
        }
        bool operator==(const CipherTextAT& rhs) const
        {
            return S_ == rhs.S_ && T_ == rhs.T_;
        }
        bool operator!=(const CipherTextAT& rhs) const { return !operator==(rhs); }
        size_t serialize(void *buf, size_t maxBufSize) const
        {
            return mcl::local::serialize2(buf, maxBufSize, S_, T_);
        }
        size_t deserialize(const void *buf, size_t bufSize)
        {
            return mcl::local::deserialize2(S_, T_, buf, bufSize);
        }
    };
    /*
        g1 = millerLoop(P1, Q)
        g2 = millerLoop(P2, Q)
    */
    static void doublePairing(GT& g1, GT& g2, const G1& P1, const G1& P2, const G2& Q)
    {
#if 1
        std::vector<bn_current::Fp6> Qcoeff;
        BN::precomputeG2(Qcoeff, Q);
        BN::precomputedMillerLoop(g1, P1, Qcoeff);
        BN::finalExp(g1, g1);
        BN::precomputedMillerLoop(g2, P2, Qcoeff);
        BN::finalExp(g2, g2);
#else
        BN::pairing(g1, P1, Q);
        BN::pairing(g2, P2, Q);
#endif
    }
    static void tensorProduct(GT g[4], const G1& S1, const G1& T1, const G2& S2, const G2& T2)
    {
        /*
            (S1, T1) x (S2, T2) = (e(S1, S2), e(S1, T2), e(T1, S2), e(T1, T2))
        */
        doublePairing(g[0], g[2], S1, T1, S2);
        doublePairing(g[1], g[3], S1, T1, T2);
    }
public:

    typedef CipherTextAT<G1> CipherTextG1;
    typedef CipherTextAT<G2> CipherTextG2;

    static void init(const mcl::bn::CurveParam& cp = mcl::bn::CurveFp254BNb)
    {
        bn_current::initPairing(cp);
        BN::hashAndMapToG1(P_, "0");
        BN::hashAndMapToG2(Q_, "0");
        BN::pairing(ePQ_, P_, Q_);
        BN::precomputeG2(Qcoeff_, Q_);
    }
    /*
        set range for G1-DLP
    */
    static void setRangeForG1DLP(size_t hashSize, size_t tryNum = 0)
    {
        PhashTbl_.init(P_, hashSize, tryNum);
    }
    /*
        set range for G2-DLP
    */
    static void setRangeForG2DLP(size_t hashSize, size_t tryNum = 0)
    {
        QhashTbl_.init(Q_, hashSize, tryNum);
    }
    /*
        set range for GT-DLP
    */
    static void setRangeForGTDLP(size_t hashSize, size_t tryNum = 0)
    {
        ePQhashTbl_.init(ePQ_, hashSize, tryNum);
    }
    /*
        set range for G1/G2/GT DLP
        decode message m for |m| <= hasSize * tryNum
        decode time = O(log(hasSize) * tryNum)
        @note if tryNum = 0 then fast but require more memory(TBD)
    */
    static void setRangeForDLP(size_t hashSize, size_t tryNum = 0)
    {
        setRangeForG1DLP(hashSize, tryNum);
        setRangeForG2DLP(hashSize, tryNum);
        setRangeForGTDLP(hashSize, tryNum);
    }

    /*
        only one element is necessary for each G1 and G2.
        this is better than David Mandell Freeman's algorithm
    */
    class SecretKey {
        Fr x_, y_;
        void getPowOfePQ(GT& v, const CipherTextGT& c) const
        {
            /*
                (s, t, u, v) := (e(S, S'), e(S, T'), e(T, S'), e(T, T'))
                s v^(xy) / (t^y u^x) = s (v^x / t) ^ y / u^x
                = e(P, Q)^(mm')
            */
            GT t, u;
            GT::unitaryInv(t, c.g_[1]);
            GT::unitaryInv(u, c.g_[2]);
            GT::pow(v, c.g_[3], x_);
            v *= t;
            GT::pow(v, v, y_);
            GT::pow(u, u, x_);
            v *= u;
            v *= c.g_[0];
        }
    public:
        template<class RG>
        void setByCSPRNG(RG& rg)
        {
            x_.setRand(rg);
            y_.setRand(rg);
        }
        void setByCSPRNG() { setByCSPRNG(local::g_rg); }
        /*
            set xP and yQ
        */
        void getPublicKey(PublicKey& pub) const
        {
            pub.set(x_, y_);
        }
#if 0
        // log_x(y)
        int log(const GT& x, const GT& y) const
        {
            if (y == 1) return 0;
            if (y == x) return 1;
            GT inv;
            GT::unitaryInv(inv, x);
            if (y == inv) return -1;
            GT t = x;
            for (int i = 2; i < 100; i++) {
                t *= x;
                if (y == t) return i;
                GT::unitaryInv(inv, t);
                if (y == inv) return -i;
            }
            throw cybozu::Exception("she:dec:log:not found");
        }
#endif
        int64_t dec(const CipherTextG1& c) const
        {
            /*
                S = mP + rxP
                T = rP
                R = S - xT = mP
            */
            G1 R;
            G1::mul(R, c.T_, x_);
            G1::sub(R, c.S_, R);
            return PhashTbl_.log(R);
        }
        int64_t dec(const CipherTextG2& c) const
        {
            G2 R;
            G2::mul(R, c.T_, y_);
            G2::sub(R, c.S_, R);
            return QhashTbl_.log(R);
        }
        int64_t dec(const CipherTextA& c) const
        {
            return dec(c.c1_);
        }
        int64_t dec(const CipherTextGT& c) const
        {
            GT v;
            getPowOfePQ(v, c);
            return ePQhashTbl_.log(v);
//          return log(g, v);
        }
        int64_t dec(const CipherText& c) const
        {
            if (c.isMultiplied()) {
                return dec(c.m_);
            } else {
                return dec(c.a_);
            }
        }
        bool isZero(const CipherTextG1& c) const
        {
            return c.isZero(x_);
        }
        bool isZero(const CipherTextG2& c) const
        {
            return c.isZero(y_);
        }
        bool isZero(const CipherTextA& c) const
        {
            return c.c1_.isZero(x_);
        }
        bool isZero(const CipherTextGT& c) const
        {
            GT v;
            getPowOfePQ(v, c);
            return v.isOne();
        }
        bool isZero(const CipherText& c) const
        {
            if (c.isMultiplied()) {
                return isZero(c.m_);
            } else {
                return isZero(c.a_);
            }
        }
        std::istream& readStream(std::istream& is, int ioMode)
        {
            x_.readStream(is, ioMode);
            y_.readStream(is, ioMode);
            return is;
        }
        void getStr(std::string& str, int ioMode = 0) const
        {
            const char *sep = fp::getIoSeparator(ioMode);
            str = x_.getStr(ioMode);
            str += sep;
            str += y_.getStr(ioMode);
        }
        void setStr(const std::string& str, int ioMode = 0)
        {
            std::istringstream is(str);
            readStream(is, ioMode);
        }
        std::string getStr(int ioMode = 0) const
        {
            std::string str;
            getStr(str, ioMode);
            return str;
        }
        friend std::istream& operator>>(std::istream& is, SecretKey& self)
        {
            return self.readStream(is, fp::detectIoMode(Fr::getIoMode(), is));
        }
        friend std::ostream& operator<<(std::ostream& os, const SecretKey& self)
        {
            return os << self.getStr(fp::detectIoMode(Fr::getIoMode(), os));
        }
        bool operator==(const SecretKey& rhs) const
        {
            return x_ == rhs.x_ && y_ == rhs.y_;
        }
        bool operator!=(const SecretKey& rhs) const { return !operator==(rhs); }
        size_t serialize(void *buf, size_t maxBufSize) const
        {
            return mcl::local::serialize2(buf, maxBufSize, x_, y_);
        }
        size_t deserialize(const void *buf, size_t bufSize)
        {
            return mcl::local::deserialize2(x_, y_, buf, bufSize);
        }
    };

    class PublicKey {
        G1 xP_;
        G2 yQ_;
        friend class SecretKey;
        friend class PrecomputedPublicKey;
        /*
            (S, T) = (m P + r xP, rP)
        */
        template<class G, class RG, class I>
        static void enc1(G& S, G& T, const G& /*P*/, const G& xP, int64_t m, RG& rg, const mcl::fp::WindowMethod<I>& wm)
        {
            Fr r;
            r.setRand(rg);
//          G::mul(T, P, r);
            wm.mul(static_cast<I&>(T), r);
            G::mul(S, xP, r);
            if (m == 0) return;
            G C;
//          G::mul(C, P, m);
            wm.mul(static_cast<I&>(C), m);
            S += C;
        }
        void set(const Fr& x, const Fr& y)
        {
            G1::mul(xP_, P_, x);
            G2::mul(yQ_, Q_, y);
        }
    public:
        template<class RG>
        void enc(CipherTextG1& c, int64_t m, RG& rg) const
        {
            enc1(c.S_, c.T_, P_, xP_, m, rg, PhashTbl_.getWM());
        }
        template<class RG>
        void enc(CipherTextG2& c, int64_t m, RG& rg) const
        {
            enc1(c.S_, c.T_, Q_, yQ_, m, rg, QhashTbl_.getWM());
        }
        template<class RG>
        void enc(CipherTextA& c, int64_t m, RG& rg) const
        {
            enc(c.c1_, m, rg);
            enc(c.c2_, m, rg);
        }
        template<class RG>
        void enc(CipherTextGT& c, int64_t m, RG& rg) const
        {
            /*
                (s, t, u, v) = ((e^x)^a (e^y)^b (e^-xy)^c e^m, e^b, e^a, e^c)
                s = e(a xP + m P, Q)e(b P - c xP, yQ)
            */
            Fr ra, rb, rc;
            ra.setRand(rg);
            rb.setRand(rg);
            rc.setRand(rg);
            GT e;

            G1 P1, P2;
            G1::mul(P1, xP_, ra);
            if (m) {
//              G1::mul(P2, P, m);
                PhashTbl_.mulByWindowMethod(P2, m);
                P1 += P2;
            }
//          BN::millerLoop(c.g[0], P1, Q);
            BN::precomputedMillerLoop(c.g_[0], P1, Qcoeff_);
//          G1::mul(P1, P, rb);
            PhashTbl_.mulByWindowMethod(P1, rb);
            G1::mul(P2, xP_, rc);
            P1 -= P2;
            BN::millerLoop(e, P1, yQ_);
            c.g_[0] *= e;
            BN::finalExp(c.g_[0], c.g_[0]);
#if 1
            ePQhashTbl_.mulByWindowMethod(c.g_[1], rb);
            ePQhashTbl_.mulByWindowMethod(c.g_[2], ra);
            ePQhashTbl_.mulByWindowMethod(c.g_[3], rc);
#else
            GT::pow(c.g_[1], ePQ_, rb);
            GT::pow(c.g_[2], ePQ_, ra);
            GT::pow(c.g_[3], ePQ_, rc);
#endif
        }
        template<class RG>
        void enc(CipherText& c, int64_t m, RG& rg, bool multiplied = false) const
        {
            c.isMultiplied_ = multiplied;
            if (multiplied) {
                enc(c.m_, m, rg);
            } else {
                enc(c.a_, m, rg);
            }
        }
        void enc(CipherTextG1& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void enc(CipherTextG2& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void enc(CipherTextA& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void enc(CipherTextGT& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void enc(CipherText& c, int64_t m, bool multiplied = false) const { return enc(c, m, local::g_rg, multiplied); }
        /*
            convert from CipherTextG1 to CipherTextGT
        */
        void convert(CipherTextGT& cm, const CipherTextG1& c1) const
        {
            /*
                Enc(1) = (S, T) = (Q + r yQ, rQ) = (Q, 0) if r = 0
                cm = c1 * (Q, 0) = (S, T) * (Q, 0) = (e(S, Q), 1, e(T, Q), 1)
            */
//          doublePairing(cm.g_[0], cm.g_[2], c1.S, c1.T, Q);
            BN::precomputedMillerLoop(cm.g_[0], c1.S_, Qcoeff_);
            BN::finalExp(cm.g_[0], cm.g_[0]);
            BN::precomputedMillerLoop(cm.g_[2], c1.T_, Qcoeff_);
            BN::finalExp(cm.g_[2], cm.g_[2]);

            cm.g_[1] = 1;
            cm.g_[3] = 1;
        }
        /*
            convert from CipherTextG2 to CipherTextGT
        */
        void convert(CipherTextGT& cm, const CipherTextG2& c2) const
        {
            /*
                Enc(1) = (S, T) = (P + r xP, rP) = (P, 0) if r = 0
                cm = (P, 0) * c2
            */
            G1 zero; zero.clear();
            tensorProduct(cm.g_, P_, zero, c2.S_, c2.T_);
        }
        void convert(CipherTextGT& cm, const CipherTextA& ca) const
        {
            convert(cm, ca.c1_);
        }
        void convert(CipherText& cm, const CipherText& ca) const
        {
            if (ca.isMultiplied()) throw cybozu::Exception("she:PublicKey:convertCipherText:already isMultiplied");
            cm.isMultiplied_ = true;
            convert(cm.m_, ca.a_);
        }
        /*
            c += Enc(0)
        */
        template<class RG>
        void reRand(CipherTextG1& c, RG& rg) const
        {
            CipherTextG1 c0;
            enc(c0, 0, rg);
            CipherTextG1::add(c, c, c0);
        }
        template<class RG>
        void reRand(CipherTextG2& c, RG& rg) const
        {
            CipherTextG2 c0;
            enc(c0, 0, rg);
            CipherTextG2::add(c, c, c0);
        }
        template<class RG>
        void reRand(CipherTextA& c, RG& rg) const
        {
            CipherTextA c0;
            enc(c0, 0, rg);
            CipherTextA::add(c, c, c0);
        }
        template<class RG>
        void reRand(CipherTextGT& c, RG& rg) const
        {
#if 1 // for circuit security : 3.58Mclk -> 5.4Mclk
            CipherTextGT c0;
            enc(c0, 0, rg);
            CipherTextGT::add(c, c, c0);
#else
            /*
                add Enc(0) * Enc(0)
                (S1, T1) * (S2, T2) = (rxP, rP) * (r'yQ, r'Q)
                replace r <- rr', r' <- 1
                = (r xP, rP) * (yQ, Q)
            */
            G1 S1, T1;
            Fr r;
            r.setRand(rg);
            G1::mul(S1, xP, r);
            G1::mul(T1, P, r);
            GT g_[4];
            tensorProduct(g_, S1, T1, yQ, Q);
            for (int i = 0; i < 4; i++) {
                c.g_[i] *= g_[i];
            }
#endif
        }
        template<class RG>
        void reRand(CipherText& c, RG& rg) const
        {
            if (c.isMultiplied()) {
                reRand(c.m_, rg);
            } else {
                reRand(c.a_, rg);
            }
        }
        void reRand(CipherTextG1& c) const { reRand(c, local::g_rg); }
        void reRand(CipherTextG2& c) const { reRand(c, local::g_rg); }
        void reRand(CipherTextA& c) const { reRand(c, local::g_rg); }
        void reRand(CipherTextGT& c) const { reRand(c, local::g_rg); }
        void reRand(CipherText& c) const { reRand(c, local::g_rg); }

        std::istream& readStream(std::istream& is, int ioMode)
        {
            xP_.readStream(is, ioMode);
            yQ_.readStream(is, ioMode);
            return is;
        }
        void getStr(std::string& str, int ioMode = 0) const
        {
            const char *sep = fp::getIoSeparator(ioMode);
            str = xP_.getStr(ioMode);
            str += sep;
            str += yQ_.getStr(ioMode);
        }
        void setStr(const std::string& str, int ioMode = 0)
        {
            std::istringstream is(str);
            readStream(is, ioMode);
        }
        std::string getStr(int ioMode = 0) const
        {
            std::string str;
            getStr(str, ioMode);
            return str;
        }
        friend std::istream& operator>>(std::istream& is, PublicKey& self)
        {
            return self.readStream(is, fp::detectIoMode(G1::getIoMode(), is));
        }
        friend std::ostream& operator<<(std::ostream& os, const PublicKey& self)
        {
            return os << self.getStr(fp::detectIoMode(G1::getIoMode(), os));
        }
        bool operator==(const PublicKey& rhs) const
        {
            return xP_ == rhs.xP_ && yQ_ == rhs.yQ_;
        }
        bool operator!=(const PublicKey& rhs) const { return !operator==(rhs); }
        size_t serialize(void *buf, size_t maxBufSize) const
        {
            return mcl::local::serialize2(buf, maxBufSize, xP_, yQ_);
        }
        size_t deserialize(const void *buf, size_t bufSize)
        {
            return mcl::local::deserialize2(xP_, yQ_, buf, bufSize);
        }
    };

    class PrecomputedPublicKey {
        typedef local::InterfaceForHashTable<GT, false> GTasEC;
        typedef mcl::fp::WindowMethod<GTasEC> GTwin;
        GT exPQ_;
        GT eyPQ_;
        GT exyPQ_;
        GTwin exPQwm_;
        GTwin eyPQwm_;
        GTwin exyPQwm_;
        mcl::fp::WindowMethod<G1> xPwm_;
        mcl::fp::WindowMethod<G2> yQwm_;
        template<class T>
        void mulByWindowMethod(GT& x, const GTwin& wm, const T& y) const
        {
            wm.mul(static_cast<GTasEC&>(x), y);
        }
    public:
        void init(const PublicKey& pub)
        {
            BN::pairing(exPQ_, pub.xP_, Q_);
            BN::pairing(eyPQ_, P_, pub.yQ_);
            BN::pairing(exyPQ_, pub.xP_, pub.yQ_);
            const size_t bitSize = Fr::getBitSize();
            exPQwm_.init(static_cast<const GTasEC&>(exPQ_), bitSize, local::winSize);
            eyPQwm_.init(static_cast<const GTasEC&>(eyPQ_), bitSize, local::winSize);
            exyPQwm_.init(static_cast<const GTasEC&>(exyPQ_), bitSize, local::winSize);
            xPwm_.init(pub.xP_, bitSize, local::winSize);
            yQwm_.init(pub.yQ_, bitSize, local::winSize);
        }
        /*
            (S, T) = (m P + r xP, rP)
        */
        template<class G, class RG, class I>
        void enc1(G& S, G& T, int64_t m, RG& rg, const mcl::fp::WindowMethod<I>& Pwm, const mcl::fp::WindowMethod<G>& xPwm) const
        {
            Fr r;
            r.setRand(rg);
            Pwm.mul(static_cast<I&>(T), r);
            xPwm.mul(S, r);
            if (m == 0) return;
            G C;
            Pwm.mul(static_cast<I&>(C), m);
            S += C;
        }
        template<class RG>
        void enc(CipherTextG1& c, int64_t m, RG& rg) const
        {
            enc1(c.S_, c.T_, m, rg, PhashTbl_.getWM(), xPwm_);
        }
        template<class RG>
        void enc(CipherTextG2& c, int64_t m, RG& rg) const
        {
            enc1(c.S_, c.T_, m, rg, QhashTbl_.getWM(), yQwm_);
        }
        template<class RG>
        void enc(CipherTextGT& c, int64_t m, RG& rg) const
        {
            /*
                (s, t, u, v) = (e^m e^(xya), (e^x)^b, (e^y)^c, e^(b + c - a))
            */
            Fr ra, rb, rc;
            ra.setRand(rg);
            rb.setRand(rg);
            rc.setRand(rg);
            GT t;
            ePQhashTbl_.mulByWindowMethod(c.g_[0], m); // e^m
            mulByWindowMethod(t, exyPQwm_, ra); // (e^xy)^a
            c.g_[0] *= t;
            mulByWindowMethod(c.g_[1], exPQwm_, rb); // (e^x)^b
            mulByWindowMethod(c.g_[2], eyPQwm_, rc); // (e^y)^c
            rb = rb + rc - ra;
            ePQhashTbl_.mulByWindowMethod(c.g_[3], rb);
        }
        template<class CT, class RG>
        void reRandT(CT& c, RG& rg) const
        {
            CT c0;
            enc(c0, 0, rg);
            CT::add(c, c, c0);
        }
        template<class RG> void reRand(CipherTextG1& c, RG& rg) const { reRandT(c, rg); }
        template<class RG> void reRand(CipherTextG2& c, RG& rg) const { reRandT(c, rg); }
        template<class RG> void reRand(CipherTextGT& c, RG& rg) const { reRandT(c, rg); }
        void enc(CipherTextG1& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void enc(CipherTextG2& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void enc(CipherTextGT& c, int64_t m) const { return enc(c, m, local::g_rg); }
        void reRand(CipherTextG1& c) const { reRand(c, local::g_rg); }
        void reRand(CipherTextG2& c) const { reRand(c, local::g_rg); }
        void reRand(CipherTextGT& c) const { reRand(c, local::g_rg); }
    };

    class CipherTextA {
        CipherTextG1 c1_;
        CipherTextG2 c2_;
        friend class SecretKey;
        friend class PublicKey;
        friend class CipherTextGT;
    public:
        void clear()
        {
            c1_.clear();
            c2_.clear();
        }
        static void add(CipherTextA& z, const CipherTextA& x, const CipherTextA& y)
        {
            CipherTextG1::add(z.c1_, x.c1_, y.c1_);
            CipherTextG2::add(z.c2_, x.c2_, y.c2_);
        }
        static void sub(CipherTextA& z, const CipherTextA& x, const CipherTextA& y)
        {
            CipherTextG1::sub(z.c1_, x.c1_, y.c1_);
            CipherTextG2::sub(z.c2_, x.c2_, y.c2_);
        }
        static void mul(CipherTextA& z, const CipherTextA& x, int64_t y)
        {
            CipherTextG1::mul(z.c1_, x.c1_, y);
            CipherTextG2::mul(z.c2_, x.c2_, y);
        }
        static void neg(CipherTextA& y, const CipherTextA& x)
        {
            CipherTextG1::neg(y.c1_, x.c1_);
            CipherTextG2::neg(y.c2_, x.c2_);
        }
        void add(const CipherTextA& c) { add(*this, *this, c); }
        void sub(const CipherTextA& c) { sub(*this, *this, c); }
        std::istream& readStream(std::istream& is, int ioMode)
        {
            c1_.readStream(is, ioMode);
            c2_.readStream(is, ioMode);
            return is;
        }
        void getStr(std::string& str, int ioMode = 0) const
        {
            const char *sep = fp::getIoSeparator(ioMode);
            str = c1_.getStr(ioMode);
            str += sep;
            str += c2_.getStr(ioMode);
        }
        void setStr(const std::string& str, int ioMode = 0)
        {
            std::istringstream is(str);
            readStream(is, ioMode);
        }
        std::string getStr(int ioMode = 0) const
        {
            std::string str;
            getStr(str, ioMode);
            return str;
        }
        friend std::istream& operator>>(std::istream& is, CipherTextA& self)
        {
            return self.readStream(is, fp::detectIoMode(G1::getIoMode(), is));
        }
        friend std::ostream& operator<<(std::ostream& os, const CipherTextA& self)
        {
            return os << self.getStr(fp::detectIoMode(G1::getIoMode(), os));
        }
        bool operator==(const CipherTextA& rhs) const
        {
            return c1_ == rhs.c1_ && c2_ == rhs.c2_;
        }
        bool operator!=(const CipherTextA& rhs) const { return !operator==(rhs); }
    };

    class CipherTextGT {
        GT g_[4];
        friend class SecretKey;
        friend class PublicKey;
        friend class PrecomputedPublicKey;
        friend class CipherTextA;
    public:
        void clear()
        {
            for (int i = 0; i < 4; i++) {
                g_[i].setOne();
            }
        }
        static void add(CipherTextGT& z, const CipherTextGT& x, const CipherTextGT& y)
        {
            /*
                (g[i]) + (g'[i]) = (g[i] * g'[i])
            */
            for (int i = 0; i < 4; i++) {
                GT::mul(z.g_[i], x.g_[i], y.g_[i]);
            }
        }
        static void sub(CipherTextGT& z, const CipherTextGT& x, const CipherTextGT& y)
        {
            /*
                (g[i]) - (g'[i]) = (g[i] / g'[i])
            */
            GT t;
            for (size_t i = 0; i < 4; i++) {
                GT::unitaryInv(t, y.g_[i]);
                GT::mul(z.g_[i], x.g_[i], t);
            }
        }
        static void mul(CipherTextGT& z, const CipherTextG1& x, const CipherTextG2& y)
        {
            /*
                (S1, T1) * (S2, T2) = (e(S1, S2), e(S1, T2), e(T1, S2), e(T1, T2))
            */
            tensorProduct(z.g_, x.S_, x.T_, y.S_, y.T_);
        }
        static void mul(CipherTextGT& z, const CipherTextA& x, const CipherTextA& y)
        {
            mul(z, x.c1_, y.c2_);
        }
        static void mul(CipherTextGT& z, const CipherTextGT& x, int64_t y)
        {
            for (int i = 0; i < 4; i++) {
                GT::pow(z.g_[i], x.g_[i], y);
            }
        }
        void add(const CipherTextGT& c) { add(*this, *this, c); }
        void sub(const CipherTextGT& c) { sub(*this, *this, c); }
        std::istream& readStream(std::istream& is, int ioMode)
        {
            for (int i = 0; i < 4; i++) {
                g_[i].readStream(is, ioMode);
            }
            return is;
        }
        void getStr(std::string& str, int ioMode = 0) const
        {
            const char *sep = fp::getIoSeparator(ioMode);
            str = g_[0].getStr(ioMode);
            for (int i = 1; i < 4; i++) {
                str += sep;
                str += g_[i].getStr(ioMode);
            }
        }
        void setStr(const std::string& str, int ioMode = 0)
        {
            std::istringstream is(str);
            readStream(is, ioMode);
        }
        std::string getStr(int ioMode = 0) const
        {
            std::string str;
            getStr(str, ioMode);
            return str;
        }
        friend std::istream& operator>>(std::istream& is, CipherTextGT& self)
        {
            return self.readStream(is, fp::detectIoMode(G1::getIoMode(), is));
        }
        friend std::ostream& operator<<(std::ostream& os, const CipherTextGT& self)
        {
            return os << self.getStr(fp::detectIoMode(G1::getIoMode(), os));
        }
        bool operator==(const CipherTextGT& rhs) const
        {
            for (int i = 0; i < 4; i++) {
                if (g_[i] != rhs.g_[i]) return false;
            }
            return true;
        }
        bool operator!=(const CipherTextGT& rhs) const { return !operator==(rhs); }
        size_t serialize(void *buf, size_t maxBufSize) const
        {
            char *p = reinterpret_cast<char*>(buf);
            const size_t n1 = mcl::local::serialize2(p, maxBufSize, g_[0], g_[1]);
            if (n1 == 0) return 0;
            p += n1; maxBufSize -= n1;
            const size_t n2 = mcl::local::serialize2(p, maxBufSize, g_[2], g_[3]);
            if (n2 == 0) return 0;
            return n1 + n2;
        }
        size_t deserialize(const void *buf, size_t bufSize)
        {
            const char *p = reinterpret_cast<const char*>(buf);
            const size_t n1 = mcl::local::deserialize2(g_[0], g_[1], p, bufSize);
            if (n1 == 0) return 0;
            p += n1; bufSize -= n1;
            const size_t n2 = mcl::local::deserialize2(g_[2], g_[3], p, bufSize);
            if (n2 == 0) return 0;
            return n1 + n2;
        }
    };

    class CipherText {
        bool isMultiplied_;
        CipherTextA a_;
        CipherTextGT m_;
        friend class SecretKey;
        friend class PublicKey;
    public:
        CipherText() : isMultiplied_(false) {}
        void clearAsAdded()
        {
            isMultiplied_ = false;
            a_.clear();
        }
        void clearAsMultiplied()
        {
            isMultiplied_ = true;
            m_.clear();
        }
        bool isMultiplied() const { return isMultiplied_; }
        static void add(CipherText& z, const CipherText& x, const CipherText& y)
        {
            if (x.isMultiplied() && y.isMultiplied()) {
                z.isMultiplied_ = true;
                CipherTextGT::add(z.m_, x.m_, y.m_);
                return;
            }
            if (!x.isMultiplied() && !y.isMultiplied()) {
                z.isMultiplied_ = false;
                CipherTextA::add(z.a_, x.a_, y.a_);
                return;
            }
            throw cybozu::Exception("she:CipherText:add:mixed CipherText");
        }
        static void sub(CipherText& z, const CipherText& x, const CipherText& y)
        {
            if (x.isMultiplied() && y.isMultiplied()) {
                z.isMultiplied_ = true;
                CipherTextGT::sub(z.m_, x.m_, y.m_);
                return;
            }
            if (!x.isMultiplied() && !y.isMultiplied()) {
                z.isMultiplied_ = false;
                CipherTextA::sub(z.a_, x.a_, y.a_);
                return;
            }
            throw cybozu::Exception("she:CipherText:sub:mixed CipherText");
        }
        static void mul(CipherText& z, const CipherText& x, const CipherText& y)
        {
            if (x.isMultiplied() || y.isMultiplied()) {
                throw cybozu::Exception("she:CipherText:mul:mixed CipherText");
            }
            z.isMultiplied_ = true;
            CipherTextGT::mul(z.m_, x.a_, y.a_);
        }
        static void mul(CipherText& z, const CipherText& x, int64_t y)
        {
            if (x.isMultiplied()) {
                CipherTextGT::mul(z.m_, x.m_, y);
            } else {
                CipherTextA::mul(z.a_, x.a_, y);
            }
        }
        void add(const CipherText& c) { add(*this, *this, c); }
        void sub(const CipherText& c) { sub(*this, *this, c); }
        void mul(const CipherText& c) { mul(*this, *this, c); }
        std::istream& readStream(std::istream& is, int ioMode)
        {
            is >> isMultiplied_;
            if (isMultiplied()) {
                m_.readStream(is, ioMode);
            } else {
                a_.readStream(is, ioMode);
            }
            return is;
        }
        void getStr(std::string& str, int ioMode = 0) const
        {
            const char *sep = fp::getIoSeparator(ioMode);
            str = isMultiplied() ? "1" : "0";
            str += sep;
            if (isMultiplied()) {
                str += m_.getStr(ioMode);
            } else {
                str += a_.getStr(ioMode);
            }
        }
        void setStr(const std::string& str, int ioMode = 0)
        {
            std::istringstream is(str);
            readStream(is, ioMode);
        }
        std::string getStr(int ioMode = 0) const
        {
            std::string str;
            getStr(str, ioMode);
            return str;
        }
        friend std::istream& operator>>(std::istream& is, CipherText& self)
        {
            return self.readStream(is, fp::detectIoMode(G1::getIoMode(), is));
        }
        friend std::ostream& operator<<(std::ostream& os, const CipherText& self)
        {
            return os << self.getStr(fp::detectIoMode(G1::getIoMode(), os));
        }
        bool operator==(const CipherTextGT& rhs) const
        {
            if (isMultiplied() != rhs.isMultiplied()) return false;
            if (isMultiplied()) {
                return m_ == rhs.m_;
            }
            return a_ == rhs.a_;
        }
        bool operator!=(const CipherTextGT& rhs) const { return !operator==(rhs); }
    };
};

template<class BN, class Fr> typename BN::G1 SHET<BN, Fr>::P_;
template<class BN, class Fr> typename BN::G2 SHET<BN, Fr>::Q_;
template<class BN, class Fr> typename BN::Fp12 SHET<BN, Fr>::ePQ_;
template<class BN, class Fr> std::vector<bn_current::Fp6> SHET<BN, Fr>::Qcoeff_;
template<class BN, class Fr> local::HashTable<typename BN::G1> SHET<BN, Fr>::PhashTbl_;
template<class BN, class Fr> local::HashTable<typename BN::G2> SHET<BN, Fr>::QhashTbl_;
template<class BN, class Fr> local::HashTable<typename BN::Fp12, false> SHET<BN, Fr>::ePQhashTbl_;
typedef mcl::she::SHET<bn_current::BN, bn_current::Fr> SHE;
typedef SHE::SecretKey SecretKey;
typedef SHE::PublicKey PublicKey;
typedef SHE::PrecomputedPublicKey PrecomputedPublicKey;
typedef SHE::CipherTextG1 CipherTextG1;
typedef SHE::CipherTextG2 CipherTextG2;
typedef SHE::CipherTextGT CipherTextGT;
typedef SHE::CipherTextA CipherTextA;
typedef CipherTextGT CipherTextGM; // old class
typedef SHE::CipherText CipherText;

} } // mcl::she