Using Encryption/Hashing to create a secure login, Is it secure?












0












$begingroup$


Good evening all,



I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!



import hashlib
import mysql.connector
from tkinter import *
from tkinter import messagebox
from cryptography.fernet import Fernet

chat = Tk() #Api I am using to create the GUI for the application

#Connect to MySQL database
try:
loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
retrivedKey = loginFRetrieve.read()
loginFRetrieve.close()

loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
retrivedLC = loginFRetrieve.read()
loginFRetrieve.close()

cipher = Fernet(retrivedKey)
retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
retrivedLC = retrivedLC.decode('utf-8')
lC = retrivedLC.split()

mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
del(lC)
except mysql.connector.Error as err:
chat.withdraw()
messagebox.showerror("Database Error", "Failed to connect to database")
exit()



mycursor = mydb.cursor()

#hashPass hashes and returns a string of characters using SHA-256 algorithm
def hashPass(hP):
shaSignature =
hashlib.sha256(hP.encode()).hexdigest()
return shaSignature

#userExists checks a database too see if username exists in the database
def userExists(userName):
mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
userResult = mycursor.fetchall()
if userResult:
return True
return False

#Creates a new user in the connected SQL database.
def newUser(nU, nP):
if userExists(nU) == False:
mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
mycursor.fetchall()
r = hashPass(nP)
sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
val = (nU, r)
mycursor.execute(sql, val)
mydb.commit()
chat.title(string="User created")
else:
messagebox.showwarning("User Creation Error", "User already exists")

#Checks the connected SQL database for an existing user.
def existingUser(uN, pW):
if userN.get() != "":
if userExists(uN) == True:
encryptedPass = hashPass(pW)
mycursor.execute("SELECT * FROM logins")
passResult = mycursor.fetchall()
for row in passResult:
if row[1] == uN and row[2] == encryptedPass:
chat.title(string="Login Successful!")
elif row[1] == uN and row[2] != encryptedPass:
messagebox.showerror("Login Error", "Password does not match our records")
else:
messagebox.showerror("Login Error", "User does not exist")
else:
messagebox.showwarning("Login Error", "Please enter a username")









share|improve this question









