The crypt Module

(Optional) The crypt module implements one-way DES encryption. Unix systems use this encryption algorithm to store passwords, and this module is really only useful to generate or check such passwords.

Example 2-40 shows how to encrypt a password by calling crypt.crypt with the password string, plus a salt, which should consist of two random characters. You can now throw away the actual password, and just store the encrypted string.

Example 2-40. Using the crypt Module

File: crypt-example-1.py

import crypt

import random, string

def getsalt(chars = string.letters + string.digits):
 # generate a random 2-character 'salt'
 return random.choice(chars) + random.choice(chars)

print crypt.crypt("bananas", getsalt())


To verify a given password, encrypt the new password using the two first characters from the encrypted string as the salt. If the result matches the encrypted string, the password is valid. Example 2-41 uses the pwd module to fetch the encrypted password for a given user.

Example 2-41. Using the crypt Module for Authentication

File: crypt-example-2.py

import pwd, crypt

def login(user, password):
 "Check if user would be able to log in using password"
 pw1 = pwd.getpwnam(user)[1]
 pw2 = crypt.crypt(password, pw1[:2])
 return pw1 == pw2
 except KeyError:
 return 0 # no such user

user = raw_input("username:")
password = raw_input("password:")

if login(user, password):
 print "welcome", user
 print "login failed"

For other ways to implement authentication, see the description of the md5 module.

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net