Advertisement
1yes123

BAD CODE

Apr 16th, 2023
1,039
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.56 KB | None | 0 0
  1. import random
  2. import json as j
  3. from cryptography.fernet import Fernet
  4. import re
  5. import os
  6. import shutil
  7. import csv
  8. import sys
  9. import string
  10. import mysql.connector as mys
  11. obj = mys.connect(host = 'localhost',user='root',password = 'root',database = 'password_manager')
  12. cursor = obj.cursor()
  13.  
  14. def currentfile_location_writer(a = os.path.join(f'{os.getcwd()}', "passwords.txt")):
  15.     if not os.path.exists(a):
  16.         with open(a, "w"):
  17.             pass
  18.     with open('text_file.txt', 'w') as f:
  19.         f.write(a)
  20.     return a
  21.  
  22. def currentfile_location():
  23.     if os.path.exists(os.path.join(f'{os.getcwd()}','text_file.txt')):
  24.             with open('text_file.txt') as f:
  25.                 a = f.read()
  26.                 if os.path.exists(a):
  27.                     return a
  28.                 else:
  29.                     currentfile_location_writer()
  30.     else:
  31.         currentfile_location_writer()
  32.  
  33. def csv_filelocation_writer(a=os.path.join(f'{os.getcwd()}', "passwords.csv")):
  34.     if not os.path.exists(a):
  35.         with open(a, "w"):
  36.             pass
  37.     with open("text_file.csv", "w") as f:
  38.         f.write(a)
  39.     return a
  40.  
  41. def csv_filelocation():
  42.     if os.path.exists(os.path.join(f'{os.getcwd()}','text_file.csv')):
  43.         with open('text_file.csv') as f:
  44.             a = f.read()
  45.             if os.path.exists(a):
  46.                 return a
  47.             else:
  48.                 csv_filelocation_writer()
  49.     else:
  50.         csv_filelocation_writer()
  51.  
  52.  
  53. def key_generator():
  54.     key = Fernet.generate_key()
  55.     with open('filekey.key', 'wb') as filekey:
  56.         filekey.write(key)
  57.     return key
  58.  
  59.  
  60. def encrypt():
  61.     currentfileloc = currentfile_location()
  62.     csvfileloc = csv_filelocation()
  63.     with open(currentfileloc,"rb") as filekey:
  64.         original = filekey.read()
  65.     fernet1 = Fernet(key_generator())
  66.     encrypted = fernet1.encrypt(original)
  67.     with open(currentfileloc,"wb") as f:
  68.         f.write(encrypted)
  69.     with open(csvfileloc,"rb") as filekey:
  70.         original1 = filekey.read()
  71.     encrypted = fernet1.encrypt(original)
  72.     with open(csvfileloc, 'wb') as f:
  73.         f.write(encrypted)
  74.     dest_path = f'{currentfileloc}'+'.enc'
  75.     dest_path1 = f'{csvfileloc}'+'.enc'
  76.     enc_file_name(currentfileloc, dest_path)
  77.     enc_file_name(csvfileloc, dest_path1)
  78.     currentfile_location_writer(dest_path)
  79.     csv_filelocation_writer(dest_path1)
  80.  
  81. def enc_file_name(a,b):
  82.     os.rename(a,b)
  83.  
  84.  
  85.  
  86.  
  87. def decrypt():
  88.     currentfileloc = currentfile_location()
  89.     csvfileloc = csv_filelocation()
  90.     dest_path = f'{currentfileloc}'.replace('.enc','')
  91.     dest_path1 = f'{csvfileloc}'.replace('.enc','')
  92.     print(dest_path,dest_path1)
  93.     enc_file_name(currentfileloc,dest_path)
  94.     enc_file_name(csvfileloc,dest_path1)
  95.     currentfile_location_writer(dest_path)
  96.     csv_filelocation_writer(dest_path1)
  97.  
  98.     with open('filekey.key','rb') as f:
  99.         fernet1 = Fernet(f.read())
  100.     with open(dest_path, 'rb') as enc_file:
  101.         encrypted = enc_file.read()
  102.     decrypted = fernet1.decrypt(encrypted)
  103.     with open(dest_path, "w") as f:
  104.         f.write(decrypted.decode())
  105.  
  106.     # opening the file in write mode and
  107.     # writing the decrypted data
  108.     with open(dest_path1,"rb") as enc_file:
  109.         encrypted = enc_file.read()
  110.     decrypted = fernet1.decrypt(encrypted)
  111.     with open(dest_path1, "w") as f:
  112.         f.write(decrypted.decode())
  113.  
  114.  
  115.  
  116.  
  117.  
  118.  
  119.  
  120.  
  121. def check_access():
  122.     csv_filelocation()
  123.     currentfile_location()
  124.     if not master_key_exists():
  125.         create_master_key()
  126.         return True
  127.  
  128.     else:
  129.         master_key = get_master_key()
  130.         attempts = 3
  131.         while attempts > 0:
  132.             attempts -= 1
  133.             user_input = input('Enter master key: ')
  134.             if user_input != master_key:
  135.                 print('Wrong key, please try again.')
  136.             else:
  137.                 return True
  138.    
  139.  
  140.  
  141.     return False
  142.  
  143.  
  144. def get_master_key():
  145.     with open("masterfile.txt") as f:
  146.         a = f.read()
  147.         return a
  148.  
  149.  
  150.  
  151. def create_master_key():
  152.     with open("masterfile.txt", 'w') as f:
  153.         mk = input("Set Master Key:")
  154.         mk1 = input("Confirm Master Key:")
  155.         while mk1!= mk:input("Confirm Master Key:")
  156.         f.write(mk)
  157.         print("master key successfully created")
  158.  
  159.  
  160.  
  161. def master_key_exists():
  162.     if os.path.exists((os.path.join(f"{os.getcwd()}", "masterfile.txt"))) :
  163.         with open((os.path.join(f"{os.getcwd()}", "masterfile.txt"))) as f:
  164.             if len(f.read())!=0:
  165.                 return True
  166.     else:
  167.         return False
  168.  
  169.  
  170. def final_password():
  171.     set = string.ascii_letters + string.digits + string.punctuation
  172.     try:
  173.         length = int(input("enter  desired length of password:"))
  174.     except TypeError:
  175.         print("TypeError: enter a number")
  176.     password = ''.join([random.SystemRandom().choice(set) for _ in range(length)])
  177.     return password
  178.  
  179.  
  180. def exist_check(a, b):
  181.     currentfileloc = currentfile_location()
  182.     with open (currentfileloc) as f:
  183.         new = f.read().split('\n')
  184.         print(new)
  185.         if len(new)>1:
  186.             a1 = [j.loads(i) for i in new if i !='']
  187.             print(a1)
  188.             for i in a1:
  189.                 if a in i.keys() and b in i[a]:
  190.                     return True
  191.         else:
  192.             return False
  193.  
  194.  
  195.  
  196.  
  197.  
  198. def view_func():
  199.     c = currentfile_location()
  200.     with open(c) as f:
  201.         return f.read()
  202.  
  203.  
  204.  
  205. def edit(a,b):
  206.     currentfileloc,csvv = currentfile_location(),csv_filelocation()
  207.     try:
  208.         with open(currentfileloc) as f:
  209.             a1 = j.loads(f.read())
  210.  
  211.     except:
  212.         print("no saves found!")
  213.         return None
  214.  
  215.     if a not in a1.keys(): return "does not exist"
  216.     elif b not in [i[0] for i in a1.values()]:return "does not exist"
  217.     for i in a1.keys():
  218.         if a1[i][0] == b:
  219.             option = input("1.regenarate password,\n2.manually change password,\n3.delete save\n:")
  220.             if option not in ("1","2","3"):return False
  221.             elif option == "1":
  222.                 password = final_password()
  223.                 a1[i][1] == password
  224.                 cursor.execute("update pwm set password =(%s) where Domain = (%s) and Gmail = (%s)",(a,b,a1[i][1]))
  225.                 print(a1[i])
  226.                 return "successful"
  227.             elif option == "2": a1[i][1] = input("enter password:")
  228.             elif option == "3": del a1[i][1]
  229.             write_func(b)
  230.             csv_operations(b)
  231.  
  232.  
  233.  
  234. def write_func(l):
  235.     currentfileloc = currentfile_location()
  236.     with open(currentfileloc, "a") as a:
  237.         a.write(j.dumps(l)+'\n')
  238.  
  239.  
  240.  
  241.  
  242. def copyanother_csvfile_remove_exsisting_file():
  243.     currentfile = csv_filelocation()
  244.     newfile = input("enter file path")
  245.     while not os.path.exists(newfile) and ".csv" not in newfile:newfile = input("enter file path, should be csv:")
  246.     shutil.copyfile(currentfile,newfile)
  247.     os.remove(currentfile)
  248.     csv_filelocation_writer(newfile)
  249.  
  250.  
  251. def copytoanother_file_remove_exisitingfile():
  252.     currentfileloc = currentfile_location()
  253.     newfile = input("enter file path:")
  254.     while not os.path.exists(newfile) or not ".txt" not in newfile:newfile = input("enter file path:")
  255.     shutil.copyfile(currentfileloc, newfile)
  256.     os.remove(currentfileloc)
  257.     currentfile_location_writer(currentfileloc)
  258. def csv_operations(l):
  259.     csvfileloc = csv_filelocation()
  260.     with open(csvfileloc, 'a+', newline="") as csvfile:
  261.         f = csv.writer(csvfile, delimiter=' ')
  262.         f.writerow(j.dumps(l))
  263.  
  264.  
  265.  
  266. def phone_number(s):
  267.     regex = re.compile(r"^(?:\+44|0)7\d{9}$")
  268.     return regex.match(s)
  269.  
  270.    
  271.  
  272.  
  273. def check(email):
  274.     regex = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$'
  275.  
  276.     if (re.search(regex, email)):
  277.         print("Valid Email")
  278.         return (email)
  279.     else:
  280.         print("Invalid Email")
  281.         check(input("enter email:"))
  282.  
  283.  
  284. def del_func():
  285.     currentfileloc = currentfile_location()
  286.     csvfileloc = csv_filelocation()
  287.     if os.path.exists(currentfileloc):
  288.         os.remove(currentfileloc)
  289.         print("sucessful")
  290.         exit()
  291.     else:
  292.         print("file does not exist")
  293.         exit()
  294.  
  295.  
  296.  
  297.  
  298. def password_generator():
  299.     domainname = str(input("enter domain name :"))
  300.     username = str(input("enter username :"))
  301.  
  302.  
  303. def instagram():
  304.     email = input("enter email: ")
  305.     b = check(email)
  306.     a = exist_check("instagram",b)
  307.     if not a:
  308.         password = final_password()
  309.         L = {'instagram': [f'{email}', f"{password}"]}
  310.         cursor.execute('insert into pwm values(("instagram"),(%s),(%s));', (email, password))
  311.         write_func(L)
  312.         csv_operations(L)
  313.     else:print("account aldready exists")
  314.  
  315.  
  316.  
  317. # write_func(password)
  318. def facebook():
  319.     email = input("enter email: ")
  320.     b = check(email)
  321.     a = exist_check("facebook", b)
  322.     if not a:
  323.         password = final_password()
  324.         L = {'facebook': [f'{email}', f"{password}"]}
  325.         cursor.execute('insert into pwm values(("facebook"),(%s),(%s));', (email, password))
  326.         write_func(L)
  327.         csv_operations(L)
  328.  
  329.     else:
  330.         print("account aldready exists")
  331.  
  332.  
  333. def twitter():
  334.     email = input("enter email: ")
  335.     b = check(email)
  336.     a = exist_check("twitter", b)
  337.     if not a:
  338.         password = final_password()
  339.         L = {'twitter': [f'{email}', f"{password}"]}
  340.         cursor.execute('insert into pwm values(("twiiter"),(%s),(%s));', (email, password))
  341.         write_func(L)
  342.         csv_operations(L)
  343.     else:
  344.         print("account aldready exists")
  345.  
  346.  
  347.  
  348.  
  349. def netflix():
  350.     email = input("enter email: ")
  351.     b = check(email)
  352.     a = exist_check("netflix", b)
  353.     if not a:
  354.         password = final_password()
  355.         L = {'netflix': [f'{email}', f"{password}"]}
  356.         cursor.execute('insert into pwm values(("netflix"),(%s),(%s));', (email, password))
  357.         write_func(L)
  358.         csv_operations(L)
  359.     else:
  360.         print("account aldready exists")
  361.  
  362.  
  363.  
  364.  
  365. def amazon():
  366.     email = input("enter emaiil: ")
  367.     b = check(email)
  368.     a = exist_check("amazon", b)
  369.     if not a:
  370.         password = final_password()
  371.         L = {'amazon': [f'{email}', f"{password}"]}
  372.         cursor.execute('insert into pwm values(("amazon"),(%s),(%s));', (email, password))
  373.         write_func(L)
  374.         csv_operations(L)
  375.     else:
  376.         print("account aldready exists")
  377.  
  378.  
  379.  
  380.  
  381. def gmail():
  382.     email = input("enter email: ")
  383.     b = check(email)
  384.     a = exist_check("gmail", b)
  385.     if not a:
  386.         password = final_password()
  387.         b = passcheck(password)
  388.         while b == False:
  389.             password = final_password()
  390.             b = passcheck(password)
  391.         m = password
  392.         L = {'gmail': [f'{email}', f"{password}"]}
  393.         cursor.execute('insert into pwm values(("gmail"),(%s),(%s));', (email, password))
  394.         write_func(L)
  395.         csv_operations(L)
  396.     else:
  397.         print("account aldready exists")
  398.  
  399.  
  400.  
  401.  
  402. def reddit():
  403.     email = input("enter email: ")
  404.     check(email)
  405.     a = final_password()
  406.     b = passcheck(a)
  407.     if not a:
  408.         while b == False:
  409.             a = final_password()
  410.             b = passcheck(a)
  411.         reddit_pass = a
  412.         L = {'gmail': [f'{email}', f"{reddit_pass}"]}
  413.         cursor.execute('insert into pwm values(("reddit"),(%s),(%s));', (email, reddit_pass))
  414.         write_func(L)
  415.         csv_operations(L)
  416.     else:
  417.         print("account aldready exists")
  418.  
  419.  
  420. def passcheck(a):
  421.     y = []
  422.     for x in a:
  423.         y.append(x)
  424.     i = 0
  425.     newvar = True
  426.     while i < len(y):
  427.         if [y[i]] != [y[i + 1]] and y[i]+y[i+1]!="\n":
  428.             i = i + 2
  429.             newvar = True
  430.         else:
  431.             newvar = False
  432.             break
  433.         return newvar
  434.  
  435.  
  436. def new_accnt_details():
  437.     email = input("enter email")
  438.     check(email)
  439.     domain = input("enter domain:")
  440.     if domain.lower() in ['instagram', 'facebook', 'twitter', 'netflix', 'gmail', 'reddit', 'amazon']:
  441.         print("that domain is availabe in our prebuilts, please select the appropriate option")
  442.         main_menu()
  443.     password = final_password()
  444.     L = {f'{domain}': [f'{email}', f"{password}"]}
  445.     cursor.execute('insert into pwm values((%s),(%s),(%s));', (domain,email, password))
  446.     write_func(L)
  447.     csv_operations(L)
  448.  
  449.  
  450.  
  451. def emailgen():
  452.     num_of_chars = int(input("enter number of characters between 4 to 20: "))
  453.     if num_of_chars < 4 or num_of_chars > 20:
  454.         print("number of chars excceding limit")
  455.         emailgen()
  456.  
  457.     else:
  458.         listofletters = [string.digits, string.ascii_lowercase, string.ascii_uppercase]
  459.         letters = "".join(listofletters)
  460.         emailformat =  "@gmail.com"
  461.         emailgenerated = "".join(random.choices(letters, k = num_of_chars))+emailformat
  462.         print(emailgenerated)
  463.  
  464.  
  465. def main_menu():
  466.     print("⁺˚*•̩̩͙✩•̩̩͙*˚⁺‧͙⁺˚*•̩̩͙⋆⁺₊⋆Ƹ̵̡Ӝ̵̨̄Ʒ⋆⁺₊⋆•̩̩͙*˚⁺‧͙⁺˚*•̩̩͙✩•̩̩͙*˚⁺‧͙")
  467.     print("1.generate a password")
  468.     print("2.managing password saves")
  469.     print("3.file settings")
  470.     print("4.add an existing account for saving")
  471.     print("5.generate new gmail id")
  472.     print("6.exit program")
  473.     print("⁺˚*•̩̩͙✩•̩̩͙*˚⁺‧͙⁺˚*•̩̩͙⋆⁺₊⋆Ƹ̵̡Ӝ̵̨̄Ʒ⋆⁺₊⋆•̩̩͙*˚⁺‧͙⁺˚*•̩̩͙✩•̩̩͙*˚⁺‧")
  474.     action = input("enter key :")
  475.     if (action == '1'):
  476.  
  477.         print(
  478.             "╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱"
  479.             "\nWhich of the following sites would you like to generate a password for:\n1.instagram\n2.facebook\n3.twitter\n4.netflix\n5.reddit\n6.amazon\n7.gmail\n8.other\n9.menu"
  480.             "\n╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱╲⎝⧹╲⎝⧹⧸⎠╱⧸⎠╱")
  481.         key = input("enter key :")
  482.  
  483.         if (key == '1'):
  484.             instagram()
  485.         elif (key == '2'):
  486.             facebook()
  487.         elif (key == '3'):
  488.             twitter()
  489.         elif (key == '4'):
  490.             netflix()
  491.         elif (key == '5'):
  492.             reddit()
  493.         elif (key == '6'):
  494.             amazon()
  495.         elif (key == '7'):
  496.             gmail()
  497.         elif (key == "8"):
  498.             new_accnt_details()
  499.         else:
  500.             print("key does not match!\n enter a valid option")
  501.             main_menu()
  502.     elif (action == '2'):
  503.         print("1.view saved passwords"
  504.               "\n2.edit saved passwords")
  505.         keyforaction_2 = input("enter key:")
  506.  
  507.         if (keyforaction_2 == "1"):
  508.             print(view_func())
  509.         elif (keyforaction_2 == "2"):
  510.  
  511.             edit(input("domain:"),input("mail:"))
  512.         else:
  513.             print("thats not a valid key!")
  514.             encrypt()
  515.             exit()
  516.     elif (action == '3'):
  517.         key = input("\nchoose the following actions:\n1.delete file\n2.copy data to another file and delete existing file\n:")
  518.         if key not in ['1', '2']:
  519.             print("\nplease choose a valid key")
  520.             main_menu()
  521.         elif (key == "1"):
  522.             del_func()
  523.         elif (key == '2'):
  524.             print("\nAre you sure want to permanently delete this file and move dta to a new file")
  525.             key = input("1.yes""\n2.no")
  526.             if key == '1':
  527.                 copytoanother_file_remove_exisitingfile()
  528.             else:
  529.                 obj.commit()
  530.                 encrypt()
  531.                 exit()
  532.  
  533.  
  534.  
  535.  
  536.  
  537.     elif (action == '4'):
  538.         new_accnt_details()
  539.  
  540.     elif (action == '5'):
  541.         emailgen()
  542.  
  543.  
  544.     elif (action == '6'):
  545.         print("exiting")
  546.         print(
  547.             "💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟💠⃟")
  548.         encrypt()
  549.         obj.commit()
  550.         sys.exit()
  551.  
  552.  
  553. if ".enc" not in f'{currentfile_location()}'and ".enc" not in f'{csv_filelocation()}' and not os.path.exists(os.path.join(f'{os.getcwd()}','filekey.key')):
  554.     pass
  555. else:
  556.     decrypt()
  557. if check_access():
  558.     a = 'y'
  559.     try:
  560.         while a.lower() == 'y':
  561.  
  562.             print("Welcome to password Generator and Manager!")
  563.             print("press the key to perform the required action!")
  564.             main_menu()
  565.             a = input("would you like to continue?(y/n) :")
  566.             if a.lower() == '':
  567.                 obj.commit()
  568.                 encrypt()
  569.                 print("no input detected")
  570.                 sys.exit()
  571.         else:
  572.             obj.commit()
  573.             encrypt()
  574.             sys.exit()
  575.     except KeyboardInterrupt:
  576.         encrypt()
  577.         obj.commit()
  578.         print(" program interrupted")
  579.         sys.exit(0)
  580.        
  581. else:
  582.     sys.exit()
  583.  
  584.  
  585.  
  586.  
  587.  
  588.  
  589.  
  590.  
  591.  
  592.  
  593.  
  594.  
  595.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement