Python Password Protection

Chris Aung picture Chris Aung · Sep 2, 2013 · Viewed 32.4k times · Source

I am a beginner so if this question sounds stupid, please bear with me.

I am wondering that when we write code for username/password check in python, if it is not compiled to exe ie script state, won't people will easily open the file and remove the code potion that is doing the password check?

I am assuming that the whole program is entirely written in python, no C or C++.

Even if I use a program like py2exe it can be easily decompiled back to source code. So, does that mean it is useless to do a password check?

How do professional programmers cope with that?

Answer

Mark R. Wilkins picture Mark R. Wilkins · Sep 2, 2013

Edit: Your revised question makes clear that you're concerned about people editing the code to bypass a password check. Yes, that is quite possible. You can deliver your code in .pyc form, but that won't necessarily prevent someone from decompiling and altering it. Unfortunately, Python's just not designed to prevent code alteration. The best you can do is perform some kind of authentication transaction with a secure server, so that no matter how someone alters the code, they can't bypass that step. Depending on your exact application, that might be overkill.


The problem of how to manage password authentication is a tricky security problem on which people spend entire careers. However, here's some information about it, that assumes that you're trying to roll your own password authentication from scratch:

Even for casual password protection, as a general rule, user passwords are not stored in a plaintext form. Instead, usually a reliable one-way hash function is used to create a bit pattern that doesn't resemble the password. When a password is entered, the same hash function is applied and the bit patterns are compared. If they're the same, the likelihood is quite high that the password was entered correctly.

What constitutes a "reliable" hash function is tricky. Several are in common use, and some of the common hash functions are susceptible to known exploits.

Noelkd provides some code that demonstrates this approach, although MD5, which his code uses, is (I believe) one that's been compromised to an extent that there are better choices out there. This article also offers some code to do something similar:

Authentication of Users and Passwords in Python

If your concern is storing the actual password that you have to pass to the SQLite database in plaintext, that's a different problem. Most of the time, I've seen such passwords stored in plaintext in either scripts or a configuration file, and the application is structured in such a way that compromising that password is a matter of modest risk.