Code

Centralised conversion of user-input data to hyperdb values (bug #802405,
[roundup.git] / roundup / password.py
1 #
2 # Copyright (c) 2001 Bizar Software Pty Ltd (http://www.bizarsoftware.com.au/)
3 # This module is free software, and you may redistribute it and/or modify
4 # under the same terms as Python, so long as this copyright message and
5 # disclaimer are retained in their original form.
6 #
7 # IN NO EVENT SHALL BIZAR SOFTWARE PTY LTD BE LIABLE TO ANY PARTY FOR
8 # DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING
9 # OUT OF THE USE OF THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE
10 # POSSIBILITY OF SUCH DAMAGE.
11 #
12 # BIZAR SOFTWARE PTY LTD SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
13 # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
14 # FOR A PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS"
15 # BASIS, AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
16 # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
17
18 # $Id: password.py,v 1.10 2003-11-11 00:35:13 richard Exp $
20 __doc__ = """
21 Password handling (encoding, decoding).
22 """
24 import sha, re, string, random
25 try:
26     import crypt
27 except:
28     crypt = None
29     pass
31 class PasswordValueError(ValueError):
32     ''' The password value is not valid '''
33     pass
35 def encodePassword(plaintext, scheme, other=None):
36     '''Encrypt the plaintext password.
37     '''
38     if plaintext is None:
39         plaintext = ""
40     if scheme == 'SHA':
41         s = sha.sha(plaintext).hexdigest()
42     elif scheme == 'crypt' and crypt is not None:
43         if other is not None:
44             salt = other[:2]
45         else:
46             saltchars = './0123456789'+string.letters
47             salt = random.choice(saltchars) + random.choice(saltchars)
48         s = crypt.crypt(plaintext, salt)
49     elif scheme == 'plaintext':
50         s = plaintext
51     else:
52         raise PasswordValueError, 'unknown encryption scheme %r'%scheme
53     return s
55 def generatePassword(length=8):
56     chars = string.letters+string.digits
57     return ''.join([random.choice(chars) for x in range(length)])
59 class Password:
60     '''The class encapsulates a Password property type value in the database. 
62     The encoding of the password is one if None, 'SHA' or 'plaintext'. The
63     encodePassword function is used to actually encode the password from
64     plaintext. The None encoding is used in legacy databases where no
65     encoding scheme is identified.
67     The scheme is stored with the encoded data in the database:
68         {scheme}data
70     Example usage:
71     >>> p = Password('sekrit')
72     >>> p == 'sekrit'
73     1
74     >>> p != 'not sekrit'
75     1
76     >>> 'sekrit' == p
77     1
78     >>> 'not sekrit' != p
79     1
80     '''
82     default_scheme = 'SHA'        # new encryptions use this scheme
83     pwre = re.compile(r'{(\w+)}(.+)')
85     def __init__(self, plaintext=None, scheme=None):
86         '''Call setPassword if plaintext is not None.'''
87         if scheme is None:
88             scheme = self.default_scheme
89         if plaintext is not None:
90             self.password = encodePassword(plaintext, self.default_scheme)
91             self.scheme = self.default_scheme
92         else:
93             self.password = None
94             self.scheme = self.default_scheme
96     def unpack(self, encrypted):
97         '''Set the password info from the scheme:<encryted info> string
98            (the inverse of __str__)
99         '''
100         m = self.pwre.match(encrypted)
101         if m:
102             self.scheme = m.group(1)
103             self.password = m.group(2)
104         else:
105             # currently plaintext - encrypt
106             self.password = encodePassword(encrypted, self.default_scheme)
107             self.scheme = self.default_scheme
109     def setPassword(self, plaintext, scheme=None):
110         '''Sets encrypts plaintext.'''
111         if scheme is None:
112             scheme = self.default_scheme
113         self.password = encodePassword(plaintext, scheme)
115     def __cmp__(self, other):
116         '''Compare this password against another password.'''
117         # check to see if we're comparing instances
118         if isinstance(other, Password):
119             if self.scheme != other.scheme:
120                 return cmp(self.scheme, other.scheme)
121             return cmp(self.password, other.password)
123         # assume password is plaintext
124         if self.password is None:
125             raise ValueError, 'Password not set'
126         return cmp(self.password, encodePassword(other, self.scheme,
127             self.password))
129     def __str__(self):
130         '''Stringify the encrypted password for database storage.'''
131         if self.password is None:
132             raise ValueError, 'Password not set'
133         return '{%s}%s'%(self.scheme, self.password)
135 def test():
136     # SHA
137     p = Password('sekrit')
138     assert p == 'sekrit'
139     assert p != 'not sekrit'
140     assert 'sekrit' == p
141     assert 'not sekrit' != p
143     # crypt
144     p = Password('sekrit', 'crypt')
145     assert p == 'sekrit'
146     assert p != 'not sekrit'
147     assert 'sekrit' == p
148     assert 'not sekrit' != p
150 if __name__ == '__main__':
151     test()
153 # vim: set filetype=python ts=4 sw=4 et si