hozer

RSA

Oct 19th, 2014
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.07 KB | None | 0 0
  1. #получаем тэ в степени минус один методом перебора
  2. def gene(d, n):
  3.     i = 0
  4.     for i in range(1, n+1):
  5.         if ((i*d)%n == 1):
  6.             return i
  7.     return 0
  8.  
  9. #шифровка
  10. def encrypt(text, e, n):
  11.     ctext = []
  12.     for a in text:
  13.                 #проверяем символ ли это
  14.         if (ord(a) >= 97 and ord(a) <= 122):
  15.             c = int(((ord(a)-96)**e)%n)#шифруем по формуле
  16.             ctext.append(c)#вставляем шифротекст
  17.         elif (a == ' '):#если пробел - то ноль
  18.             ctext.append(0)
  19.        
  20.     return ctext
  21. #деша
  22. def decrypt(ctext, d, n):
  23.     text = ''
  24.     for c in ctext:#проходим по шифротексту
  25.         if (c != 0):#если не ноль, то дешифрим по формуле (неожиданно, да?) )
  26.             a = (c**d)%n
  27.             text += chr(a+96)
  28.         else:#0 - пробел
  29.             text += ' '
  30.     return text
  31.    
  32. choose = int(raw_input("1 - encrypt; 2 - decrypt: "))
  33. if choose == 1:
  34.         #вводим данные для гена ключа
  35.     p = int(input('input p: '))
  36.     q = int(input('input q: '))
  37.     n = p*q
  38.     fin = (p-1)*(q-1)
  39.     d = int(input('input d: '))
  40.     e = gene(d, fin) #фигачим глючик шифровочки
  41.     #открываем файлик
  42.     with open("input.txt", "r") as f:
  43.         text = f.read().lower()
  44.         ct = encrypt(text, e, n) #шифруем текстики
  45.         text = ""
  46.         #пишем это в файлик
  47.         for el in ct:
  48.             text += str(el) + ' '
  49.         fo = open("output.txt", "w")
  50.         fo.write(text)
  51.         fo.close()
  52.     print('n = ' + str(n))
  53.    
  54. elif (choose == 2):
  55.         #открываем файлик и считываем шифротекстик
  56.     with open("input.txt", "r") as f:
  57.         d = int(input('input d: '))
  58.         n = int(input('input n: '))
  59.         ctext = f.read()
  60.         ctext = ctext.split()
  61.         ct = []
  62.         for c in ctext:
  63.             ct.append(int(c))
  64.         tx = decrypt(ct, d, n) #дешифровочка чисел
  65.         print(tx)
Advertisement
Add Comment
Please, Sign In to add comment