· 7 years ago · Jan 08, 2019, 05:34 PM
1ï¸ e97a4556-d90e-40b4-a70e-676b8b586c1dsï¸
2Zx.<x> = ZZ[]
3n = 7
4d = 3
5q = 29
6p = 2
7
8# FUNKCJE MATEMATYCZNE
9def convolution(f,g):
10 return ((f * g) % (x^n-1))
11
12def balancedmod(f,q):
13 g = list(((f[i] + q//2) % q) - q//2 for i in range(n))
14 return (Zx(g))
15
16def randomdpoly():
17 assert (d <= n)
18 result = n*[0]
19 for j in range(d):
20 while True:
21 r = randrange(n)
22 if (not result[r]):
23 break
24 result[r] = 1-2*randrange(2)
25 return (Zx(result))
26
27def invertmodprime(f,p):
28 T = Zx.change_ring(Integers(p)).quotient(x^n-1)
29 return (Zx(lift(1 / T(f))))
30
31def invertmodpowerof2(f,q):
32 assert q.is_power_of(2)
33 g = invertmodprime(f,2)
34 while True:
35 r = balancedmod(convolution(g,f),q)
36 if (r == 1):
37 return g
38 g = balancedmod(convolution(g,2 - r),q)
39
40# GENEROWANIE KLUCZY
41def keypair():
42 while True:
43 try:
44 f = randomdpoly()
45 f3 = invertmodprime(f,3)
46 fq = invertmodpowerof2(f,q)
47 break
48 except:
49 pass
50 g = randomdpoly()
51 publickey = balancedmod(3 * convolution(fq,g),q)
52 secretkey = f,f3
53 return publickey,secretkey
54
55# GENEROWANIE WIADOMOSCI
56def randommessage():
57 result = list(randrange(3) - 1 for j in range(n))
58 return (Zx(result))
59
60# SZYFROWANIE
61def encrypt(message,publickey):
62 r = 1 + x + x^3 + x^6
63 return balancedmod(convolution(publickey,r) + message,q)
64# ODSZYFROWYWANIE
65def decrypt(ciphertext):
66 f = 1 + x + x^2 + x^4 + x^5
67 f3 = 1 + x^5 + x^6
68 a = balancedmod(convolution(ciphertext,f),q)
69 return balancedmod(convolution(a,f3),2)
70
71m = 1 + x^5
72h = 23 + 23*x + 23*x^2 + 24*x^3 + 23*x^4+24*x^5+23*x^6
73enc = encrypt(m,h)
74decrypted = decrypt(enc)
75print'\nWIADOMOSC ODSZYFROWANA'
76decrypted
77︡c4645556-708b-49d1-91de-3f2d7bef8cf8︡{"stdout":"\nWIADOMOSC ODSZYFROWANA\n"}︡{"stdout":"-x^3 - x^2 - x - 1\n"}︡{"done":true}︡