Advertisement
DigitalMag

The simplest RSA implementation

Jul 13th, 2020
1,252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.57 KB | None | 0 0
  1. import random
  2.  
  3. isprime = lambda number: all(number % i for i in range(2, number))
  4.  
  5. class RSA:
  6.  
  7.     e = 3
  8.  
  9.     def __init__(self, *args, **kwargs):
  10.         if args: self.p, self.q = args
  11.         else:
  12.             kwargs = kwargs or {'start': 100, 'end':1000}
  13.             simples = [i for i in range(kwargs['start'], kwargs['end']) if isprime(i)]
  14.             self.p = random.choice(simples)
  15.             while True:
  16.                 self.q = random.choice(simples)
  17.                 if self.q != self.p: break;
  18.             print (self.p, self.q)
  19.         self.n = self.q * self.p
  20.         self.euler_value = (self.p-1)*(self.q-1)
  21.  
  22.     def create_secret_key(self, start=1000000, end=10000000):
  23.  
  24.         for i in range(start, end):
  25.             if (i * self.e) % self.euler_value == 1:
  26.                 self.secret_exp = i
  27.                 return self.secret_exp, self.n
  28.  
  29.  
  30.     generate_open_key = lambda self: (self.e, self.n,)
  31.  
  32.     encrypt_value = lambda self, value: (value ** self.e) % self.n
  33.     decrypt_value = lambda self, value: (value ** self.secret_exp) % self.n
  34.  
  35.  
  36. def main():
  37.     rsa = RSA(3557, 2579)
  38.  
  39.     print(rsa)
  40.     s_key = rsa.create_secret_key()
  41.  
  42.     print(s_key)
  43.     o_key = rsa.generate_open_key()
  44.  
  45.     print(o_key)
  46.  
  47.     val = int(input("Enter value for decryption: ")) or 111111
  48.  
  49.  
  50.     enc_value = (rsa.encrypt_value(val))
  51.     print (enc_value)
  52.  
  53.     input("Enter any key for decryption ")
  54.  
  55.     print(rsa.decrypt_value(enc_value))
  56.  
  57.     # print( isprime(6111579))
  58.  
  59. if __name__ == '__main__':
  60.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement