Python Program to generate Random Password with out using Libraries Using Prime Numbers

A simple python program to create a random password without using any libraries using prime number is as follows

alpha_lower = 'abcdefghijklmonpqrstuvwxyz'
digits = '0123456789'
spcialchars = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

allcharrs = alpha_lower + alpha_upper + digits + spcialchars

primen = 3

def seed(n):
    global primen
    primen = n 
    primen = getNextPrime()

def isPrime(n):
    x = 2
    for i in range(2, n):
        if (n % i == 0): 
            return False 
    return True 

def getNextPrime():
    global primen
    primen += 1
    while not isPrime(primen):
        primen +=1 
    return primen

def getRandom(): 
    p = getNextPrime()
    ir = p ** (1/2)
    r = str(ir).split('.')[1]
    return r 

def genPassword(length=8):
    ran = getRandom()
    #print("randoom number: {}".format(ran))
    ran = list(map(int, ran))
    passwd = ''
    for i in range(length): 
        char_index = ran[i]
        char = allcharrs[char_index]
        #print("Char index {} and char: {}".format(char_index, char))
        passwd += char

    return passwd       

Random numbers created by above program is not truly random, it was an effort to create random password with out using any library

Same program to create random password using random and string library is as follows

import string
import random 

def genPassword(length=8): 
    assert 8 <= length <= 15, "Minimum Lenght must be 8 and max is 15"
    password_chars = string.ascii_letters + string.digits + string.punctuation

    rand_password = random.sample(password_chars, length)
    rand_password = ''.join(rand_password)
    return rand_password

Default image
Naveen T aka neotam. Programming language agnostic, Software architect, Python expert, Networking & DevOps engineer & consultant with decade of experience in creating serious web applications, real time event-driven non blocking applications and database driven applications ranging from small scale to enterprise grade. website
Leave a Reply