Python Authentication API

I'm looking for a python library that will help me to create an authentication method for a desktop app I'm writing. I have found several method in web framework such as django or turbogears.

I just want a kind of username-password association stored into a local file. I can write it by myself, but I'm really it already exists and will be a better solution (I'm not very fluent with encryption).


Asked by: Walter502 | Posted: 24-09-2021






Answer 1

dbr said:

def hash_password(password):
    """Returns the hashed version of a string
    """
    return hasher.new( str(password) ).hexdigest()

This is a really insecure way to hash passwords. You don't want to do this. If you want to know why read the Bycrypt Paper by the guys who did the password hashing system for OpenBSD. Additionally if want a good discussion on how passwords are broken check out this interview with the author of Jack the Ripper (the popular unix password cracker).

Now B-Crypt is great but I have to admit I don't use this system because I didn't have the EKS-Blowfish algorithm available and did not want to implement it my self. I use a slightly updated version of the FreeBSD system which I will post below. The gist is this. Don't just hash the password. Salt the password then hash the password and repeat 10,000 or so times.

If that didn't make sense here is the code:

#note I am using the Python Cryptography Toolkit
from Crypto.Hash import SHA256

HASH_REPS = 50000

def __saltedhash(string, salt):
    sha256 = SHA256.new()
    sha256.update(string)
    sha256.update(salt)
    for x in xrange(HASH_REPS): 
        sha256.update(sha256.digest())
        if x % 10: sha256.update(salt)
    return sha256

def saltedhash_bin(string, salt):
    """returns the hash in binary format"""
    return __saltedhash(string, salt).digest()

def saltedhash_hex(string, salt):
    """returns the hash in hex format"""
    return __saltedhash(string, salt).hexdigest()

For deploying a system like this the key thing to consider is the HASH_REPS constant. This is the scalable cost factor in this system. You will need to do testing to determine what is the exceptable amount of time you want to wait for each hash to be computed versus the risk of an offline dictionary based attack on your password file.

Security is hard, and the method I present is not the best way to do this, but it is significantly better than a simple hash. Additionally it is dead simple to implement. So even you don't choose a more complex solution this isn't the worst out there.

hope this helps, Tim

Answered by: Melanie278 | Posted: 25-10-2021



Answer 2

I think you should make your own authentication method as you can make it fit your application best but use a library for encryption, such as pycrypto or some other more lightweight library.

btw, if you need windows binaries for pycrypto you can get them here

Answered by: Max941 | Posted: 25-10-2021



Answer 3

Treat the following as pseudo-code..

try:
    from hashlib import sha as hasher
except ImportError:
    # You could probably exclude the try/except bit,
    # but older Python distros dont have hashlib.
    try:
        import sha as hasher
    except ImportError:
        import md5 as hasher


def hash_password(password):
    """Returns the hashed version of a string
    """
    return hasher.new( str(password) ).hexdigest()

def load_auth_file(path):
    """Loads a comma-seperated file.
    Important: make sure the username
    doesn't contain any commas!
    """
    # Open the file, or return an empty auth list.
    try:
        f = open(path)
    except IOError:
        print "Warning: auth file not found"
        return {}

    ret = {}
    for line in f.readlines():
        split_line = line.split(",")
        if len(split_line) > 2:
            print "Warning: Malformed line:"
            print split_line
            continue # skip it..
        else:
            username, password = split_line
            ret[username] = password
        #end if
    #end for
    return ret

def main():
    auth_file = "/home/blah/.myauth.txt"
    u = raw_input("Username:")
    p = raw_input("Password:") # getpass is probably better..
    if auth_file.has_key(u.strip()):
        if auth_file[u] == hash_password(p):
            # The hash matches the stored one
            print "Welcome, sir!"

