Diffie-Hellman key generation in Python

In this code, I used math class only. here I implement Deffie-Hellman algorithm for produce public and private keys for Alice and Bob.
This program was written by Shooresh Sufiye. you can copy and change it, But don't forget to mention the source.


# Written by Shooresh Sufiye
import random
from math import *

class DH:
    sharedSec=None

    def __init__(self):
        self.cal()
   
    def gimmi(self, v):
        p = int(random.random() *1000000)
        p1 = p+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))]
        p=random.choice(primesList)
        primesList.remove(p)
        P = p
        return P

    def isPrime(self, a):
            isp = None
            b=int(sqrt(a))
            # should change to stave alg 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 gen(self, p):
        #   set of g for all integer values. The order
        # of g is the smallest k≥1k≥1 such that g^k = 1 mod pgk=1 mod p.
        primitives=[1,2,3,4,5,6,7,9,10,11,13,14,17,18,19,22,23,25,26,
                    27,29,31,34,37,38,41,43,46,47,49,50,53,54,58,59,
                    61,62,67,71,73,74,79,81,82,83,86,89,94,97,98,101,
                    103,106,107,109,113,118,121,122,125,127,131,134,
                    137,139]
        j=0
        for i in range(p):
            if(self.isPrime(i)):
                j+=1
        pr = primitives[j]
        #print(len(primitives))
        return pr

    def cal(self): 
        print("This program only works for P<=300 !\n", 30*"=","\n")
        print("Enter chosen number P ",end='')
        p=input()
        P = int(p)
        G = self.gen(int(P))
        print("\nG: ", G)
        A = int(random.random()*100)
        AliceK1 = (G ** A) % P
        B = int(random.random()*100)
        BobK1 = (G ** B) % P
        print("Alice key:", A,"\n Bob\'s key: ", B)
        self.sharedSec = (G ** (A*B)) % P
        print("shared secret key: ", self.sharedSec)


dhkey =  DH()
dhkey.sharedSec
input("\nPress enter exit?")


Comments

Popular posts from this blog

One-Time Pad Encryption - In Python

RSA encryption in JAVA with custom key length