SHARE
TWEET

Untitled

a guest Jun 25th, 2019 63 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import math
  2. import random
  3.  
  4. from math import *
  5.  
  6. def rozklad(x):
  7.     if x<=0:
  8.         return 0
  9.     i=2
  10.     e=floor(sqrt(x))
  11.     r=[] #używana jest tablica (lista), nie bepośrednie wypisywanie
  12.     while i<=e:
  13.         if x%i==0:
  14.             r.append(i)
  15.             x/=i
  16.             e=floor(sqrt(x))
  17.         else:
  18.             i+=1
  19.     if x>1: r.append(x)
  20.     r = list(dict.fromkeys(r))
  21.     return r
  22.  
  23.  
  24. print(rozklad(73))
  25.  
  26.  
  27.  
  28. def fme(a, k, n):
  29.  
  30.     b = bin(k)[2:] # list of bits
  31.     m = len(b)
  32.     r = 1 # result
  33.     x = a % n
  34.  
  35.     for i in range(m - 1, -1, -1):
  36.         if b[i] == '1':
  37.             r = r * x % n
  38.  
  39.         x **= 2
  40.         x  %= n
  41.  
  42.     return r
  43.  
  44.  
  45. def calc_r(n, fermat_results):
  46.     for r in range(1, n-1):
  47.             good = True
  48.             for j in fermat_results:
  49.                if(fme(r,int((n-1)/j),n) == 1):
  50.                    good = False
  51.                    break
  52.             if(good):
  53.                 return r
  54.  
  55. def generate_key(n):
  56.     if rozklad(n)==[n]:
  57.         fermat_results=rozklad(n-1)
  58.         print("ferm results: "+ str(fermat_results))
  59.         r = calc_r(n,fermat_results)
  60.         print(r)
  61.         #k = random.randint(1, n-1)
  62.         k = 6739
  63.         a = fme(r,k,n)
  64.         print("a: ", a," r: ",r," k: ",k)
  65.         return [n,r,a,k]
  66.  
  67.     else:
  68.         print("n musi być liczbą pierwszą")
  69.  
  70. def encode(t,n,r,a):
  71.     print("a",str(a))
  72.     #j = random.randint(1, n-1)
  73.     j=34310
  74.     print("j: ",j)
  75.     c1 = fme(r,j,n)
  76.     c2 = ((t%n)* (fme(a,j,n)))%n
  77.     return c1,c2
  78.  
  79. def decode(c1,c2,n,k):
  80.     print(c1,n)
  81.     print(fme(c1,n-1-k,n))
  82.     return  ((c2%n)*(fme(c1,n-1-k,n)))%n
  83.  
  84.  
  85.  
  86.  
  87.  
  88. n = 37813
  89. key = generate_key(n)
  90. print("key")
  91. print(key)
  92. message = int(300)
  93. secret1, secret2 = encode(message,key[0],key[1],key[2])
  94.  
  95. print("encoded message : "+ str(secret1),str(secret2))
  96. decoded = decode(secret1,secret2,key[0],key[3])
  97. print("decoded message : " + str(decoded))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top