Instead of using a comma-separated file, I would recommend using SQLite3 (which could be used for other settings and such.

Also, remember that this isn't very secure - if the application is local, evil users could probably just replace the ~/.myauth.txt file.. Local application auth is difficult to do well. You'll have to encrypt any data it reads using the users password, and generally be very careful.

Answered by: Maddie795 | Posted: 25-10-2021



Answer 4

If you want simple, then use a dictionary where the keys are the usernames and the values are the passwords (encrypted with something like SHA256). Pickle it to/from disk (as this is a desktop application, I'm assuming the overhead of keeping it in memory will be negligible).

For example:

import pickle
import hashlib

# Load from disk
pwd_file = "mypasswords"
if os.path.exists(pwd_file):
    pwds = pickle.load(open(pwd_file, "rb"))
else:
    pwds = {}

# Save to disk
pickle.dump(pwds, open(pwd_file, "wb"))

# Add password
pwds[username] = hashlib.sha256(password).hexdigest()

# Check password
if pwds[username] = hashlib.sha256(password).hexdigest():
   print "Good"
else:
   print "No match"

Note that this stores the passwords as a hash - so they are essentially unrecoverable. If you lose your password, you'd get allocated a new one, not get the old one back.

Answered by: John335 | Posted: 25-10-2021



Answer 5

import hashlib
import random

def gen_salt():
    salt_seed = str(random.getrandbits(128))
    salt = hashlib.sha256(salt_seed).hexdigest()
    return salt

def hash_password(password, salt):
    h = hashlib.sha256()
    h.update(salt)
    h.update(password)
    return h.hexdigest()

#in datastore
password_stored_hash = "41e2282a9c18a6c051a0636d369ad2d4727f8c70f7ddeebd11e6f49d9e6ba13c"
salt_stored = "fcc64c0c2bc30156f79c9bdcabfadcd71030775823cb993f11a4e6b01f9632c3"

password_supplied = 'password'

password_supplied_hash = hash_password(password_supplied, salt_stored)
authenticated = (password_supplied_hash == password_stored_hash)
print authenticated #True

see also gae-authenticate-to-a-3rd-party-site

Answered by: Ada837 | Posted: 25-10-2021



Answer 6

Use " md5 " it's much better than base64

>>> import md5
>>> hh = md5.new()
>>> hh.update('anoop')
>>> hh.digest
<built-in method digest of _hashlib.HASH object at 0x01FE1E40>

Answered by: Paul755 | Posted: 25-10-2021



Similar questions

Authentication for API & Python

I'm trying to get make an API for the first time and I've made my app but it says I have to do a local authentication with instructions here: Link to TDAmeritrade authentication But it says I have to go on https://...


python - User Authentication in Django

is there any way of making sure that, one user is logged in only once? I would like to avoid two different persons logging into the system with the same login/password. I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality. Cheers, Thanks for the responses!


python - Using AD as authentication for Django

I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities. Does anyone have a good example of this?


python - Google Data API authentication

I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs ...


curl - HTTP Authentication in Python

Whats is the python urllib equivallent of curl -u username:password status="abcd" http://example.com/update.json I did this: handle = urllib2.Request(url) authheader = "Basic %s" % base64.encodestring('%s:%s' % (username, password)) handle.add_header("Authorization", authheader) Is there a better / simpler way?


Python HTTPS client with basic authentication via proxy

From Python, I would like to retrieve content from a web site via HTTPS with basic authentication. I need the content on disk. I am on an intranet, trusting the HTTPS server. Platform is Python 2.6.2 on Windows. I have been playing around with urllib2, however did not succeed so far. I have a solution running, calling wget via os.system(): wget_cmd = r'\path\to\wget.exe -q -e "https_proxy = ...


python - Authentication in django

I'm trying to do connect form on my django website If in a shell I do : $ ./manage.py shell Python 2.6.4 (r264:75706, Oct 27 2009, 06:25:13) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) &gt;&gt;&gt; from django.contrib import auth &gt;&gt;&gt; user = auth.authenticate(username='user', password='password') &gt;&gt;&gt;


Python Authentication to SAMBA share

I'm able to map the drive without problems on network shares without authentication. But I'm missing something once I try to authenticate with a username and password. Here is the current working example of the code with the error message I keep receiving. #!/usr/bin/python # Drive Map Script import pywintypes import win32com.client # Disconnect previous mapped drives testnetwork = win32com.client.Dispatch...


NTLM authentication in Python

I'm trying to implement NTLM authentication on IIS (Windows Server 2003) from Windows 7 with python. LAN Manager Authentication Level: Send NTLM response only. Client machine and server are in the same domain. Domain controller (AD) is on another server (also running Windows Server 2003). I receive 401.1 - Unauthorized: Access is denied due to invalid credentials. Could you please help me find out what is w...


authentication - Why does Python (with twill) not want to log me in to a Yahoo mail box here?

Can anyone, please, explain to me what's going on here. It seems that Python refuses to work (with twill) when I am trying to log in to my mailbox on Yahoo: Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software m...


python - Django RSS Feed Authentication

I am looking into adding RSS feeds to one of my Django apps and I would like to be able to have them be authenticated. I want to use the new syndication framework in Django 1.2. I've read the docs on how to do this and have the basic feeds setup. I am new to authenticating feeds, so I am not sure what the best approach to take is or what my options really are. Each user has a unique sub domain a...


Can I implement a web user authentication system in python without POST?

My university doesn't support the POST cgi method (I know, it's crazy), and I was hoping to be able to have a system where a user can have a username and password and log in securely. Is this even possible? If it's not, how would you do it with POST? Just out of curiosity. Cheers!


javascript - Django authentication and Ajax - URLs that require login

I want to add some Ajax-niceness to my Django-coded website. In my Django code, I use the @login_required decorator from django.contrib.auth.decorators to mark which view requires authentication. The default behavior when a not authenticated user clicks it is to redirect him/her to login page, and then pass...


authentication - Authenticating against active directory using python + ldap

How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_SUBTREE Filter = "(&amp;(objectClass=user)(sAMAccountName="+un+"))" Attrs = ["displ...


python - User Authentication in Django

is there any way of making sure that, one user is logged in only once? I would like to avoid two different persons logging into the system with the same login/password. I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality. Cheers, Thanks for the responses!


authentication - In Python, how might one log in, answer a web form via HTTP POST (not url-encoded), and fetch a returned XML file?

I am basically trying to export a configuration file, once a week. While the product in question allows you to log in manually via a web client, enter some information, and get an XML file back when you submit, there's no facility for automating this. I can get away with using Python 2.5 (have used for a while) or 2.6 (unfamiliar) to do this. I think I need to have some way to authenticate against the pr...


Python - downloading a file over HTTP with progress bar and basic authentication

I'm using urllib.urlretrieve to download a file, and implementing a download progress bar using the reporthook parameter. Since urlretrieve doesn't directly support authentication, I came up with import urllib def urlretrieve_with_basic_auth(url, filename=None, reporthook=None, data=None, username="", password=""): class OpenerWith...


authentication - What's the best way to specify a proxy with username and password for an **https** connection in python?

I read somewhere that currently urllib2 doesn't support authenticated https connection. My proxy uses a basic authentication only, but how to open an https based webpage through it . Please help me. Thanks.


python - Using AD as authentication for Django

I'm working on a Django-based application in a corporate environment and would like to use the existing Active Directory system for authentication of users (so they don't get yet another login/password combo). I would also like to continue to use Django's user authorization / permission system to manage user capabilities. Does anyone have a good example of this?


python - Google Data API authentication

I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs ...


json - Authentication Required - Problems Establishing AIM OSCAR Session using Python

I'm writing a simple python script that will interface with the AIM servers using the OSCAR protocol. It includes a somewhat complex handshake protocol. You essentially have to send a GET request to a specific URL, receive XML or JSON encoded reply, extract a special session token and secret key, then generate a response using the token and the key. ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top