/gdata/Crypto/Util/randpool.py

http://radioappz.googlecode.com/ · Python · 421 lines · 325 code · 29 blank · 67 comment · 31 complexity · 532810ac544633f3efb7a0a10cd84c97 MD5 · raw file

  1. #
  2. # randpool.py : Cryptographically strong random number generation
  3. #
  4. # Part of the Python Cryptography Toolkit
  5. #
  6. # Distribute and use freely; there are no restrictions on further
  7. # dissemination and usage except those imposed by the laws of your
  8. # country of residence. This software is provided "as is" without
  9. # warranty of fitness for use or suitability for any purpose, express
  10. # or implied. Use at your own risk or not at all.
  11. #
  12. __revision__ = "$Id: randpool.py,v 1.14 2004/05/06 12:56:54 akuchling Exp $"
  13. import time, array, types, warnings, os.path
  14. from Crypto.Util.number import long_to_bytes
  15. try:
  16. import Crypto.Util.winrandom as winrandom
  17. except:
  18. winrandom = None
  19. STIRNUM = 3
  20. class RandomPool:
  21. """randpool.py : Cryptographically strong random number generation.
  22. The implementation here is similar to the one in PGP. To be
  23. cryptographically strong, it must be difficult to determine the RNG's
  24. output, whether in the future or the past. This is done by using
  25. a cryptographic hash function to "stir" the random data.
  26. Entropy is gathered in the same fashion as PGP; the highest-resolution
  27. clock around is read and the data is added to the random number pool.
  28. A conservative estimate of the entropy is then kept.
  29. If a cryptographically secure random source is available (/dev/urandom
  30. on many Unixes, Windows CryptGenRandom on most Windows), then use
  31. it.
  32. Instance Attributes:
  33. bits : int
  34. Maximum size of pool in bits
  35. bytes : int
  36. Maximum size of pool in bytes
  37. entropy : int
  38. Number of bits of entropy in this pool.
  39. Methods:
  40. add_event([s]) : add some entropy to the pool
  41. get_bytes(int) : get N bytes of random data
  42. randomize([N]) : get N bytes of randomness from external source
  43. """
  44. def __init__(self, numbytes = 160, cipher=None, hash=None):
  45. if hash is None:
  46. from Crypto.Hash import SHA as hash
  47. # The cipher argument is vestigial; it was removed from
  48. # version 1.1 so RandomPool would work even in the limited
  49. # exportable subset of the code
  50. if cipher is not None:
  51. warnings.warn("'cipher' parameter is no longer used")
  52. if isinstance(hash, types.StringType):
  53. # ugly hack to force __import__ to give us the end-path module
  54. hash = __import__('Crypto.Hash.'+hash,
  55. None, None, ['new'])
  56. warnings.warn("'hash' parameter should now be a hashing module")
  57. self.bytes = numbytes
  58. self.bits = self.bytes*8
  59. self.entropy = 0
  60. self._hash = hash
  61. # Construct an array to hold the random pool,
  62. # initializing it to 0.
  63. self._randpool = array.array('B', [0]*self.bytes)
  64. self._event1 = self._event2 = 0
  65. self._addPos = 0
  66. self._getPos = hash.digest_size
  67. self._lastcounter=time.time()
  68. self.__counter = 0
  69. self._measureTickSize() # Estimate timer resolution
  70. self._randomize()
  71. def _updateEntropyEstimate(self, nbits):
  72. self.entropy += nbits
  73. if self.entropy < 0:
  74. self.entropy = 0
  75. elif self.entropy > self.bits:
  76. self.entropy = self.bits
  77. def _randomize(self, N = 0, devname = '/dev/urandom'):
  78. """_randomize(N, DEVNAME:device-filepath)
  79. collects N bits of randomness from some entropy source (e.g.,
  80. /dev/urandom on Unixes that have it, Windows CryptoAPI
  81. CryptGenRandom, etc)
  82. DEVNAME is optional, defaults to /dev/urandom. You can change it
  83. to /dev/random if you want to block till you get enough
  84. entropy.
  85. """
  86. data = ''
  87. if N <= 0:
  88. nbytes = int((self.bits - self.entropy)/8+0.5)
  89. else:
  90. nbytes = int(N/8+0.5)
  91. if winrandom:
  92. # Windows CryptGenRandom provides random data.
  93. data = winrandom.new().get_bytes(nbytes)
  94. elif os.path.exists(devname):
  95. # Many OSes support a /dev/urandom device
  96. try:
  97. f=open(devname)
  98. data=f.read(nbytes)
  99. f.close()
  100. except IOError, (num, msg):
  101. if num!=2: raise IOError, (num, msg)
  102. # If the file wasn't found, ignore the error
  103. if data:
  104. self._addBytes(data)
  105. # Entropy estimate: The number of bits of
  106. # data obtained from the random source.
  107. self._updateEntropyEstimate(8*len(data))
  108. self.stir_n() # Wash the random pool
  109. def randomize(self, N=0):
  110. """randomize(N:int)
  111. use the class entropy source to get some entropy data.
  112. This is overridden by KeyboardRandomize().
  113. """
  114. return self._randomize(N)
  115. def stir_n(self, N = STIRNUM):
  116. """stir_n(N)
  117. stirs the random pool N times
  118. """
  119. for i in xrange(N):
  120. self.stir()
  121. def stir (self, s = ''):
  122. """stir(s:string)
  123. Mix up the randomness pool. This will call add_event() twice,
  124. but out of paranoia the entropy attribute will not be
  125. increased. The optional 's' parameter is a string that will
  126. be hashed with the randomness pool.
  127. """
  128. entropy=self.entropy # Save inital entropy value
  129. self.add_event()
  130. # Loop over the randomness pool: hash its contents
  131. # along with a counter, and add the resulting digest
  132. # back into the pool.
  133. for i in range(self.bytes / self._hash.digest_size):
  134. h = self._hash.new(self._randpool)
  135. h.update(str(self.__counter) + str(i) + str(self._addPos) + s)
  136. self._addBytes( h.digest() )
  137. self.__counter = (self.__counter + 1) & 0xFFFFffffL
  138. self._addPos, self._getPos = 0, self._hash.digest_size
  139. self.add_event()
  140. # Restore the old value of the entropy.
  141. self.entropy=entropy
  142. def get_bytes (self, N):
  143. """get_bytes(N:int) : string
  144. Return N bytes of random data.
  145. """
  146. s=''
  147. i, pool = self._getPos, self._randpool
  148. h=self._hash.new()
  149. dsize = self._hash.digest_size
  150. num = N
  151. while num > 0:
  152. h.update( self._randpool[i:i+dsize] )
  153. s = s + h.digest()
  154. num = num - dsize
  155. i = (i + dsize) % self.bytes
  156. if i<dsize:
  157. self.stir()
  158. i=self._getPos
  159. self._getPos = i
  160. self._updateEntropyEstimate(- 8*N)
  161. return s[:N]
  162. def add_event(self, s=''):
  163. """add_event(s:string)
  164. Add an event to the random pool. The current time is stored
  165. between calls and used to estimate the entropy. The optional
  166. 's' parameter is a string that will also be XORed into the pool.
  167. Returns the estimated number of additional bits of entropy gain.
  168. """
  169. event = time.time()*1000
  170. delta = self._noise()
  171. s = (s + long_to_bytes(event) +
  172. 4*chr(0xaa) + long_to_bytes(delta) )
  173. self._addBytes(s)
  174. if event==self._event1 and event==self._event2:
  175. # If events are coming too closely together, assume there's
  176. # no effective entropy being added.
  177. bits=0
  178. else:
  179. # Count the number of bits in delta, and assume that's the entropy.
  180. bits=0
  181. while delta:
  182. delta, bits = delta>>1, bits+1
  183. if bits>8: bits=8
  184. self._event1, self._event2 = event, self._event1
  185. self._updateEntropyEstimate(bits)
  186. return bits
  187. # Private functions
  188. def _noise(self):
  189. # Adds a bit of noise to the random pool, by adding in the
  190. # current time and CPU usage of this process.
  191. # The difference from the previous call to _noise() is taken
  192. # in an effort to estimate the entropy.
  193. t=time.time()
  194. delta = (t - self._lastcounter)/self._ticksize*1e6
  195. self._lastcounter = t
  196. self._addBytes(long_to_bytes(long(1000*time.time())))
  197. self._addBytes(long_to_bytes(long(1000*time.clock())))
  198. self._addBytes(long_to_bytes(long(1000*time.time())))
  199. self._addBytes(long_to_bytes(long(delta)))
  200. # Reduce delta to a maximum of 8 bits so we don't add too much
  201. # entropy as a result of this call.
  202. delta=delta % 0xff
  203. return int(delta)
  204. def _measureTickSize(self):
  205. # _measureTickSize() tries to estimate a rough average of the
  206. # resolution of time that you can see from Python. It does
  207. # this by measuring the time 100 times, computing the delay
  208. # between measurements, and taking the median of the resulting
  209. # list. (We also hash all the times and add them to the pool)
  210. interval = [None] * 100
  211. h = self._hash.new(`(id(self),id(interval))`)
  212. # Compute 100 differences
  213. t=time.time()
  214. h.update(`t`)
  215. i = 0
  216. j = 0
  217. while i < 100:
  218. t2=time.time()
  219. h.update(`(i,j,t2)`)
  220. j += 1
  221. delta=int((t2-t)*1e6)
  222. if delta:
  223. interval[i] = delta
  224. i += 1
  225. t=t2
  226. # Take the median of the array of intervals
  227. interval.sort()
  228. self._ticksize=interval[len(interval)/2]
  229. h.update(`(interval,self._ticksize)`)
  230. # mix in the measurement times and wash the random pool
  231. self.stir(h.digest())
  232. def _addBytes(self, s):
  233. "XOR the contents of the string S into the random pool"
  234. i, pool = self._addPos, self._randpool
  235. for j in range(0, len(s)):
  236. pool[i]=pool[i] ^ ord(s[j])
  237. i=(i+1) % self.bytes
  238. self._addPos = i
  239. # Deprecated method names: remove in PCT 2.1 or later.
  240. def getBytes(self, N):
  241. warnings.warn("getBytes() method replaced by get_bytes()",
  242. DeprecationWarning)
  243. return self.get_bytes(N)
  244. def addEvent (self, event, s=""):
  245. warnings.warn("addEvent() method replaced by add_event()",
  246. DeprecationWarning)
  247. return self.add_event(s + str(event))
  248. class PersistentRandomPool (RandomPool):
  249. def __init__ (self, filename=None, *args, **kwargs):
  250. RandomPool.__init__(self, *args, **kwargs)
  251. self.filename = filename
  252. if filename:
  253. try:
  254. # the time taken to open and read the file might have
  255. # a little disk variability, modulo disk/kernel caching...
  256. f=open(filename, 'rb')
  257. self.add_event()
  258. data = f.read()
  259. self.add_event()
  260. # mix in the data from the file and wash the random pool
  261. self.stir(data)
  262. f.close()
  263. except IOError:
  264. # Oh, well; the file doesn't exist or is unreadable, so
  265. # we'll just ignore it.
  266. pass
  267. def save(self):
  268. if self.filename == "":
  269. raise ValueError, "No filename set for this object"
  270. # wash the random pool before save, provides some forward secrecy for
  271. # old values of the pool.
  272. self.stir_n()
  273. f=open(self.filename, 'wb')
  274. self.add_event()
  275. f.write(self._randpool.tostring())
  276. f.close()
  277. self.add_event()
  278. # wash the pool again, provide some protection for future values
  279. self.stir()
  280. # non-echoing Windows keyboard entry
  281. _kb = 0
  282. if not _kb:
  283. try:
  284. import msvcrt
  285. class KeyboardEntry:
  286. def getch(self):
  287. c = msvcrt.getch()
  288. if c in ('\000', '\xe0'):
  289. # function key
  290. c += msvcrt.getch()
  291. return c
  292. def close(self, delay = 0):
  293. if delay:
  294. time.sleep(delay)
  295. while msvcrt.kbhit():
  296. msvcrt.getch()
  297. _kb = 1
  298. except:
  299. pass
  300. # non-echoing Posix keyboard entry
  301. if not _kb:
  302. try:
  303. import termios
  304. class KeyboardEntry:
  305. def __init__(self, fd = 0):
  306. self._fd = fd
  307. self._old = termios.tcgetattr(fd)
  308. new = termios.tcgetattr(fd)
  309. new[3]=new[3] & ~termios.ICANON & ~termios.ECHO
  310. termios.tcsetattr(fd, termios.TCSANOW, new)
  311. def getch(self):
  312. termios.tcflush(0, termios.TCIFLUSH) # XXX Leave this in?
  313. return os.read(self._fd, 1)
  314. def close(self, delay = 0):
  315. if delay:
  316. time.sleep(delay)
  317. termios.tcflush(self._fd, termios.TCIFLUSH)
  318. termios.tcsetattr(self._fd, termios.TCSAFLUSH, self._old)
  319. _kb = 1
  320. except:
  321. pass
  322. class KeyboardRandomPool (PersistentRandomPool):
  323. def __init__(self, *args, **kwargs):
  324. PersistentRandomPool.__init__(self, *args, **kwargs)
  325. def randomize(self, N = 0):
  326. "Adds N bits of entropy to random pool. If N is 0, fill up pool."
  327. import os, string, time
  328. if N <= 0:
  329. bits = self.bits - self.entropy
  330. else:
  331. bits = N*8
  332. if bits == 0:
  333. return
  334. print bits,'bits of entropy are now required. Please type on the keyboard'
  335. print 'until enough randomness has been accumulated.'
  336. kb = KeyboardEntry()
  337. s='' # We'll save the characters typed and add them to the pool.
  338. hash = self._hash
  339. e = 0
  340. try:
  341. while e < bits:
  342. temp=str(bits-e).rjust(6)
  343. os.write(1, temp)
  344. s=s+kb.getch()
  345. e += self.add_event(s)
  346. os.write(1, 6*chr(8))
  347. self.add_event(s+hash.new(s).digest() )
  348. finally:
  349. kb.close()
  350. print '\n\007 Enough. Please wait a moment.\n'
  351. self.stir_n() # wash the random pool.
  352. kb.close(4)
  353. if __name__ == '__main__':
  354. pool = RandomPool()
  355. print 'random pool entropy', pool.entropy, 'bits'
  356. pool.add_event('something')
  357. print `pool.get_bytes(100)`
  358. import tempfile, os
  359. fname = tempfile.mktemp()
  360. pool = KeyboardRandomPool(filename=fname)
  361. print 'keyboard random pool entropy', pool.entropy, 'bits'
  362. pool.randomize()
  363. print 'keyboard random pool entropy', pool.entropy, 'bits'
  364. pool.randomize(128)
  365. pool.save()
  366. saved = open(fname, 'rb').read()
  367. print 'saved', `saved`
  368. print 'pool ', `pool._randpool.tostring()`
  369. newpool = PersistentRandomPool(fname)
  370. print 'persistent random pool entropy', pool.entropy, 'bits'
  371. os.remove(fname)