-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaillier.py
897 lines (738 loc) · 34.7 KB
/
paillier.py
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
#!/usr/bin/env python3
# Portions copyright 2012 Google Inc. All Rights Reserved.
# This file has been modified by NICTA
# This file is part of pyphe.
#
# pyphe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyphe is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pyphe. If not, see <http://www.gnu.org/licenses/>.
"""Paillier encryption library for partially homomorphic encryption."""
import random
import time
try:
from collections.abc import Mapping
except ImportError:
Mapping = dict
from phe import EncodedNumber
from phe.util import invert, powmod, mulmod, getprimeover, isqrt
import gpu_lib as gpu_cal
from test_gpu_lib import test_gxx
# Paillier cryptosystem is based on integer factorisation.
# The default is chosen to give a minimum of 128 bits of security.
# https://www.keylength.com/en/4/
# DEFAULT_KEYSIZE = 3072
DEFAULT_KEYSIZE = 1024
def generate_paillier_keypair(private_keyring=None, n_length=DEFAULT_KEYSIZE):
"""Return a new :class:`PaillierPublicKey` and :class:`PaillierPrivateKey`.
Add the private key to *private_keyring* if given.
Args:
private_keyring (PaillierPrivateKeyring): a
:class:`PaillierPrivateKeyring` on which to store the private
key.
n_length: key size in bits.
Returns:
tuple: The generated :class:`PaillierPublicKey` and
:class:`PaillierPrivateKey`
"""
p = q = n = None
n_len = 0
while n_len != n_length:
p = getprimeover(n_length // 2)
q = p
while q == p:
q = getprimeover(n_length // 2)
n = p * q
n_len = n.bit_length()
public_key = PaillierPublicKey(n)
private_key = PaillierPrivateKey(public_key, p, q)
if private_keyring is not None:
private_keyring.add(private_key)
return public_key, private_key
class PaillierPublicKey(object):
"""Contains a public key and associated encryption methods.
Args:
n (int): the modulus of the public key - see Paillier's paper.
Attributes:
g (int): part of the public key - see Paillier's paper.
n (int): part of the public key - see Paillier's paper.
nsquare (int): :attr:`n` ** 2, stored for frequent use.
max_int (int): Maximum int that may safely be stored. This can be
increased, if you are happy to redefine "safely" and lower the
chance of detecting an integer overflow.
"""
def __init__(self, n):
self.g = n + 1
self.n = n
self.nsquare = n * n
self.max_int = n // 3 - 1
def __repr__(self):
publicKeyHash = hex(hash(self))[2:]
return "<PaillierPublicKey {}>".format(publicKeyHash[:10])
def __eq__(self, other):
return self.n == other.n
def __hash__(self):
return hash(self.n)
def gpu_raw_encrypt(self, plaintextlist, r_value=None):
batch_param = []
batch_param1 = []
batch_param2 = []
nude_ciphertext_list = []
start = time.time()
for plaintext in plaintextlist:
if not isinstance(plaintext, int):
raise TypeError('Expected int type plaintext but got: %s' %
type(plaintext))
if self.n - self.max_int <= plaintext < self.n:
# Very large plaintext, take a sneaky shortcut using inverses
neg_plaintext = self.n - plaintext # = abs(plaintext - nsquare)
# avoid using gmpy2's mulmod when a * b < c
neg_ciphertext = (self.n * neg_plaintext + 1) % self.nsquare
nude_ciphertext = invert(neg_ciphertext, self.nsquare)
nude_ciphertext_list.append(nude_ciphertext)
else:
# we chose g = n + 1, so that we can exploit the fact that
# (n+1)^plaintext = n*plaintext + 1 mod n^2
nude_ciphertext = (self.n * plaintext + 1) % self.nsquare
nude_ciphertext_list.append(nude_ciphertext)
r = r_value or self.get_random_lt_n()
obfuscator = powmod(r, self.n, self.nsquare)
r_bytes = obfuscator.to_bytes(512, "little")
nsquare_bytes = self.nsquare.to_bytes(512, "little")
for i in nude_ciphertext_list:
nude_ciphertext_bytes = i.to_bytes(512, "little")
batch_param.append((nude_ciphertext_bytes,r_bytes,nsquare_bytes ))
result= gpu_cal.mulm_2048(batch_param, len(batch_param))
result2 = [int.from_bytes(i, "little")for i in result]
return result2
def raw_encrypt(self, plaintext, r_value=None):
"""Paillier encryption of a positive integer plaintext < :attr:`n`.
You probably should be using :meth:`encrypt` instead, because it
handles positive and negative ints and floats.
Args:
plaintext (int): a positive integer < :attr:`n` to be Paillier
encrypted. Typically this is an encoding of the actual
number you want to encrypt.
r_value (int): obfuscator for the ciphertext; by default (i.e.
r_value is None), a random value is used.
Returns:
int: Paillier encryption of plaintext.
Raises:
TypeError: if plaintext is not an int.
"""
if not isinstance(plaintext, int):
raise TypeError('Expected int type plaintext but got: %s' %
type(plaintext))
if self.n - self.max_int <= plaintext < self.n:
# Very large plaintext, take a sneaky shortcut using inverses
neg_plaintext = self.n - plaintext # = abs(plaintext - nsquare)
# avoid using gmpy2's mulmod when a * b < c
neg_ciphertext = (self.n * neg_plaintext + 1) % self.nsquare
nude_ciphertext = invert(neg_ciphertext, self.nsquare)
else:
# we chose g = n + 1, so that we can exploit the fact that
# (n+1)^plaintext = n*plaintext + 1 mod n^2
nude_ciphertext = (self.n * plaintext + 1) % self.nsquare
r = r_value or self.get_random_lt_n()
obfuscator = powmod(r, self.n, self.nsquare)
return mulmod(nude_ciphertext, obfuscator, self.nsquare)
def get_random_lt_n(self):
"""Return a cryptographically random number less than :attr:`n`"""
return random.SystemRandom().randrange(1, self.n)
def gpu_encrypt(self, list, precision=None, r_value=None):
encode_list = []
for value in list:
if isinstance(value, EncodedNumber):
encoding = value
encode_list.append(encoding)
else:
encoding = EncodedNumber.encode(self, value, precision)
encode_list.append(encoding)
return self.gpu_encrypt_encoded(encode_list, r_value)
def encrypt(self, value, precision=None, r_value=None):
"""Encode and Paillier encrypt a real number *value*.
Args:
value: an int or float to be encrypted.
If int, it must satisfy abs(*value*) < :attr:`n`/3.
If float, it must satisfy abs(*value* / *precision*) <<
:attr:`n`/3
(i.e. if a float is near the limit then detectable
overflow may still occur)
precision (float): Passed to :meth:`EncodedNumber.encode`.
If *value* is a float then *precision* is the maximum
**absolute** error allowed when encoding *value*. Defaults
to encoding *value* exactly.
r_value (int): obfuscator for the ciphertext; by default (i.e.
if *r_value* is None), a random value is used.
Returns:
EncryptedNumber: An encryption of *value*.
Raises:
ValueError: if *value* is out of range or *precision* is so
high that *value* is rounded to zero.
"""
if isinstance(value, EncodedNumber):
encoding = value
else:
encoding = EncodedNumber.encode(self, value, precision)
return self.encrypt_encoded(encoding, r_value)
def encrypt_encoded(self, encoding, r_value):
"""Paillier encrypt an encoded value.
Args:
encoding: The EncodedNumber instance.
r_value (int): obfuscator for the ciphertext; by default (i.e.
if *r_value* is None), a random value is used.
Returns:
EncryptedNumber: An encryption of *value*.
"""
# If r_value is None, obfuscate in a call to .obfuscate() (below)
obfuscator = r_value or 1
ciphertext = self.raw_encrypt(encoding.encoding, r_value=obfuscator)
encrypted_number = EncryptedNumber(self, ciphertext, encoding.exponent)
if r_value is None:
encrypted_number.obfuscate()
return encrypted_number
def gpu_encrypt_encoded(self, encoding_list, r_value):
"""Paillier encrypt an encoded value.
Args:
encoding: The EncodedNumber instance.
r_value (int): obfuscator for the ciphertext; by default (i.e.
if *r_value* is None), a random value is used.
Returns:
EncryptedNumber: An encryption of *value*.
"""
# If r_value is None, obfuscate in a call to .obfuscate() (below)
obfuscator = r_value or 1
instance_list = [i.encoding for i in encoding_list]
ciphertext_list = self.gpu_raw_encrypt(instance_list, r_value=obfuscator)
encrypted_number_list = [EncryptedNumber(self, ciphertext, encoding.exponent)for ciphertext,encoding in zip(ciphertext_list,encoding_list)]
# if r_value is None:
# encrypted_number.obfuscate()
return encrypted_number_list
class PaillierPrivateKey(object):
"""Contains a private key and associated decryption method.
Args:
public_key (:class:`PaillierPublicKey`): The corresponding public
key.
p (int): private secret - see Paillier's paper.
q (int): private secret - see Paillier's paper.
Attributes:
public_key (PaillierPublicKey): The corresponding public
key.
p (int): private secret - see Paillier's paper.
q (int): private secret - see Paillier's paper.
psquare (int): p^2
qsquare (int): q^2
p_inverse (int): p^-1 mod q
hp (int): h(p) - see Paillier's paper.
hq (int): h(q) - see Paillier's paper.
"""
def __init__(self, public_key, p, q):
if not p*q == public_key.n:
raise ValueError('given public key does not match the given p and q.')
if p == q:
# check that p and q are different, otherwise we can't compute p^-1 mod q
raise ValueError('p and q have to be different')
self.public_key = public_key
if q < p: #ensure that p < q.
self.p = q
self.q = p
else:
self.p = p
self.q = q
self.psquare = self.p * self.p
self.qsquare = self.q * self.q
self.lam = (self.p-1) * (self.q-1)
self.mu = invert(self.l_function(powmod(self.public_key.g,self.lam,self.public_key.nsquare),self.public_key.n),self.public_key.n)
self.p_inverse = invert(self.p, self.q)
self.hp = self.h_function(self.p, self.psquare)
self.hq = self.h_function(self.q, self.qsquare)
@staticmethod
def from_totient(public_key, totient):
"""given the totient, one can factorize the modulus
The totient is defined as totient = (p - 1) * (q - 1),
and the modulus is defined as modulus = p * q
Args:
public_key (PaillierPublicKey): The corresponding public
key
totient (int): the totient of the modulus
Returns:
the :class:`PaillierPrivateKey` that corresponds to the inputs
Raises:
ValueError: if the given totient is not the totient of the modulus
of the given public key
"""
p_plus_q = public_key.n - totient + 1
p_minus_q = isqrt(p_plus_q * p_plus_q - public_key.n * 4)
q = (p_plus_q - p_minus_q) // 2
p = p_plus_q - q
if not p*q == public_key.n:
raise ValueError('given public key and totient do not match.')
return PaillierPrivateKey(public_key, p, q)
def __repr__(self):
pub_repr = repr(self.public_key)
return "<PaillierPrivateKey for {}>".format(pub_repr)
def gpu_decrypt(self, encrypted_number_list):
encoded_list = self.gpu_decrypt_encoded(encrypted_number_list)
return [encoded.decode()for encoded in encoded_list]
def decrypt(self, encrypted_number):
"""Return the decrypted & decoded plaintext of *encrypted_number*.
Uses the default :class:`EncodedNumber`, if using an alternative encoding
scheme, use :meth:`decrypt_encoded` or :meth:`raw_decrypt` instead.
Args:
encrypted_number (EncryptedNumber): an
:class:`EncryptedNumber` with a public key that matches this
private key.
Returns:
the int or float that `EncryptedNumber` was holding. N.B. if
the number returned is an integer, it will not be of type
float.
Raises:
TypeError: If *encrypted_number* is not an
:class:`EncryptedNumber`.
ValueError: If *encrypted_number* was encrypted against a
different key.
"""
encoded = self.decrypt_encoded(encrypted_number)
return encoded.decode()
def gpu_decrypt_encoded(self, encrypted_number_list, Encoding=None):
encoded_list = []
for encrypted_number in encrypted_number_list:
if not isinstance(encrypted_number, EncryptedNumber):
raise TypeError('Expected encrypted_number to be an EncryptedNumber'
' not: %s' % type(encrypted_number))
if self.public_key != encrypted_number.public_key:
raise ValueError('encrypted_number was encrypted against a '
'different key!')
if Encoding is None:
Encoding = EncodedNumber
res_list = [encrypted_number.ciphertext(be_secure=False)for encrypted_number in encrypted_number_list]
encoded_list = self.gpu_raw_decrypt(res_list)
return [Encoding(self.public_key, encoded,
encrypted_number.exponent)for encoded,encrypted_number in zip(encoded_list,encrypted_number_list) ]
def decrypt_encoded(self, encrypted_number, Encoding=None):
"""Return the :class:`EncodedNumber` decrypted from *encrypted_number*.
Args:
encrypted_number (EncryptedNumber): an
:class:`EncryptedNumber` with a public key that matches this
private key.
Encoding (class): A class to use instead of :class:`EncodedNumber`, the
encoding used for the *encrypted_number* - used to support alternative
encodings.
Returns:
:class:`EncodedNumber`: The decrypted plaintext.
Raises:
TypeError: If *encrypted_number* is not an
:class:`EncryptedNumber`.
ValueError: If *encrypted_number* was encrypted against a
different key.
"""
if not isinstance(encrypted_number, EncryptedNumber):
raise TypeError('Expected encrypted_number to be an EncryptedNumber'
' not: %s' % type(encrypted_number))
if self.public_key != encrypted_number.public_key:
raise ValueError('encrypted_number was encrypted against a '
'different key!')
if Encoding is None:
Encoding = EncodedNumber
encoded = self.raw_decrypt(encrypted_number.ciphertext(be_secure=False))
return Encoding(self.public_key, encoded,
encrypted_number.exponent)
def gpu_raw_decrypt(self, ciphertext_list):
for ciphertext in ciphertext_list:
if not isinstance(ciphertext, int):
raise TypeError('Expected ciphertext to be an int, not: %s' %
type(ciphertext))
batch_param = []
batch_param1 = []
batch_param2 = []
batch_param3 = []
p_1_bytes = (self.p-1).to_bytes(512, "little")
psquare_bytes = self.psquare.to_bytes(512, "little")
q_1_bytes = (self.q-1).to_bytes(512, "little")
qsquare_bytes = self.qsquare.to_bytes(512, "little")
hp_bytes = self.hp.to_bytes(512, "little")
hq_bytes = self.hq.to_bytes(512, "little")
p_bytes = self.p.to_bytes(512, "little")
q_bytes = self.q.to_bytes(512, "little")
for ciphertext in ciphertext_list:
t1 = ciphertext
t2 = ciphertext
if ciphertext > self.psquare :
t1 = ciphertext % self.psquare
if ciphertext > self.qsquare :
t2 = ciphertext % self.qsquare
ciphertext_bytes_p = t1.to_bytes(512, "little")
ciphertext_bytes_q = t2.to_bytes(512, "little")
batch_param.append((ciphertext_bytes_p, p_1_bytes, psquare_bytes))
# GPU 调用异常,当ciphertext_bytes< psquare_bytes CGNB模乘不调用 显示异常
batch_param1.append((ciphertext_bytes_q, q_1_bytes, qsquare_bytes))
result1 = gpu_cal.powm_2048(batch_param, len(batch_param))
result2 = gpu_cal.powm_2048(batch_param1, len(batch_param1))
result3 = [self.l_function(int.from_bytes(i, "little"), self.p)for i in result1]
result4 = [self.l_function(int.from_bytes(i, "little"), self.q)for i in result2]
for j,k in zip(result3,result4):
j_bytes = j.to_bytes(512, "little")
k_bytes = k.to_bytes(512, "little")
batch_param2.append((j_bytes, hp_bytes, p_bytes))
batch_param3.append((k_bytes, hq_bytes, q_bytes))
result5 = gpu_cal.mulm_2048(batch_param2, len(batch_param2))
result6 = gpu_cal.mulm_2048(batch_param3, len(batch_param3))
result7 = [int.from_bytes(i, "little")for i in result5]
result8 = [int.from_bytes(i, "little")for i in result6]
return self.gpu_crt(result7,result8)
def raw_decrypt(self, ciphertext):
"""Decrypt raw ciphertext and return raw plaintext.
Args:
ciphertext (int): (usually from :meth:`EncryptedNumber.ciphertext()`)
that is to be Paillier decrypted.
Returns:
int: Paillier decryption of ciphertext. This is a positive
integer < :attr:`public_key.n`.
Raises:
TypeError: if ciphertext is not an int.
"""
if not isinstance(ciphertext, int):
raise TypeError('Expected ciphertext to be an int, not: %s' %
type(ciphertext))
decrypt_to_p = mulmod(
self.l_function(powmod(ciphertext, self.p-1, self.psquare), self.p),
self.hp,
self.p)
t = powmod(ciphertext, self.q-1, self.qsquare)
decrypt_to_q = mulmod(
self.l_function(t, self.q),
self.hq,
self.q)
return self.crt(decrypt_to_p, decrypt_to_q)
def h_function(self, x, xsquare):
"""Computes the h-function as defined in Paillier's paper page 12,
'Decryption using Chinese-remaindering'.
"""
return invert(self.l_function(powmod(self.public_key.g, x - 1, xsquare),x), x)
def l_function(self, x, p):
"""Computes the L function as defined in Paillier's paper. That is: L(x,p) = (x-1)/p"""
return (x - 1) // p
def gpu_crt(self, mp_list, mq_list):
batch_param = []
p_inverse_bytes = self.p_inverse.to_bytes(512, "little")
q_bytes = self.q.to_bytes(512, "little")
for mp,mq in zip(mp_list, mq_list):
mq_mp_bytes = (mq - mp).to_bytes(512, "little")
batch_param.append((mq_mp_bytes, p_inverse_bytes, q_bytes))
result = gpu_cal.mulm_2048(batch_param, len(batch_param))
return [mp + (int.from_bytes(u,"little") * self.p)for mp,u in zip(mp_list,result)]
def crt(self, mp, mq):
"""The Chinese Remainder Theorem as needed for decryption. Returns the solution modulo n=pq.
Args:
mp(int): the solution modulo p.
mq(int): the solution modulo q.
"""
u = mulmod(mq - mp, self.p_inverse, self.q)
return mp + (u * self.p)
def __eq__(self, other):
return self.p == other.p and self.q == other.q
def __hash__(self):
return hash((self.p, self.q))
class PaillierPrivateKeyring(Mapping):
"""Holds several private keys and can decrypt using any of them.
Acts like a dict, supports :func:`del`, and indexing with **[]**,
but adding keys is done using :meth:`add`.
Args:
private_keys (list of PaillierPrivateKey): an optional starting
list of :class:`PaillierPrivateKey` instances.
"""
def __init__(self, private_keys=None):
if private_keys is None:
private_keys = []
public_keys = [k.public_key for k in private_keys]
self.__keyring = dict(zip(public_keys, private_keys))
def __getitem__(self, key):
return self.__keyring[key]
def __len__(self):
return len(self.__keyring)
def __iter__(self):
return iter(self.__keyring)
def __delitem__(self, public_key):
del self.__keyring[public_key]
def add(self, private_key):
"""Add a key to the keyring.
Args:
private_key (PaillierPrivateKey): a key to add to this keyring.
"""
if not isinstance(private_key, PaillierPrivateKey):
raise TypeError("private_key should be of type PaillierPrivateKey, "
"not %s" % type(private_key))
self.__keyring[private_key.public_key] = private_key
def gpu_encrypt(self,encrypted_number_list):
relevant_private_key = self.__keyring[encrypted_number.public_key]
return relevant_private_key.gpu_decrypt(encrypted_number_list)
def decrypt(self, encrypted_number):
"""Return the decrypted & decoded plaintext of *encrypted_number*.
Args:
encrypted_number (EncryptedNumber): encrypted against a known public
key, i.e., one for which the private key is on this keyring.
Returns:
the int or float that *encrypted_number* was holding. N.B. if
the number returned is an integer, it will not be of type
float.
Raises:
KeyError: If the keyring does not hold the private key that
decrypts *encrypted_number*.
"""
relevant_private_key = self.__keyring[encrypted_number.public_key]
return relevant_private_key.decrypt(encrypted_number)
class EncryptedNumber(object):
"""Represents the Paillier encryption of a float or int.
Typically, an `EncryptedNumber` is created by
:meth:`PaillierPublicKey.encrypt`. You would only instantiate an
`EncryptedNumber` manually if you are de-serializing a number
someone else encrypted.
Paillier encryption is only defined for non-negative integers less
than :attr:`PaillierPublicKey.n`. :class:`EncodedNumber` provides
an encoding scheme for floating point and signed integers that is
compatible with the partially homomorphic properties of the Paillier
cryptosystem:
1. D(E(a) * E(b)) = a + b
2. D(E(a)**b) = a * b
where `a` and `b` are ints or floats, `E` represents encoding then
encryption, and `D` represents decryption then decoding.
Args:
public_key (PaillierPublicKey): the :class:`PaillierPublicKey`
against which the number was encrypted.
ciphertext (int): encrypted representation of the encoded number.
exponent (int): used by :class:`EncodedNumber` to keep track of
fixed precision. Usually negative.
Attributes:
public_key (PaillierPublicKey): the :class:`PaillierPublicKey`
against which the number was encrypted.
exponent (int): used by :class:`EncodedNumber` to keep track of
fixed precision. Usually negative.
Raises:
TypeError: if *ciphertext* is not an int, or if *public_key* is
not a :class:`PaillierPublicKey`.
"""
def __init__(self, public_key, ciphertext, exponent=0):
self.public_key = public_key
self.__ciphertext = ciphertext
self.exponent = exponent
self.__is_obfuscated = False
if isinstance(self.ciphertext, EncryptedNumber):
raise TypeError('ciphertext should be an integer')
if not isinstance(self.public_key, PaillierPublicKey):
raise TypeError('public_key should be a PaillierPublicKey')
def __add__(self, other):
"""Add an int, float, `EncryptedNumber` or `EncodedNumber`."""
if isinstance(other, EncryptedNumber):
return self._add_encrypted(other)
elif isinstance(other, EncodedNumber):
return self._add_encoded(other)
else:
return self._add_scalar(other)
def __radd__(self, other):
"""Called when Python evaluates `34 + <EncryptedNumber>`
Required for builtin `sum` to work.
"""
return self.__add__(other)
def __mul__(self, other):
"""Multiply by an int, float, or EncodedNumber."""
if isinstance(other, EncryptedNumber):
raise NotImplementedError('Good luck with that...')
if isinstance(other, EncodedNumber):
encoding = other
else:
encoding = EncodedNumber.encode(self.public_key, other)
product = self._raw_mul(encoding.encoding)
exponent = self.exponent + encoding.exponent
return EncryptedNumber(self.public_key, product, exponent)
def __rmul__(self, other):
return self.__mul__(other)
def __sub__(self, other):
return self + (other * -1)
def __rsub__(self, other):
return other + (self * -1)
def __truediv__(self, scalar):
return self.__mul__(1 / scalar)
def ciphertext(self, be_secure=True):
"""Return the ciphertext of the EncryptedNumber.
Choosing a random number is slow. Therefore, methods like
:meth:`__add__` and :meth:`__mul__` take a shortcut and do not
follow Paillier encryption fully - every encrypted sum or
product should be multiplied by r **
:attr:`~PaillierPublicKey.n` for random r < n (i.e., the result
is obfuscated). Not obfuscating provides a big speed up in,
e.g., an encrypted dot product: each of the product terms need
not be obfuscated, since only the final sum is shared with
others - only this final sum needs to be obfuscated.
Not obfuscating is OK for internal use, where you are happy for
your own computer to know the scalars you've been adding and
multiplying to the original ciphertext. But this is *not* OK if
you're going to be sharing the new ciphertext with anyone else.
So, by default, this method returns an obfuscated ciphertext -
obfuscating it if necessary. If instead you set `be_secure=False`
then the ciphertext will be returned, regardless of whether it
has already been obfuscated. We thought that this approach,
while a little awkward, yields a safe default while preserving
the option for high performance.
Args:
be_secure (bool): If any untrusted parties will see the
returned ciphertext, then this should be True.
Returns:
an int, the ciphertext. If `be_secure=False` then it might be
possible for attackers to deduce numbers involved in
calculating this ciphertext.
"""
if be_secure and not self.__is_obfuscated:
self.obfuscate()
return self.__ciphertext
def decrease_exponent_to(self, new_exp):
"""Return an EncryptedNumber with same value but lower exponent.
If we multiply the encoded value by :attr:`EncodedNumber.BASE` and
decrement :attr:`exponent`, then the decoded value does not change.
Thus we can almost arbitrarily ratchet down the exponent of an
`EncryptedNumber` - we only run into trouble when the encoded
integer overflows. There may not be a warning if this happens.
When adding `EncryptedNumber` instances, their exponents must
match.
This method is also useful for hiding information about the
precision of numbers - e.g. a protocol can fix the exponent of
all transmitted `EncryptedNumber` instances to some lower bound(s).
Args:
new_exp (int): the desired exponent.
Returns:
EncryptedNumber: Instance with the same plaintext and desired
exponent.
Raises:
ValueError: You tried to increase the exponent.
"""
if new_exp > self.exponent:
raise ValueError('New exponent %i should be more negative than '
'old exponent %i' % (new_exp, self.exponent))
multiplied = self * pow(EncodedNumber.BASE, self.exponent - new_exp)
multiplied.exponent = new_exp
return multiplied
def obfuscate(self):
"""Disguise ciphertext by multiplying by r ** n with random r.
This operation must be performed for every `EncryptedNumber`
that is sent to an untrusted party, otherwise eavesdroppers
might deduce relationships between this and an antecedent
`EncryptedNumber`.
For example::
enc = public_key.encrypt(1337)
send_to_nsa(enc) # NSA can't decrypt (we hope!)
product = enc * 3.14
send_to_nsa(product) # NSA can deduce 3.14 by bruteforce attack
product2 = enc * 2.718
product2.obfuscate()
send_to_nsa(product) # NSA can't deduce 2.718 by bruteforce attack
"""
r = self.public_key.get_random_lt_n()
r_pow_n = powmod(r, self.public_key.n, self.public_key.nsquare)
self.__ciphertext = mulmod(self.__ciphertext, r_pow_n, self.public_key.nsquare)
self.__is_obfuscated = True
def _add_scalar(self, scalar):
"""Returns E(a + b), given self=E(a) and b.
Args:
scalar: an int or float b, to be added to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~PaillierPublicKey.n` ** 2.
Raises:
ValueError: if scalar is out of range or precision.
"""
encoded = EncodedNumber.encode(self.public_key, scalar,
max_exponent=self.exponent)
return self._add_encoded(encoded)
def _add_encoded(self, encoded):
"""Returns E(a + b), given self=E(a) and b.
Args:
encoded (EncodedNumber): an :class:`EncodedNumber` to be added
to `self`.
Returns:
EncryptedNumber: E(a + b), calculated by encrypting b and
taking the product of E(a) and E(b) modulo
:attr:`~PaillierPublicKey.n` ** 2.
Raises:
ValueError: if scalar is out of range or precision.
"""
if self.public_key != encoded.public_key:
raise ValueError("Attempted to add numbers encoded against "
"different public keys!")
# In order to add two numbers, their exponents must match.
a, b = self, encoded
if a.exponent > b.exponent:
a = self.decrease_exponent_to(b.exponent)
elif a.exponent < b.exponent:
b = b.decrease_exponent_to(a.exponent)
# Don't bother to salt/obfuscate in a basic operation, do it
# just before leaving the computer.
encrypted_scalar = a.public_key.raw_encrypt(b.encoding, 1)
sum_ciphertext = a._raw_add(a.ciphertext(False), encrypted_scalar)
return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)
def _add_encrypted(self, other):
"""Returns E(a + b) given E(a) and E(b).
Args:
other (EncryptedNumber): an `EncryptedNumber` to add to self.
Returns:
EncryptedNumber: E(a + b), calculated by taking the product
of E(a) and E(b) modulo :attr:`~PaillierPublicKey.n` ** 2.
Raises:
ValueError: if numbers were encrypted against different keys.
"""
if self.public_key != other.public_key:
raise ValueError("Attempted to add numbers encrypted against "
"different public keys!")
# In order to add two numbers, their exponents must match.
a, b = self, other
if a.exponent > b.exponent:
a = self.decrease_exponent_to(b.exponent)
elif a.exponent < b.exponent:
b = b.decrease_exponent_to(a.exponent)
sum_ciphertext = a._raw_add(a.ciphertext(False), b.ciphertext(False))
return EncryptedNumber(a.public_key, sum_ciphertext, a.exponent)
def _raw_add(self, e_a, e_b):
"""Returns the integer E(a + b) given ints E(a) and E(b).
N.B. this returns an int, not an `EncryptedNumber`, and ignores
:attr:`ciphertext`
Args:
e_a (int): E(a), first term
e_b (int): E(b), second term
Returns:
int: E(a + b), calculated by taking the product of E(a) and
E(b) modulo :attr:`~PaillierPublicKey.n` ** 2.
"""
return mulmod(e_a, e_b, self.public_key.nsquare)
def _raw_mul(self, plaintext):
"""Returns the integer E(a * plaintext), where E(a) = ciphertext
Args:
plaintext (int): number by which to multiply the
`EncryptedNumber`. *plaintext* is typically an encoding.
0 <= *plaintext* < :attr:`~PaillierPublicKey.n`
Returns:
int: Encryption of the product of `self` and the scalar
encoded in *plaintext*.
Raises:
TypeError: if *plaintext* is not an int.
ValueError: if *plaintext* is not between 0 and
:attr:`PaillierPublicKey.n`.
"""
if not isinstance(plaintext, int):
raise TypeError('Expected ciphertext to be int, not %s' %
type(plaintext))
if plaintext < 0 or plaintext >= self.public_key.n:
raise ValueError('Scalar out of bounds: %i' % plaintext)
if self.public_key.n - self.public_key.max_int <= plaintext:
# Very large plaintext, play a sneaky trick using inverses
neg_c = invert(self.ciphertext(False), self.public_key.nsquare)
neg_scalar = self.public_key.n - plaintext
return powmod(neg_c, neg_scalar, self.public_key.nsquare)
else:
return powmod(self.ciphertext(False), plaintext, self.public_key.nsquare)