本文主要是介绍NTRU的Python简单实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
使用python实现了NTRU加密方案的基本操作,为读者理解NTRU提供一个例子。
"""
This is done by zyf
"""
#public parametersN=503
p=3
q=256
df=216
dg=72
dr=55import numpy as np
import math
from sympy import GF,invert,Poly,symbols,isprime
x=symbols("x")def L_P(num,f=False):if f:f1=[1]*num+[-1]*(num-1)+[0]*(N-2*num+1)else:f1=[1]*num+[-1]*(num)+[0]*(N-2*num)np.random.shuffle(f1)return f1#poly should be [1,2,3]=1+2x+3x**2class NTRU:def __init__(self,p=3,q=256,N=503):self.N=Nself.q=qself.p=pdef add(self,p1,p2):return np.add(p1,p2)%self.qdef mult(self,p1,p2,modulus=256):p3=(np.polynomial.polynomial.polymul(p1,p2).astype(int))%modulusp4=p3[:self.N]for i in range(self.N,len(p3)):p4[i%self.N]=(p4[i%self.N]+p3[i])%modulusreturn p4def inv(self,x1,modulus):#just invert 2^d and primeR=[1]+[0]*(self.N-1)+[-1]R=Poly(R,x,domain="ZZ")x1=Poly(x1[::-1],x,domain="ZZ")if isprime(modulus):try:tx=invert(x1,R,domain=GF(modulus)).all_coeffs()except:return Noneelse:e = int(math.log(modulus, 2))if pow(2,e)!=modulus:return Nonetry:inv_poly = invert(x1, R, domain=GF(2))except:return Nonefor _ in range(1, e):inv_poly = ((2 * inv_poly - x1 * inv_poly ** 2) % R).trunc(modulus)tx=inv_poly.all_coeffs()return tx[::-1]def keygen(self):fx=L_P(df,True)while True:Fpx=self.inv(fx,self.p)Fqx=self.inv(fx,self.q)if Fpx is not None and Fqx is not None:breakif Fpx is None:print("None for Fpx")elif Fqx is None:print("None for Fqx")else:print("error")breakfx=L_P(df)gx=L_P(dg)hx=self.mult(Fqx,gx,self.q)return hx,[fx,Fpx]def encrypt(self,mx,hx):rx=L_P(dr)ex=np.add(self.mult(np.multiply(self.p,rx),hx,self.q),mx)%self.qreturn exdef decrypt(self,ex,fx,Fpx):ax=np.array(self.mult(fx,ex,self.q))ax[ax>self.q/2]-=self.qbx=self.mult(Fpx,ax,self.p)return bx#x12=L_P(df)ntru=NTRU()pk,sk=ntru.keygen()
m1=L_P(12)
m2=L_P(41)
ct=ntru.encrypt(m1,pk)
ct2=ntru.encrypt(m2,pk)#test homomorphic addition
ct3=ntru.add(ct,ct2)
m4=ntru.decrypt(ct3,sk[0],sk[1])print(((np.add(m1,m2)%p)==m4).all())
这篇关于NTRU的Python简单实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!