RSA Public and Private key generation in Python

In this code, the only third-party library is "secrets" which is available to download and add automatically to python libraries by executing pip command.
for more information see post pip command.

-This program was written by Shooresh Sufiye. Feel free to copy and change it, But don't forget to mention the source.


# Written by Shooresh Sufiye
# RSA Algorithm Shooresh
from math import *
import random
import secrets

#===============-RSA key Class-==================
class RSAkey:
    publicKey = []
    PrivateKey = []
    sp = 0
    sq = 0
    dig = 0
    def __init__(self,sp,sq,length):
        self.sp = int(sp)
        self.sq = int(sq)
        self.dig = int(length)
        self.cal()

    def getKeys(self):
        keyl = []
        keyl.append(self.publicKey)
        keyl.append(self.PrivateKey)
        return keyl
#+++++++++++++++++++-bigPrime Class-+++++++++++++++++++++++ 
    class bigPrime:
        P=None

        def  __init__(self):         
            self.P=None

        def isPrime(self, a):
            isp = None
            b=int(sqrt(a))
            # should change to stave algorithm or better   !!!
            while(b>1):         
                if(a%b==0):
                    isp = False
                    b=-1
                    break
                else:
                    b-=1
            if(b!=-1):
                    isp = True
                    print(".", end='')
            return isp
     
        def gimmi(self, dig, s): # Generat and get method for big prime numbers
            pSeed = s
            #p = random.SystemRandom (pSeed) # -for secure random number
            p = int(random.random() * (10 ** dig))
            p1 = p+(100 if (int(random.random() * 10)>5) else -100 )
            if(p>p1): p,p1=p1,p
            primesList=[]
            primesList = [i for i in range(p,p1) if ((len(primesList)<=5) and self.isPrime(i))]
            print()
            p=random.choice(primesList)
            primesList.remove(p)
            self.P = p
            return self.P
     
        def egcd(self, a, b):  # Extended Euclidean greatest common divisor
            if a == 0:
                return (b, 0, 1)
            else:
                g, y, x = self.egcd(b % a, a)
                return (g, x - (b // a) * y, y)

        def modinv(self, a, m):    # mod inverse function
            g, x, y = self.egcd(a, m)
            if g != 1:
                print('modular inverse does not exist')
            else:
                return x % m
         
#++++++++++++++++-end of bigPrime Class-++++++++++++++++++++++
         
    def cal(self):  # calculates RSA elements
        b = self.bigPrime()
        p = b.gimmi(self.dig, self.sp)
        q = b.gimmi(self.dig, self.sq)
        #print("P ",p,"Q ",q)
        N = p*q
        W = (p-1)*(q-1)
        e = int(sqrt(W))
        while(e<W):
            if (gcd(W,e) == 1):
                E = e
                break
            e+=1
        d = (W / E)
        d = E * int(random.random()*100)
        D = b.modinv(E,W)
        print("N ",N,"W ",W,"E ",E,"D ", D,"\nP ",p ,"Q ", q)
        print("="*50)
        print("public key:  ( ",N,",",E," )")
        print("Private key: ( ",N,",",D," )")
        print("="*50)
        self.publicKey = [N, E]
        self.PrivateKey = [N, D]
#==============-end of RSA key Class-============
#================================================
#  main part:
p=7   # input("Enter P seed? ")
q=11  # input("Enter Q seed? ")
length = input("How long digits key you want? ")
c = RSAkey(p,q,length)
print(c.getKeys())
input()

Comments

Popular posts from this blog

One-Time Pad Encryption - In Python

RSA encryption in JAVA with custom key length