Create secure passwords with Python's pyscript and secrets libraries

Alphanumeric strings are created with at least 1 lower char, 1 upper char, 1 digit and 1 special character

Copied!
import secrets import string from string import digits, ascii_letters import js from js import document password = '' def generate_pwd(length=8): chars = digits + ascii_letters return ''.join(secrets.choice(chars) for c in range(length)) def generate_secure_pwd(length, upper, digits, lower, special): if length < upper + digits + 1: raise ValueError('Nice try!') while True: pwd = generate_pwd(length) if (any(c.islower() for c in pwd) and sum(c.isupper() for c in pwd) >= upper and sum(c.isdigit() for c in pwd) >= digits): i=0 while i in range(special): pwd += secrets.choice(string.punctuation) i+=1 return pwd def create_pwd_by_type(): ptype = Element('pwdtype').element.value if (ptype == 'Alphanumeric'): show_pwd() elif (ptype == 'Digits'): show_digit() def show_pwd(): pyscript.write("python-container", "") global password xlen = Element('test-input').element.value if xlen.isdigit(): xlen = int(Element('test-input').element.value) else: Element('test-input').element.value = "6" xlen = int(Element('test-input').element.value) if (xlen < 10): xlen = 10 Element('test-input').element.value = "10" xspecial = int(xlen)//5 my_secure_rng = secrets.SystemRandom() rndspecial = my_secure_rng.randrange(1, xspecial) string_characters = "character" if (rndspecial ==1) else "characters" pyscript.write("python-container","password size is : " + str(xlen) + " with " + str(rndspecial) + " special " + string_characters) password = generate_secure_pwd(int(xlen) - int(rndspecial), 1, 2, 2, int(rndspecial)) char_list = list(password) secrets.SystemRandom().shuffle(char_list) password = ''.join(char_list) pyscript.write("pwdtext", str(password)) document.getElementById('clip').style.visibility = "visible"; def show_digit(): #js.alert("show_digit()"); pyscript.write("python-container", "") xlen = Element('test-input').element.value if xlen.isdigit(): xlen = int(Element('test-input').element.value) else: Element('test-input').element.value = "6" xlen = int(Element('test-input').element.value) if (xlen < 1): xlen = 1 Element('test-input').element.value = "6" OTP = '' digit = string.digits for i in range(xlen): OTP +=str(''.join(secrets.choice(digit))) pyscript.write("pwdtext", str(OTP)) xsize =len(str(Element('pwdtext').element.value)) #js.alert(str(xsize)); pyscript.write("python-container","number size is : " + str(xsize)) document.getElementById('clip').style.visibility = "visible"; def send2clipboard(): # Copy the text inside the text field js.navigator.clipboard.writeText(password);