home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyth_os2.zip / python-1.0.2 / Demo / rsa / bin2rand.py < prev    next >
Text File  |  1993-12-17  |  1KB  |  55 lines

  1.  
  2. from report import *
  3. from binary import *
  4.  
  5. success_rate = 10
  6.  
  7. class Bin2Rand:
  8.     #
  9.     #
  10.     #
  11.     def __init__(self, ef):
  12.         self.ef = ef        # pointer to the expand function
  13.         self.n = None
  14.         self.highest_multiple = None
  15.         self.l = None
  16.     #
  17.     #
  18.     #
  19.     def random(self, n):
  20.         if n != self.n:
  21.             self._newlimit(n)
  22.         return self._random()
  23.     #
  24.     #
  25.     #
  26.     def _newlimit(self, n):
  27.         reportnl('Bin2Rand()._newlimit(' + `n` + ')')
  28.         if n <= 0:
  29.             raise ValueError, 'bin2rand._newlimit(n): n <= 0'
  30.         self.n = n
  31.         self.l = len(tobinary(n))
  32.         ceil = frombinary('\0' * self.l + '\1')
  33.         quot, rem = divmod(ceil, n)
  34.         if rem != 0 and quot < success_rate:
  35.             reportnl('Bin2Rand()._newlimit: 1 byte more')
  36.             self.l = self.l + 1
  37.             ceil = ceil << 8
  38.             quot, rem = divmod(ceil, n)
  39.         self.highest_multiple = ceil - rem  # should be eq. to  quot*n
  40.     #
  41.     #
  42.     #
  43.     def _random(self):
  44.         reportnl('Bin2Rand()._random()')
  45.         while 1:
  46.             result = frombinary(self.ef(self.l))
  47.             if result < self.highest_multiple:
  48.                 break
  49.             reportnl(('Bin2Rand()._random(): retrying, result', result))
  50.         return result % self.n
  51.  
  52. def bin2rand(ef):
  53.     reportnl('bin2rand(' + `ef` + ')')
  54.     return Bin2Rand(ef)
  55.