""" Password encryption. """

__version__ = "$Revision: 1.5 $"
# $Source: /home/vladap/src/mysqlUserFolder/RCS/passwords.py,v $
#
# $Author: vladap $
# $Date: 2004/05/15 18:25:16 $


PASSWD_ENC_LIST = [
	(0, 'Clear text'),
	(1, 'UNIX crypt'),
	(2, 'MD5 Digest'),
]

import random, md5

has_crypt = 1

try: import crypt
except: has_crypt = 0

# --------------------------------------------------------------------- */
# Interface functions.

def encode (password, type):
	if type == 0:
		return password

	elif type == 1:
		return pwe_crypt (password)

	elif type == 2:
		return pwe_md5_crypt (password)

	else:
		raise 'Unknown password type: %s' % type


def check (password, enc_password, type):
	if type == 0:
		return (password == enc_password)

	elif type == 1:
		return pwe_crypt_check (password, enc_password)

	elif type == 2:
		return pwe_md5_check (password, enc_password)

	else:
		raise 'Unknown password type: %s' % type


# --------------------------------------------------------------------- */
# Utility functions

def get_random_char ():
	c = random.randrange (ord ('a'), ord ('z') + 1)
	return chr (c)


# --------------------------------------------------------------------- */
# Specific crypto functions.

def pwe_crypt (password):
	if not has_crypt: raise 'Crypt module is not avaiable.'
	
	salt = get_random_char () + get_random_char ()

	return crypt.crypt (password, salt)

def pwe_crypt_check (password, enc_password):
	if not has_crypt: raise 'Crypt module is not avaiable.'

	salt = enc_password [:2]
	s = crypt.crypt (password, salt)

	return (s == enc_password)


def pwe_md5_crypt (password):
	#digest = md5.new (password).digest()
	#digest = ''.join (map (lambda x:'%02x' % ord (x), digest))

	digest = md5.new (password).hexdigest()

	return digest

def pwe_md5_check (password, enc_password):
	digest = pwe_md5_crypt (password)

	return (digest == enc_password)