New contributor




Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$

















    0












    $begingroup$


    Good evening all,



    I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!



    import hashlib
    import mysql.connector
    from tkinter import *
    from tkinter import messagebox
    from cryptography.fernet import Fernet

    chat = Tk() #Api I am using to create the GUI for the application

    #Connect to MySQL database
    try:
    loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
    retrivedKey = loginFRetrieve.read()
    loginFRetrieve.close()

    loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
    retrivedLC = loginFRetrieve.read()
    loginFRetrieve.close()

    cipher = Fernet(retrivedKey)
    retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
    retrivedLC = retrivedLC.decode('utf-8')
    lC = retrivedLC.split()

    mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
    del(lC)
    except mysql.connector.Error as err:
    chat.withdraw()
    messagebox.showerror("Database Error", "Failed to connect to database")
    exit()



    mycursor = mydb.cursor()

    #hashPass hashes and returns a string of characters using SHA-256 algorithm
    def hashPass(hP):
    shaSignature =
    hashlib.sha256(hP.encode()).hexdigest()
    return shaSignature

    #userExists checks a database too see if username exists in the database
    def userExists(userName):
    mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
    userResult = mycursor.fetchall()
    if userResult:
    return True
    return False

    #Creates a new user in the connected SQL database.
    def newUser(nU, nP):
    if userExists(nU) == False:
    mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
    mycursor.fetchall()
    r = hashPass(nP)
    sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
    val = (nU, r)
    mycursor.execute(sql, val)
    mydb.commit()
    chat.title(string="User created")
    else:
    messagebox.showwarning("User Creation Error", "User already exists")

    #Checks the connected SQL database for an existing user.
    def existingUser(uN, pW):
    if userN.get() != "":
    if userExists(uN) == True:
    encryptedPass = hashPass(pW)
    mycursor.execute("SELECT * FROM logins")
    passResult = mycursor.fetchall()
    for row in passResult:
    if row[1] == uN and row[2] == encryptedPass:
    chat.title(string="Login Successful!")
    elif row[1] == uN and row[2] != encryptedPass:
    messagebox.showerror("Login Error", "Password does not match our records")
    else:
    messagebox.showerror("Login Error", "User does not exist")
    else:
    messagebox.showwarning("Login Error", "Please enter a username")









    share|improve this question









    New contributor




    Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$















      0












      0








      0





      $begingroup$


      Good evening all,



      I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!



      import hashlib
      import mysql.connector
      from tkinter import *
      from tkinter import messagebox
      from cryptography.fernet import Fernet

      chat = Tk() #Api I am using to create the GUI for the application

      #Connect to MySQL database
      try:
      loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
      retrivedKey = loginFRetrieve.read()
      loginFRetrieve.close()

      loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
      retrivedLC = loginFRetrieve.read()
      loginFRetrieve.close()

      cipher = Fernet(retrivedKey)
      retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
      retrivedLC = retrivedLC.decode('utf-8')
      lC = retrivedLC.split()

      mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
      del(lC)
      except mysql.connector.Error as err:
      chat.withdraw()
      messagebox.showerror("Database Error", "Failed to connect to database")
      exit()



      mycursor = mydb.cursor()

      #hashPass hashes and returns a string of characters using SHA-256 algorithm
      def hashPass(hP):
      shaSignature =
      hashlib.sha256(hP.encode()).hexdigest()
      return shaSignature

      #userExists checks a database too see if username exists in the database
      def userExists(userName):
      mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
      userResult = mycursor.fetchall()
      if userResult:
      return True
      return False

      #Creates a new user in the connected SQL database.
      def newUser(nU, nP):
      if userExists(nU) == False:
      mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
      mycursor.fetchall()
      r = hashPass(nP)
      sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
      val = (nU, r)
      mycursor.execute(sql, val)
      mydb.commit()
      chat.title(string="User created")
      else:
      messagebox.showwarning("User Creation Error", "User already exists")

      #Checks the connected SQL database for an existing user.
      def existingUser(uN, pW):
      if userN.get() != "":
      if userExists(uN) == True:
      encryptedPass = hashPass(pW)
      mycursor.execute("SELECT * FROM logins")
      passResult = mycursor.fetchall()
      for row in passResult:
      if row[1] == uN and row[2] == encryptedPass:
      chat.title(string="Login Successful!")
      elif row[1] == uN and row[2] != encryptedPass:
      messagebox.showerror("Login Error", "Password does not match our records")
      else:
      messagebox.showerror("Login Error", "User does not exist")
      else:
      messagebox.showwarning("Login Error", "Please enter a username")









      share|improve this question









      New contributor




      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      Good evening all,



      I am creating a login for an encrypted chat application which retrieves login information from a MySQL database. I have got to the point where I feel pretty confident that (to the best of my knowledge) it is relatively secure. I am trying to learn so feel free to criticize!



      import hashlib
      import mysql.connector
      from tkinter import *
      from tkinter import messagebox
      from cryptography.fernet import Fernet

      chat = Tk() #Api I am using to create the GUI for the application

      #Connect to MySQL database
      try:
      loginFRetrieve = open("LK.bin", "rb") #Retrieving Encryption key from file
      retrivedKey = loginFRetrieve.read()
      loginFRetrieve.close()

      loginFRetrieve = open("LC.bin", "rb") #Retrieving MySQL server login credentials
      retrivedLC = loginFRetrieve.read()
      loginFRetrieve.close()

      cipher = Fernet(retrivedKey)
      retrivedLC = cipher.decrypt(retrivedLC) #Decrypting server login data from file
      retrivedLC = retrivedLC.decode('utf-8')
      lC = retrivedLC.split()

      mydb = mysql.connector.connect(host=lC[0],user=lC[1],passwd=lC[2],database=lC[3])
      del(lC)
      except mysql.connector.Error as err:
      chat.withdraw()
      messagebox.showerror("Database Error", "Failed to connect to database")
      exit()



      mycursor = mydb.cursor()

      #hashPass hashes and returns a string of characters using SHA-256 algorithm
      def hashPass(hP):
      shaSignature =
      hashlib.sha256(hP.encode()).hexdigest()
      return shaSignature

      #userExists checks a database too see if username exists in the database
      def userExists(userName):
      mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % userName)
      userResult = mycursor.fetchall()
      if userResult:
      return True
      return False

      #Creates a new user in the connected SQL database.
      def newUser(nU, nP):
      if userExists(nU) == False:
      mycursor.execute("SELECT username FROM logins WHERE username = '%s'" % nU)
      mycursor.fetchall()
      r = hashPass(nP)
      sql = "INSERT INTO logins(username, passwordhash) VALUES(%s,%s)"
      val = (nU, r)
      mycursor.execute(sql, val)
      mydb.commit()
      chat.title(string="User created")
      else:
      messagebox.showwarning("User Creation Error", "User already exists")

      #Checks the connected SQL database for an existing user.
      def existingUser(uN, pW):
      if userN.get() != "":
      if userExists(uN) == True:
      encryptedPass = hashPass(pW)
      mycursor.execute("SELECT * FROM logins")
      passResult = mycursor.fetchall()
      for row in passResult:
      if row[1] == uN and row[2] == encryptedPass:
      chat.title(string="Login Successful!")
      elif row[1] == uN and row[2] != encryptedPass:
      messagebox.showerror("Login Error", "Password does not match our records")
      else:
      messagebox.showerror("Login Error", "User does not exist")
      else:
      messagebox.showwarning("Login Error", "Please enter a username")






      python python-3.x mysql authentication






      share|improve this question









      New contributor




      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited 1 hour ago









      esote

      2,6861936




      2,6861936






      New contributor




      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 2 hours ago









      Mr.cleanMr.clean

      1




      1




      New contributor




      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Mr.clean is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






















          1 Answer
          1






          active

          oldest

          votes


















          0












          $begingroup$

          Encryption isn't Hashing



          encryptedPass = hashPass(pW)


          You're not encrypting the password, you're hashing it.



          For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.



          Sanitize input



          From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.



          You should be passing the variables as arguments to execute() every time.






          share|improve this answer











          $endgroup$













          • $begingroup$
            Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
            $endgroup$
            – Mr.clean
            1 hour ago










          • $begingroup$
            @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
            $endgroup$
            – esote
            57 mins ago











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });






          Mr.clean is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213774%2fusing-encryption-hashing-to-create-a-secure-login-is-it-secure%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0












          $begingroup$

          Encryption isn't Hashing



          encryptedPass = hashPass(pW)


          You're not encrypting the password, you're hashing it.



          For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.



          Sanitize input



          From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.



          You should be passing the variables as arguments to execute() every time.






          share|improve this answer











          $endgroup$













          • $begingroup$
            Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
            $endgroup$
            – Mr.clean
            1 hour ago










          • $begingroup$
            @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
            $endgroup$
            – esote
            57 mins ago
















          0












          $begingroup$

          Encryption isn't Hashing



          encryptedPass = hashPass(pW)


          You're not encrypting the password, you're hashing it.



          For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.



          Sanitize input



          From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.



          You should be passing the variables as arguments to execute() every time.






          share|improve this answer











          $endgroup$













          • $begingroup$
            Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
            $endgroup$
            – Mr.clean
            1 hour ago










          • $begingroup$
            @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
            $endgroup$
            – esote
            57 mins ago














          0












          0








          0





          $begingroup$

          Encryption isn't Hashing



          encryptedPass = hashPass(pW)


          You're not encrypting the password, you're hashing it.



          For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.



          Sanitize input



          From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.



          You should be passing the variables as arguments to execute() every time.






          share|improve this answer











          $endgroup$



          Encryption isn't Hashing



          encryptedPass = hashPass(pW)


          You're not encrypting the password, you're hashing it.



          For passwords you should not be hashing them with the SHA2 family. Instead, use bcrypt.



          Sanitize input



          From my limited knowledge of Python, it doesn't appear you're sanitizing your input on some functions, for example userExists() and the first query in newUser(). Instead, you're using simple string formatting to substitute values directly.



          You should be passing the variables as arguments to execute() every time.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 1 hour ago

























          answered 1 hour ago









          esoteesote

          2,6861936




          2,6861936












          • $begingroup$
            Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
            $endgroup$
            – Mr.clean
            1 hour ago










          • $begingroup$
            @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
            $endgroup$
            – esote
            57 mins ago


















          • $begingroup$
            Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
            $endgroup$
            – Mr.clean
            1 hour ago










          • $begingroup$
            @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
            $endgroup$
            – esote
            57 mins ago
















          $begingroup$
          Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
          $endgroup$
          – Mr.clean
          1 hour ago




          $begingroup$
          Thanks for the input! What's your thoughts on the way I am retrieving the key from the bin file and decrypting the server login credentials? Is this a secure way to store connection strings?
          $endgroup$
          – Mr.clean
          1 hour ago












          $begingroup$
          @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
          $endgroup$
          – esote
          57 mins ago




          $begingroup$
          @Mr.clean I am not very familiar with Python. It looks okay, but security is very nuanced and I can't say for sure. Perhaps, if variables persist beyond the try-catch scope, you could del other variables used in it.
          $endgroup$
          – esote
          57 mins ago










          Mr.clean is a new contributor. Be nice, and check out our Code of Conduct.










          draft saved

          draft discarded


















          Mr.clean is a new contributor. Be nice, and check out our Code of Conduct.













          Mr.clean is a new contributor. Be nice, and check out our Code of Conduct.












          Mr.clean is a new contributor. Be nice, and check out our Code of Conduct.
















          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f213774%2fusing-encryption-hashing-to-create-a-secure-login-is-it-secure%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          How to make a Squid Proxy server?

          Is this a new Fibonacci Identity?

          Touch on Surface Book