hozer

[IS] RSA cryptosystem

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