前言
> 不知不觉,研究生三年的时光即将告一段落,毕业在即。回想起当初学习的场景,那时候笔记本上记满了密密麻麻的笔记,如今想要扔掉却又舍不得。因此,我决定将当初刚入门同态加密时的学习笔记分享出来。由于时间原因,公式比较难打,并不能一下子发布所有的内容,后续的内容将在以后陆续接上。并且,笔记中可能存在一些错误,仅供参考,切勿直接照搬。希望读者能够在阅读的过程中保持思考,同时,大体逻辑是可靠的。如果发现了任何错误,请务必告知我,我将及时进行修改。
先占个坑,后续写完毕。
1、准备知识
1.1最小公倍数
gcd
(
m
,
n
)
=
1
,
m
∣
x
,
n
∣
x
,
⇒
m
n
∣
x
\gcd (m,n) = 1,m|x,n|x, \Rightarrow mn|x
gcd(m,n)=1,m∣x,n∣x,⇒mn∣x
两个数互质,那么最小公倍数就是mn
1.2、Carmichael函数
我们设n=pq,其中p和q是大素数, ϕ ( n ) \phi {\rm{(n)}} ϕ(n)表示欧拉函数
λ ( n ) \lambda {\rm{(n)}} λ(n)表示Carmichael函数,当前情况下
ϕ
(
n
)
=
p
−
1
(
q
−
1
)
,
λ
n
=
l
c
m
(
p
−
1
)
,
(
q
−
1
)
\phi {\rm{(n)}}{\rm{ = }}{\rm{p - }}1(q - 1),\lambda {\rm{n}}{\rm{ = lcm}}(p - 1),(q - 1)
ϕ(n)=p−1(q−1),λn=lcm(p−1),(q−1)
其中:
∣
Z
n
2
∗
∣
=
ϕ
(
n
)
2
=
n
ϕ
(
n
)
\left| {Z_{{{\rm{n}}^2}}^*} \right| = \phi {{\rm{(n)}}^{\rm{2}}} = n\phi {\rm{(n)}}
Zn2∗
=ϕ(n)2=nϕ(n)
1.3、欧拉函数
(1)欧拉函数定义:
欧拉函数是指:对于一个正整数n ,小于n且和n互质的正整数(包括1的个数,记作
ϕ
(
n
)
\phi {\rm{(n)}}
ϕ(n)
欧拉函数公式
ϕ
(
x
)
=
x
∏
i
=
1
i
=
n
(
1
−
1
p
i
)
\phi {\rm{(x)}} = x\prod\nolimits_{i = 1}^{i = n} {(1 - \frac{1}{{{p_i}}})}
ϕ(x)=x∏i=1i=n(1−pi1)
其中,p1, p2,p3,pi为x的质因数
什么是质因数,质因数(素因数或质因子)在数论里是指能整除给定正整数的质数
(3)性质
①
i
f
gcd
(
a
,
b
)
=
1
t
h
e
n
ϕ
(
a
b
)
=
ϕ
(
a
)
ϕ
(
b
)
if\gcd (a,{\rm{b}}) = 1{\kern 1pt} {\kern 1pt} {\kern 1pt} {\kern 1pt} then\phi {\rm{(a}}b) = \phi( a)\phi (b)
ifgcd(a,b)=1thenϕ(ab)=ϕ(a)ϕ(b)
②
2、Paillier同态加密
2.1、密钥匙生成阶段:
(1)选择两个随机的大素数p和q,计算n=pq以及 λ = l c m ( p − 1 , q − 1 ) \lambda {\rm{ = lcm}}(p - 1,q - 1) λ=lcm(p−1,q−1)其中Icm为最小公倍数。
(2)选择随机数 g ∈ Z n 2 ∗ {\rm{g}} \in Z_{{n^2}}^* g∈Zn2∗满足 λ = L ( g λ m o d n 2 ) − 1 m o d n \lambda {\rm{ = }}L{({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})^{ - 1}}{\rm{mod n}} λ=L(gλmodn2)−1modn(这个-1就是逆元)存在(面会发现g =n+1满足条件,因此可以直接取g =n+1) ,其中L(x)的函数定义为:
L x = x − 1 n μ = L ( g λ m o d n 2 ) − 1 m o d n L{\rm{x}} = {{x - 1} \over n}\mu {\rm{ = }}L{({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})^{ - 1}}\bmod n Lx=nx−1μ=L(gλmodn2)−1modn$(-1代表逆元)
(3)设置公钥为(n, g)私钥( λ \lambda λ, μ \mu μ)
2.2、加密阶段的步骤如下
(1)选择明文
m
∈
Z
n
{\rm{m}} \in {Z_{\rm{n}}}
m∈Zn
(2)选择随机数0<r<n,且
g
∈
Z
n
2
∗
{\rm{g}} \in Z_{{n^2}}^*
g∈Zn2∗,
(3)计算相应密文为:
c
=
g
m
r
n
m
o
d
n
2
{\rm{c}} = {g^m}{r^n}\bmod {n^2}
c=gmrnmodn2
2.3、解密阶段:
(1)计算下边公式获得明文
m
=
L
(
c
λ
m
o
d
n
2
)
×
μ
m
o
d
n
=
L
(
c
λ
m
o
d
n
2
)
L
(
g
λ
m
o
d
n
2
)
m
o
d
n
{\rm{m}} = L({c^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}}) \times \mu \bmod n{\rm{ = }}{{L({c^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})} \over {L({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})}}{\rm{mod n}}
m=L(cλmodn2)×μmodn=L(gλmodn2)L(cλmodn2)modn
(2)备注:
m
=
a
∗
c
(
m
o
d
m
)
m = a*c\left( {mod{\rm{ }}m} \right)
m=a∗c(modm) m= ac(mod m);即a / b的模等于a(b) 的逆元的模,那么
L
(
c
λ
m
o
d
n
2
)
L
(
g
λ
m
o
d
n
2
)
{{L({c^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})} \over {L({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})}}
L(gλmodn2)L(cλmodn2) 应该是整数
2.4、正确性分析
首先:
(
p
−
1
)
∣
λ
{(\rm{p}} - 1)|\lambda
(p−1)∣λ,
(
q
−
1
)
∣
λ
(q - 1)|\lambda
(q−1)∣λ
因此:
λ
=
k
1
(
p
−
1
)
=
k
2
(
q
−
1
)
\lambda = {k_1}(p - 1) = {k_2}(q - 1)
λ=k1(p−1)=k2(q−1)
由费马小定理得:
g
λ
=
g
k
1
(
p
−
1
)
≡
1
m
o
d
p
,
p
∣
(
g
λ
−
1
)
{g^\lambda } = {g^{{k_1}(p - 1)}} \equiv 1\bmod p,p|({g^\lambda } - 1)
gλ=gk1(p−1)≡1modp,p∣(gλ−1)
同理:
g
λ
=
g
k
1
(
p
−
1
)
≡
1
m
o
d
p
,
q
∣
(
g
λ
−
1
)
{g^\lambda } = {g^{k1(p - 1)}} \equiv 1\bmod p,q|({g^\lambda } - 1)
gλ=gk1(p−1)≡1modp,q∣(gλ−1)
所以:
p
q
∣
(
g
λ
−
1
)
,
g
λ
≡
1
m
o
d
n
pq|({g^\lambda } - 1),{g^\lambda } \equiv 1\bmod n
pq∣(gλ−1),gλ≡1modn
即:
g
λ
m
o
d
n
2
=
n
×
k
g
+
1
m
o
d
n
2
=
n
×
k
g
+
1
,
k
<
n
(为啥
n
<
k
)
{g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}}{\rm{ = }}{\rm{n}} \times {k_{\rm{g}}} + 1\bmod {\rm{ }}{{\rm{n}}^{\rm{2}}} = {\rm{n}} \times {k_{\rm{g}}} + 1,k < n (为啥n<k)
gλmodn2=n×kg+1modn2=n×kg+1,k<n(为啥n<k)
L
(
g
λ
m
o
d
n
2
)
=
k
g
L({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}}) = {k_g}
L(gλmodn2)=kg
并且有:
1
+
k
n
≡
1
+
k
n
m
o
d
n
2
1{\rm{ + kn}} \equiv 1 + kn\bmod {n^2}
1+kn≡1+knmodn2
(
1
+
k
n
)
2
≡
1
+
2
k
n
+
(
k
n
)
2
≡
1
+
2
k
n
m
o
d
n
2
{(1{\rm{ + kn)}}^{\rm{2}}} \equiv 1 + 2kn + {(kn)^2} \equiv 1 + 2kn\bmod {n^2}
(1+kn)2≡1+2kn+(kn)2≡1+2knmodn2
(
1
+
k
n
)
3
≡
1
+
3
k
n
+
3
(
k
n
)
2
+
(
k
n
)
3
≡
1
+
3
k
n
m
o
d
n
2
{(1{\rm{ + kn)}}^3} \equiv 1 + 3kn + 3{(kn)^2} + {(kn)^3} \equiv 1 + 3kn\bmod {n^2}
(1+kn)3≡1+3kn+3(kn)2+(kn)3≡1+3knmodn2
可以观察得:
(
1
+
k
n
)
m
≡
1
+
k
m
n
m
o
d
n
2
{(1{\rm{ + kn)}}^{\rm{m}}} \equiv 1 + kmn\bmod {n^2}
(1+kn)m≡1+kmnmodn2
所以:
g
m
λ
=
(
1
+
k
g
n
)
m
≡
1
+
k
g
m
n
m
o
d
n
2
{g^{\rm{m}}}^\lambda {\rm{ = }}{(1{\rm{ + }}{{\rm{k}}_{\rm{g}}}{\rm{n)}}^{\rm{m}}} \equiv 1 + {k_g}mn\bmod {n^2}
gmλ=(1+kgn)m≡1+kgmnmodn2
且
r n λ = ( r λ n m o d n 2 = ( 1 + k n n ) n m o d n 2 ≡ 1 + k n n 2 m o d n 2 {r^n}^\lambda = ({r^\lambda }{^{\rm{n}}}{\rm{mod n}}{{\rm{ }}^{\rm{2}}}{\rm{ = }}{(1{\rm{ + }}{{\rm{k}}_n}{\rm{n)}}^{\rm{n}}}\bmod {n^2} \equiv 1 + {k_n}{n^2}\bmod {n^2} rnλ=(rλnmodn2=(1+knn)nmodn2≡1+knn2modn2
有:
L g m λ r n λ m o d n 2 = m k g L{g^{\rm{m}}}^\lambda {r^n}^\lambda mod{n^2} = {\rm{m}}{k_g} Lgmλrnλmodn2=mkg
所以:
L ( c λ m o d n 2 ) L ( g λ m o d n 2 ) = m k g k g = m m o d n {{L({{\rm{c}}^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})} \over {L({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})}} = {{m{\rm{k}}g} \over {kg}} = m\bmod n L(gλmodn2)L(cλmodn2)=kgmkg=mmodn
2.5\paillier算法加法同态性
通过paillier加密算法加密的两个密文:
c
1
≡
g
m
1
r
1
n
m
o
d
n
2
{\rm{c}}1 \equiv {g^{{{\rm{m}}_1}}}{r_1}^n\bmod {n^2}
c1≡gm1r1nmodn2
c 2 ≡ g m 2 r 2 n m o d n 2 {\rm{c2}} \equiv {g^{{{\rm{m}}_{\rm{2}}}}}{r_2}^n\bmod {n^2} c2≡gm2r2nmodn2
两个密文相乘可得到消息相加的结果
c 1 × c 2 ≡ g m 1 g m 2 r 1 n r 2 n ≡ g m 1 + m 2 ( r 1 r 2 ) n m o d n 2 {\rm{c}}1 \times {\rm{c}}2 \equiv {g^{{{\rm{m}}_{_1}}}}{g^{{{\rm{m}}_2}}}{r_1}^n{r_2}^n \equiv {g^{{{\rm{m}}_1}{\rm{ + }}{{\rm{m}}_{\rm{2}}}}}{({r_1}{r_2})^{\rm{n}}}\bmod {n^2} c1×c2≡gm1gm2r1nr2n≡gm1+m2(r1r2)nmodn2
3、Paillier同态加密算法加速及其一些变体
我们知道同态加密算法是一个极其耗时的过程,因此有很多研究提出了同态Paillier算法的一些加速变体。
3.1 预计算加速
我们观察Paillier同态加密算法在计算密文的时候 c = g m r n m o d n 2 {\rm{c}} = {g^m}{r^n}\bmod {n^2} c=gmrnmodn2,可以注意到 r n {r^n} rn是一个盲因子,而r是一个随机数 r n m o d n 2 {r^n}\bmod {n^2} rnmodn2和 g m m o d n 2 {g^m}mod {n^2} gmmodn2一般是分开计算的,而 g m {g^m} gm是与密文有关的,这个是无法提前知道的,但是 r n m o d n 2 {r^n}\bmod {n^2} rnmodn2是可以提前计算的,也就是说,可以提前计算很多 r n m o d n 2 {r^n}\bmod {n^2} rnmodn2的值,保存在本地当中,然后等用到的时候直接去取的,这样就极大的缩短了其计算时间。这个方案原理简单,很多论文都水过,因此就不详细讨论。
3.2、使用中国剩余定理加速其加密过程
中国剩余定理是数论中的一个基本定理,它指出如果给定一组正整数模数,且这些模数两两互质(即它们的最大公约数为1),同时给定一组与这些模数两两互质的余数,那么存在唯一的一个整数,它对于每个给定的模数,都与对应的余数同余。这个定理在数学理论中具有广泛的应用,特别是在密码学、编码理论和计算机科学中。
简单来说,使用中国剩余定理可以将Paillier同态加密算法模指数运算,从一维展开到二维,模变小了,计算时间自然就小了。
中国剩余定理,不仅可以加速Paiiler同态算法的加密过程,还可以加速Paillier同态加密算法的解密过程。两者都有论文发表。
此外,基于中国剩余定理加速的Paillier同态加密算法,还有一种Pailliier同态加密算法的变体。
3.2.1、CRT的一个用途:用一组比较小的质数表示一个大的整数原理:
例如,若a满足如下线性方程组
{
a
≡
a
1
m
o
d
p
1
a
≡
a
2
m
o
d
p
2
\left\{ \begin{array}{l} a \equiv {{\rm{a}}_1}\bmod p1\\ a \equiv {a_2}\bmod p2 \end{array} \right.
{a≡a1modp1a≡a2modp2
我们可以用以下形式的式子(称作a的混合基数表示)表示;
a
=
x
1
+
x
2
p
1
a = {x_1} + {x_2}{p_1}
a=x1+x2p1
Garner算法将用来计算系数x1,x2
把a带入第一方程:
x
1
=
a
1
m
o
d
p
1
{x_1} = {{\rm{a}}_1}\bmod {p_1}
x1=a1modp1
把a带入第一方程:
p
1
p
1
−
1
≡
1
m
o
d
p
2
a
2
≡
(
x
1
+
x
2
p
1
)
m
o
d
p
2
(
a
2
−
x
1
)
≡
x
2
p
1
m
o
d
p
2
(
a
2
−
x
1
)
p
1
−
1
≡
x
2
m
o
d
p
2
x
2
≡
(
a
2
−
a
1
m
o
d
p
1
)
p
1
−
1
m
o
d
p
2
\begin{array}{l} {p_1}p_1^{ - 1} \equiv 1\bmod {p_2}\\ {a_2} \equiv ({x_1} + {x_2}{p_1})\bmod {p_2}\\ ({a_2} - {x_1}) \equiv {x_2}{p_1}\bmod {p_2}\\ ({a_2} - x1)p_1^{ - 1} \equiv {x_2}\bmod {p_2}\\ {x_2} \equiv ({a_2} - {{\rm{a}}_1}\bmod {p_1})p_1^{ - 1}{\rm{mod }}{{\rm{p}}_{\rm{2}}} \end{array}
p1p1−1≡1modp2a2≡(x1+x2p1)modp2(a2−x1)≡x2p1modp2(a2−x1)p1−1≡x2modp2x2≡(a2−a1modp1)p1−1modp2
可以求出:
a
=
a
1
m
o
d
p
1
+
p
1
(
a
2
−
a
1
m
o
d
p
1
)
p
1
−
1
m
o
d
p
2
a = {{\rm{a}}_1}\bmod {p_1} + {p_1}({a_2} - {{\rm{a}}_1}\bmod {p_1})p_1^{ - 1}{\rm{mod }}{{\rm{p}}_{\rm{2}}}
a=a1modp1+p1(a2−a1modp1)p1−1modp2
3.2.2、欧拉定理降幂
若
g
c
d
(
a
,
m
)
=
1
,
a
ϕ
(
n
)
≡
1
m
o
d
m
gcd(a,m) = 1,{a^{\phi (n)}} \equiv 1{\rm{mod m}}
gcd(a,m)=1,aϕ(n)≡1modm
a
b
m
o
d
ϕ
(
m
)
≡
a
b
m
o
d
m
{a^{{\rm{bmod }}\phi (m{\rm{) }}}} \equiv {a^b}\bmod m
abmodϕ(m)≡abmodm
3.2.3改进算法原理
x = a b m o d n , ( n = p q ) { x p = a b m o d p m o d p x q = a b m o d q m o d q { a b ≡ x p m o d p a b ≡ x q m o d q \begin{array}{l} x{\rm{ = }}{{\rm{a}}^b}\bmod n,(n = pq)\\ \left\{ \begin{array}{l} {x_p} = {{\rm{a}}^{b\bmod p}}\bmod p\\ {x_q} = {{\rm{a}}^{b\bmod q}}\bmod q \end{array} \right.\\ \left\{ \begin{array}{l} {{\rm{a}}^b} \equiv {x_p}\bmod p\\ {{\rm{a}}^b} \equiv {x_q}\bmod q \end{array} \right. \end{array} x=abmodn,(n=pq){xp=abmodpmodpxq=abmodqmodq{ab≡xpmodpab≡xqmodq
CRT通项公式:
x = ( x p ( q − 1 m o d p ) q + x q ( p − 1 m o d q ) p ) m o d p q x = ({x_p}({q^{ - 1}}\bmod p)q + {x_q}({p^{ - 1}}\bmod q)p)\bmod pq x=(xp(q−1modp)q+xq(p−1modq)p)modpq
根据配书(peishu,忘记咋打了,反正是这么念的)定理,由于pq互素数。
(
q
−
1
m
o
d
p
)
q
+
(
p
−
1
m
o
d
q
)
p
=
1
({q^{ - 1}}\bmod p)q + ({p^{ - 1}}\bmod q)p{\rm{ = }}1
(q−1modp)q+(p−1modq)p=1
带入上边式
x
=
(
x
p
(
1
−
(
p
−
1
m
o
d
q
)
p
)
)
+
x
q
(
p
−
1
m
o
d
q
)
p
)
=
x
p
+
(
x
q
−
x
p
)
(
p
−
1
m
o
d
q
)
p
\begin{array}{l} x = ({x_p}(1 - ({p^{ - 1}}\bmod q)p)) + {x_q}({p^{ - 1}}\bmod q)p)\\ = {x_p} + ({x_q} - {x_p})({p^{ - 1}}\bmod q)p \end{array}
x=(xp(1−(p−1modq)p))+xq(p−1modq)p)=xp+(xq−xp)(p−1modq)p
按照道理来讲应该还可以这样带入上边方程得到
a = a 1 m o d p 1 + p 1 ( a 2 − a 1 m o d p 1 ) p 1 − 1 m o d p 2 x = x p + ( x q − x p ) ( p − 1 m o d q ) p \begin{array}{l} a = {{\rm{a}}_1}\bmod {p_1} + {p_1}({a_2} - {{\rm{a}}_1}\bmod {p_1})p_1^{ - 1}{\rm{mod }}{{\rm{p}}_{\rm{2}}}\\ {\rm{x}} = {x_p} + ({x_q} - {x_p})({p^{ - 1}}\bmod q)p \end{array} a=a1modp1+p1(a2−a1modp1)p1−1modp2x=xp+(xq−xp)(p−1modq)p
3.2.4、正式加速解密过程:
python的paillier同态算法官方库就是用的这个方案
λ
=
l
c
m
(
p
−
1
,
q
−
1
)
\lambda {\rm{ = lcm}}(p - 1,q - 1)
λ=lcm(p−1,q−1)
m
=
L
(
c
λ
m
o
d
n
2
)
×
μ
m
o
d
n
=
L
(
c
l
c
m
(
p
−
1
)
(
q
−
1
)
m
o
d
n
2
)
L
(
g
l
c
m
(
q
−
1
)
(
q
−
1
)
m
o
d
n
2
)
−
1
m
o
d
p
q
{\rm{m}} = L({c^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}}) \times \mu \bmod n = L({c^{lcm(p - 1)(q - 1)}}{\rm{mod }}{{\rm{n}}^{\rm{2}}})L{({g^{lcm(q - 1)(q - 1)}}{\rm{mod }}{{\rm{n}}^{\rm{2}}})^{ - 1}}{\rm{mod pq}}
m=L(cλmodn2)×μmodn=L(clcm(p−1)(q−1)modn2)L(glcm(q−1)(q−1)modn2)−1modpq
L
(
X
)
=
(
x
−
1
)
N
L
p
(
x
)
=
(
x
−
1
)
p
L
q
(
x
)
=
(
x
−
1
)
q
μ
=
L
(
g
λ
m
o
d
n
2
)
−
1
m
o
d
n
L(X) = \frac{{(x - 1)}}{N}{L_p}(x) = \frac{{(x - 1)}}{p}{L_{\rm{q}}}(x) = \frac{{(x - 1)}}{q}\mu {\rm{ = }}L{({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})^{ - 1}}{\rm{mod n}}
L(X)=N(x−1)Lp(x)=p(x−1)Lq(x)=q(x−1)μ=L(gλmodn2)−1modn
L
(
g
λ
m
o
d
n
2
)
m
o
d
p
=
g
l
c
m
(
p
−
1
)
(
q
−
1
)
m
o
d
n
2
−
1
p
q
m
o
d
p
=
g
p
−
1
m
o
d
p
2
−
1
p
m
o
d
p
L({g^\lambda }{\rm{mod }}{{\rm{n}}^{\rm{2}}})\bmod p = \frac{{{g^{lcm(p - 1)(q - 1)}}{\rm{mod }}{{\rm{n}}^{\rm{2}}} - 1}}{{pq}}\bmod p = \frac{{{g^{p - 1}}{\rm{mod }}{{\rm{p}}^{\rm{2}}} - 1}}{p}\bmod p
L(gλmodn2)modp=pqglcm(p−1)(q−1)modn2−1modp=pgp−1modp2−1modp
h
p
≡
L
P
(
g
(
p
−
1
)
m
o
d
p
2
)
−
1
m
o
d
p
hp \equiv {L_P}({g^{(p - 1)}}{\rm{mod }}{{\rm{p}}^{\rm{2}}}){^{ - 1}}modp
hp≡LP(g(p−1)modp2)−1modp
h
q
≡
L
P
(
g
(
q
−
1
)
m
o
d
q
2
)
−
1
m
o
d
q
hq \equiv {L_P}({g^{(q - 1)}}{\rm{mod }}{{\rm{q}}^{\rm{2}}}){^{ - 1}}modq
hq≡LP(g(q−1)modq2)−1modq
m
p
≡
L
P
(
C
(
p
−
1
)
m
o
d
p
2
h
p
m
o
d
p
{m_p} \equiv {L_P}({C^{(p - 1)}}{\rm{mod }}{{\rm{p}}^{\rm{2}}}{h_p}modp
mp≡LP(C(p−1)modp2hpmodp
m
p
≡
L
P
(
C
(
q
−
1
)
m
o
d
p
2
)
h
q
m
o
d
q
{m_p} \equiv {L_P}({C^{(q - 1)}}{\rm{mod }}{{\rm{p}}^{\rm{2}}}){h_q}modq
mp≡LP(C(q−1)modp2)hqmodq
m
=
C
R
T
(
m
p
,
m
q
)
m
o
d
p
q
{\rm{m = CRT(}}{{\rm{m}}_{\rm{p}}}{\rm{,}}{{\rm{m}}_{\rm{q}}}{\rm{)modpq}}
m=CRT(mp,mq)modpq
3.2.5使用中国剩余定理加速Paillier加密过程
中国剩余定理不仅可以加速Paillier同态加密算法的解密过程,还可以加速Pallier同态加密算法的加密过程。加速解密过程的论文在哪篇文章中提出的我忘记了,但是加速其加密过程是在下边这篇文章中提出的。
传送门:https://ieeexplore.ieee.org/abstract/document/8323650/
Accelerate the Paillier Cryptosystem in CryptDB by Chinese Remainder Theorem
这篇文章的创新点,主要是使用中国剩余定理(CRT)来加速 cryptDB 数据库使用Pailiier加密数据的加密过程,减少其性能开销。结果表明,因此可以在一定条件下提高了 cryptDB 的性能。创新点很清晰。原理也很简单。
看下边的具体的公式,由于在上一部分已经证明过了,因此,此小节不再赘述。
再看其实验结果
由于是会议论文,因此这篇论文就这一个实验结果,原理也比较简单。其中不难看出,分别有最小,最大以及平均时间。
与原始CryptDB相比,CRT版本分别带来了28.14%、34.38%和61.55%的提升。从平均来看,这个提升相对较小,不过有胜于无,而且做实验的时候,大部分实验结果都是平均的。61应该是属于数据有一些特殊的情况。
这个核心代码也很好写,以下是pyhton代码,可以在paillier官方库的代码,实现起来也很简单。
#n =pq,p**2,q**2
def chinese_remainder_theorem(r, n, p, q):
# 计算 p1 和 q1
p1 = p ** 2
q1 = q ** 2
# 计算 q 的模逆
qinv = gmpy2.invert(q1, p1)
# 使用 CRT 计算
c1 = gmpy2.powmod(r, n, p1)
c2 = gmpy2.powmod(r, n, q1)
h = qinv * (c1 - c2) % p1
ctemp = c2 + h * q1
return int(ctemp % (p1 * q1))
3.3、Paillier同态加密算法的变体
这个也用到了中国剩余定理,但是其算法也与之前的不同,实际上,这个方案已经改变了其Paillier算法的加密结果,但是可以得到相同的解密结果,其安全性作者并未详细证明,其实这个安全性还真不太好证明,但是从其公式来看,其安全性也是基于n次剩余类的问题,具体的等有时间详细分析。
Privacy-Preserving Swarm Learning Based on Lightweight Homomorphic Encryption and Blockchain Technology
传送门:https://ieeexplore.ieee.org/abstract/document/10383173
论文中提到了三个代码,分别是经典的,CRT方案密过程,以及作者自己的,作者并给自己的算法起名字。为了方便称呼,在这里就姑且称其为LT-Paillier方案吧,源于其中论文题目,轻量级。
经典的同态加密算法
中国剩余定理加速方案
作者提出方案
其证明过程
由于这篇笔记篇幅太长,具体推导过程等我有时间,以后再分析,其实这个看起来说了这么多,但是原理也很简单,就是对其进行指数运算降幂,然后可以得到不同的加密结果,但是满足公式(8),满足公式8就可以得到相同的解密结果,因此,此算法也满足同态性质。指数运算减少了,其加密时间自然减少了。
再看其实验结果,这个是最好的情况,整整提升了450%左右,不过这个可能他定义的模型比较特殊,实验过程中,确实发现不同模型不一样,有的模型效果非常好,具体的原因未知。中间那个是前边提到的用中国剩余定理加速其加密过程的方案
这个是一般的情况,可以看出,一般情况也能够提升3倍左右,自己复现的时候,发现,大多数也是这个结果,他那个是加密时间,不是解密时间,论文中标错了。
上边这个是其具体的数值,可以看出,还是比较好的。
这个代码也是比较容易实现的,并且
在我复现其代码的时候,发现有极个别情况(某些特殊的模型),其加密时间,居然短于解密时间,这是相当不可思议的,具体原因暂时未知,可能是由于某些模型或者数值比较特殊。
这个代码应该还是有优化空间的,之前在传统paillier同态加密算法的优化方案并应该还可以应用于这个算法上,理论上应该是可以水论文的。并且代码容易实现,这是其核心代码。我觉得单纯的预计算,再加一个应用,水一篇本科毕业论文是没有问题的。但是硕士论文估计够呛。顶多可以发学报。
def paillier_powmod_crt_improvement(r, p, q):
"""
在Paillier密码体制中使用中国剩余定理来计算 a^b mod n,其中 a、b 和 n 都是整数。
参数:
a (int): 底数。
b (int): 指数。
n (int): 模数 (n = p*q)。
返回:
int: (a ** b) % n 的结果。
注:
这个函数使用中国剩余定理来优化模幂运算。
"""
# 计算 p1 和 q1
p1 = p ** 2
q1 = q ** 2
# 计算 q 的模逆
qinv = gmpy2.invert(q1, p1)
# 使用 CRT 计算
c1 = gmpy2.powmod(r, p, p1)
c2 = gmpy2.powmod(r, q, q1)
h = qinv * (c1 - c2) % p1
ctemp = c2 + h * q1
return int(ctemp % (p1 * q1))
最近比较忙,接下来还有很多pailler算法的改进的加密方案,暂时没有时间写,先写这几个简单的,然后等有时间再写。而且之前的好多地方也并未详细分析
3、paillier算法python源码分析
这是官方库的源码,等有时间再分析
!/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
try:
from collections.abc import Mapping
except ImportError:
Mapping = dict
from encoding import EncodedNumber
from util import invert, powmod, getprimeover, isqrt
DEFAULT_KEYSIZE = 2048
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 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)
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 (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 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
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.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 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 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 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 = self.l_function(powmod(ciphertext, self.p-1, self.psquare), self.p) * self.hp % self.p
decrypt_to_q = self.l_function(powmod(ciphertext, self.q-1, self.qsquare), 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 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 = (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 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 = 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 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)
if __name__ == '__main__':
import numpy as np
pubkey, privkey = generate_paillier_keypair(n_length=128)
x1 = 90000.23
y1 = 90
z1 = 3
x = pubkey.encrypt(x1)
y = pubkey.encrypt(y1)
t = x + y*0.5
print (privkey.decrypt(t))
t=np.array([1.0, 2.0], dtype=np.float)
print(type(t[0]))
x = pubkey.encrypt(t[0])
t=np.array([1, 0])
print(type(t[0]))
x = pubkey.encrypt(int(t[0]))