1. #
  2. # Pronouncable password generator, by Joe Koberg jkoberg@gmail.com
  3. #   based on code from http://www.multicians.org/thvv/gpw.html
  4. #
  5.  
  6.  
  7. import random
  8.  
  9. class FoundStartingPointException(Exception): pass
  10.  
  11. class PasswordGenerator:
  12.         alphabet = 'abcdefghijklmnopqrstuvwxyz'
  13.         def __init__(self, weightdata):
  14.                 self.data = weightdata
  15.                 self.sigma = self.computeSigma(weightdata)
  16.                 self.rnd = random.Random()
  17.                 self.rnd.seed()
  18.                            
  19.         def computeSigma(self, tris):
  20.                 trisigma = 0
  21.                 for chunk in tris:
  22.                         for row in chunk:
  23.                                 for col in row:
  24.                                         trisigma += col
  25.                 return trisigma
  26.                            
  27.         def getSigma(self):
  28.                 return self.sigma
  29.                
  30.         def generatePasswords(self, passwordLength=8, numPasswords=10):
  31.                 return [self.generatePassword(passwordLength) for i in range(numPasswords)]
  32.                
  33.         def generatePassword(self, passwordLength=8):
  34.                 password = ''
  35.                 # pick a random starting point
  36.                 r = self.rnd.random()
  37.                 rno = r * self.getSigma()
  38.                 sum = 0
  39.                 breakout = 0
  40.                 try:
  41.                         for i in range(26):
  42.                                 for j in range(26):
  43.                                         for k in range(26):
  44.                                                 sum += self.data[i][j][k]
  45.                                                 if sum > rno:
  46.                                                         password = password + self.alphabet[i] + self.alphabet[j] + self.alphabet[k]
  47.                                                         raise FoundStartingPointException
  48.                 except FoundStartingPointException:
  49.                         pass
  50.                
  51.                 while len(password) < passwordLength + 2:
  52.                         c0 = self.alphabet.find(password[-2])
  53.                         c1 = self.alphabet.find(password[-1])
  54.                         sum1 = 0
  55.                         for c2 in range(26):
  56.                                 sum1 += self.data[c0][c1][c2]
  57.                         if sum1 == 0:
  58.                                 # The only time this usually happens is when it generates "-ify"
  59. "__main__":
  60.         print generatePassword()