Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import copy
  2. from random import randint
  3. import math
  4.  
  5.  
  6.  
  7. def generowanie_listy(N,d1,d2):
  8. tab = []
  9. for i in range(N):
  10. tab.append(0)
  11. i = 0
  12. while i < (d1+d2):
  13. a = randint(0,N-1)
  14. if tab[a] == 1 or tab[a] == -1:
  15. continue
  16. else:
  17. if i >= d1:
  18. tab[a] = -1
  19. i += 1
  20. else:
  21. tab[a] = 1
  22. i += 1
  23. return tab
  24. def centralLift(q,poly):
  25. a = list(poly)
  26. for i in range(len(a)):
  27. if a[i] >= (q/2):
  28. a[i] = a[i] - q
  29. elif a[i] <= (-q/2):
  30. a[i] = a[i] + q
  31.  
  32. return QRZ(a)
  33.  
  34. def generowanie_f_fp_fq(N,d1,d2):
  35. corrFlag = 0
  36. while (corrFlag == 0):
  37. corrFlag = 1
  38. f = QRZ(generowanie_listy(N,d1,d2))
  39. try:
  40. fp = QRP(list(f))^(-1)
  41. except ZeroDivisionError:
  42. corrFlag = 0
  43.  
  44. try:
  45. fq = QRQ(list(f))^(-1)
  46. except ZeroDivisionError:
  47. corrFlag = 0
  48. return (f,fp,fq)
  49.  
  50. class NTRU:
  51. def __init__(self,N,p,q,d1,d2,d3):
  52. self.N = N
  53. self.p = p
  54. self.q = q
  55. self.d1 = d1
  56. self.d2 = d2
  57. self.d3 = d3
  58. self.f,self.fp,self.fq = generowanie_f_fp_fq(self.N,self.d1+1,self.d1)
  59. self.g = QRZ(generowanie_listy(self.N,self.d2,self.d2))
  60. self.h = self.p * self.fq*QRQ(list(self.g))
  61.  
  62. def szyfrowanie(self,m):
  63. m = QRQ(list(m))
  64. r = generowanie_listy(self.N,self.d3,self.d3)
  65. r = QRQ(r)
  66. e = r * self.h + m
  67. return e
  68.  
  69. def deszyfrowanie(self,e):
  70. a = QRQ(list(self.f))*QRQ(list(e))
  71. a = QRZ(list(a))
  72. a = centralLift(self.q,a)
  73. d = self.fp * QRP(list(a))
  74. d = QRZ(list(d))
  75. d = centralLift(self.p,d)
  76. return d
  77.  
  78.  
  79.  
  80.  
  81. N = 503
  82. p = 3
  83. q = 256
  84. df = 215
  85. dg = 72
  86. dr = 18
  87.  
  88. Fp=GF(p)
  89. Fq=GF(q)
  90.  
  91. FP.<u>=PolynomialRing(Fp)
  92. FQ.<v>=PolynomialRing(Fq)
  93. FZ.<l>=PolynomialRing(ZZ)
  94.  
  95. QRZ.<z>=FZ.quotient(l^(N)-1)
  96. QRP.<x>=FP.quotient(u^(N)-1)
  97. QRQ.<y>=FQ.quotient(v^(N)-1)
  98. wiadomosc = QRZ(genList(N,33,33))
  99.  
  100. print(wiadomosc)
  101. NTRU=NTRU(N,p,q,df,dg,dr)
  102.  
  103. e = NTRU.szyfrowanie(wiadomosc)
  104. print(e)
  105.  
  106. d = NTRU.deszyfrowanie(e)
  107. print(d)
  108. if d == wiadomosc:
  109. print("DZIALA")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement