(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.
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" try: 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 else: print "login failed"
For other ways to implement authentication, see the description of the
md5
module.
18.191.237.194