Advertisement
DigitalMag

The simplest RSA implementation with the smaller q/p values

Jul 13th, 2020
2,984
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.91 KB | None | 0 0
  1. import random
  2.  
  3. isprime = lambda number: all(number % i for i in range(2, number))
  4.  
  5.  
  6. class RSA:
  7.  
  8.     e = 3
  9.  
  10.     def __init__(self, *args, **kwargs):
  11.         self.initialize(*args, **kwargs)
  12.  
  13.     def initialize(self, *args, **kwargs):
  14.         if args: self.p, self.q = args
  15.         else:
  16.             kwargs = kwargs or {'start': 100, 'end':400}
  17.             simples = [i for i in range(kwargs['start'], kwargs['end']) if isprime(i)]
  18.             self.p = random.choice(simples)
  19.             while True:
  20.                 self.q = random.choice(simples)
  21.                 if self.q != self.p: break;
  22.  
  23.             print (self.p, self.q)
  24.         self.n = self.q * self.p
  25.         self.euler_value = (self.p-1)*(self.q-1)
  26.  
  27.         if not self.create_secret_key():
  28.             if args:
  29.                 arg = int(input('Worth p/q pair for secret_exp calculate. Input other q value: '))
  30.                 self.initialize(args[0], arg)
  31.             else:
  32.                 self.initialize()
  33.  
  34.     def create_secret_key(self, start=100, end=100000):
  35.  
  36.         for i in range(start, end):
  37.             if (i * self.e) % self.euler_value == 1:
  38.                 self.secret_exp = i
  39.                 return self.secret_exp, self.n
  40.         return None
  41.  
  42.  
  43.     generate_open_key = lambda self: (self.e, self.n,)
  44.  
  45.     encrypt_value = lambda self, value: (value ** self.e) % self.n
  46.     decrypt_value = lambda self, value: (value ** self.secret_exp) % self.n
  47.  
  48.     sign_value = decrypt_value
  49.     check_sign = lambda self, signed_value, value:  (signed_value ** self.e) % self.n == value
  50.  
  51.  
  52. def main():
  53.     rsa = RSA()
  54.  
  55.     print(rsa)
  56.     # s_key = rsa.create_secret_key()
  57.     s_key = rsa.secret_exp
  58.  
  59.     print(s_key)
  60.     o_key = rsa.generate_open_key()
  61.  
  62.     print(o_key)
  63.  
  64.     val = int(input("Enter value for decryption: ")) or 111111
  65.  
  66.  
  67.     enc_value = (rsa.encrypt_value(val))
  68.     print (enc_value)
  69.     input("Enter any key for decryption ")
  70.     print(rsa.decrypt_value(enc_value))
  71.  
  72.     # print( isprime(6111579))
  73.  
  74.     sign = rsa.sign_value(val)
  75.     print(rsa.check_sign(sign, val))
  76.  
  77. if __name__ == '__main__':
  78.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement