Fortuna.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /* Fortuna.java -- The Fortuna PRNG.
  2. Copyright (C) 2004, 2006 Free Software Foundation, Inc.
  3. This file is a part of GNU Classpath.
  4. GNU Classpath is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 2 of the License, or (at
  7. your option) any later version.
  8. GNU Classpath is distributed in the hope that it will be useful, but
  9. WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with GNU Classpath; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
  15. USA
  16. Linking this library statically or dynamically with other modules is
  17. making a combined work based on this library. Thus, the terms and
  18. conditions of the GNU General Public License cover the whole
  19. combination.
  20. As a special exception, the copyright holders of this library give you
  21. permission to link this library with independent modules to produce an
  22. executable, regardless of the license terms of these independent
  23. modules, and to copy and distribute the resulting executable under
  24. terms of your choice, provided that you also meet, for each linked
  25. independent module, the terms and conditions of the license of that
  26. module. An independent module is a module which is not derived from
  27. or based on this library. If you modify this library, you may extend
  28. this exception to your version of the library, but you are not
  29. obligated to do so. If you do not wish to do so, delete this
  30. exception statement from your version. */
  31. package gnu.javax.crypto.prng;
  32. import gnu.java.security.Registry;
  33. import gnu.java.security.hash.HashFactory;
  34. import gnu.java.security.hash.IMessageDigest;
  35. import gnu.java.security.prng.BasePRNG;
  36. import gnu.java.security.prng.LimitReachedException;
  37. import gnu.java.security.prng.RandomEvent;
  38. import gnu.java.security.prng.RandomEventListener;
  39. import gnu.javax.crypto.cipher.CipherFactory;
  40. import gnu.javax.crypto.cipher.IBlockCipher;
  41. import java.io.IOException;
  42. import java.io.ObjectInputStream;
  43. import java.io.ObjectOutputStream;
  44. import java.io.Serializable;
  45. import java.security.InvalidKeyException;
  46. import java.util.Arrays;
  47. import java.util.Collections;
  48. import java.util.Iterator;
  49. import java.util.Map;
  50. /**
  51. * The Fortuna continuously-seeded pseudo-random number generator. This
  52. * generator is composed of two major pieces: the entropy accumulator and the
  53. * generator function. The former takes in random bits and incorporates them
  54. * into the generator's state. The latter takes this base entropy and generates
  55. * pseudo-random bits from it.
  56. * <p>
  57. * There are some things users of this class <em>must</em> be aware of:
  58. * <dl>
  59. * <dt>Adding Random Data</dt>
  60. * <dd>This class does not do any polling of random sources, but rather
  61. * provides an interface for adding random events. Applications that use this
  62. * code <em>must</em> provide this mechanism. We use this design because an
  63. * application writer who knows the system he is targeting is in a better
  64. * position to judge what random data is available.</dd>
  65. * <dt>Storing the Seed</dt>
  66. * <dd>This class implements {@link Serializable} in such a way that it writes
  67. * a 64 byte seed to the stream, and reads it back again when being
  68. * deserialized. This is the extent of seed file management, however, and those
  69. * using this class are encouraged to think deeply about when, how often, and
  70. * where to store the seed.</dd>
  71. * </dl>
  72. * <p>
  73. * <b>References:</b>
  74. * <ul>
  75. * <li>Niels Ferguson and Bruce Schneier, <i>Practical Cryptography</i>, pp.
  76. * 155--184. Wiley Publishing, Indianapolis. (2003 Niels Ferguson and Bruce
  77. * Schneier). ISBN 0-471-22357-3.</li>
  78. * </ul>
  79. */
  80. public class Fortuna
  81. extends BasePRNG
  82. implements Serializable, RandomEventListener
  83. {
  84. private static final long serialVersionUID = 0xFACADE;
  85. private static final int SEED_FILE_SIZE = 64;
  86. private static final int NUM_POOLS = 32;
  87. private static final int MIN_POOL_SIZE = 64;
  88. private final Generator generator;
  89. private final IMessageDigest[] pools;
  90. private long lastReseed;
  91. private int pool;
  92. private int pool0Count;
  93. private int reseedCount;
  94. public static final String SEED = "gnu.crypto.prng.fortuna.seed";
  95. public Fortuna()
  96. {
  97. super(Registry.FORTUNA_PRNG);
  98. generator = new Generator(CipherFactory.getInstance(Registry.RIJNDAEL_CIPHER),
  99. HashFactory.getInstance(Registry.SHA256_HASH));
  100. pools = new IMessageDigest[NUM_POOLS];
  101. for (int i = 0; i < NUM_POOLS; i++)
  102. pools[i] = HashFactory.getInstance(Registry.SHA256_HASH);
  103. lastReseed = 0;
  104. pool = 0;
  105. pool0Count = 0;
  106. buffer = new byte[256];
  107. }
  108. public void setup(Map attributes)
  109. {
  110. lastReseed = 0;
  111. reseedCount = 0;
  112. pool = 0;
  113. pool0Count = 0;
  114. generator.init(attributes);
  115. try
  116. {
  117. fillBlock();
  118. }
  119. catch (LimitReachedException shouldNotHappen)
  120. {
  121. throw new RuntimeException(shouldNotHappen);
  122. }
  123. }
  124. public void fillBlock() throws LimitReachedException
  125. {
  126. if (pool0Count >= MIN_POOL_SIZE
  127. && System.currentTimeMillis() - lastReseed > 100)
  128. {
  129. reseedCount++;
  130. byte[] seed = new byte[0];
  131. for (int i = 0; i < NUM_POOLS; i++)
  132. if (reseedCount % (1 << i) == 0)
  133. generator.addRandomBytes(pools[i].digest());
  134. lastReseed = System.currentTimeMillis();
  135. pool0Count = 0;
  136. }
  137. generator.nextBytes(buffer);
  138. }
  139. public void addRandomByte(byte b)
  140. {
  141. pools[pool].update(b);
  142. if (pool == 0)
  143. pool0Count++;
  144. pool = (pool + 1) % NUM_POOLS;
  145. }
  146. public void addRandomBytes(byte[] buf, int offset, int length)
  147. {
  148. pools[pool].update(buf, offset, length);
  149. if (pool == 0)
  150. pool0Count += length;
  151. pool = (pool + 1) % NUM_POOLS;
  152. }
  153. public void addRandomEvent(RandomEvent event)
  154. {
  155. if (event.getPoolNumber() < 0 || event.getPoolNumber() >= pools.length)
  156. throw new IllegalArgumentException("pool number out of range: "
  157. + event.getPoolNumber());
  158. pools[event.getPoolNumber()].update(event.getSourceNumber());
  159. pools[event.getPoolNumber()].update((byte) event.getData().length);
  160. pools[event.getPoolNumber()].update(event.getData());
  161. if (event.getPoolNumber() == 0)
  162. pool0Count += event.getData().length;
  163. }
  164. // Reading and writing this object is equivalent to storing and retrieving
  165. // the seed.
  166. private void writeObject(ObjectOutputStream out) throws IOException
  167. {
  168. byte[] seed = new byte[SEED_FILE_SIZE];
  169. try
  170. {
  171. generator.nextBytes(seed);
  172. }
  173. catch (LimitReachedException shouldNeverHappen)
  174. {
  175. throw new Error(shouldNeverHappen);
  176. }
  177. out.write(seed);
  178. }
  179. private void readObject(ObjectInputStream in) throws IOException
  180. {
  181. byte[] seed = new byte[SEED_FILE_SIZE];
  182. in.readFully(seed);
  183. generator.addRandomBytes(seed);
  184. }
  185. /**
  186. * The Fortuna generator function. The generator is a PRNG in its own right;
  187. * Fortuna itself is basically a wrapper around this generator that manages
  188. * reseeding in a secure way.
  189. */
  190. public static class Generator
  191. extends BasePRNG
  192. implements Cloneable
  193. {
  194. private static final int LIMIT = 1 << 20;
  195. private final IBlockCipher cipher;
  196. private final IMessageDigest hash;
  197. private final byte[] counter;
  198. private final byte[] key;
  199. private boolean seeded;
  200. public Generator(final IBlockCipher cipher, final IMessageDigest hash)
  201. {
  202. super(Registry.FORTUNA_GENERATOR_PRNG);
  203. this.cipher = cipher;
  204. this.hash = hash;
  205. counter = new byte[cipher.defaultBlockSize()];
  206. buffer = new byte[cipher.defaultBlockSize()];
  207. int keysize = 0;
  208. for (Iterator it = cipher.keySizes(); it.hasNext();)
  209. {
  210. int ks = ((Integer) it.next()).intValue();
  211. if (ks > keysize)
  212. keysize = ks;
  213. if (keysize >= 32)
  214. break;
  215. }
  216. key = new byte[keysize];
  217. }
  218. public byte nextByte()
  219. {
  220. byte[] b = new byte[1];
  221. nextBytes(b, 0, 1);
  222. return b[0];
  223. }
  224. public void nextBytes(byte[] out, int offset, int length)
  225. {
  226. if (! seeded)
  227. throw new IllegalStateException("generator not seeded");
  228. int count = 0;
  229. do
  230. {
  231. int amount = Math.min(LIMIT, length - count);
  232. try
  233. {
  234. super.nextBytes(out, offset + count, amount);
  235. }
  236. catch (LimitReachedException shouldNeverHappen)
  237. {
  238. throw new Error(shouldNeverHappen);
  239. }
  240. count += amount;
  241. for (int i = 0; i < key.length; i += counter.length)
  242. {
  243. fillBlock();
  244. int l = Math.min(key.length - i, cipher.currentBlockSize());
  245. System.arraycopy(buffer, 0, key, i, l);
  246. }
  247. resetKey();
  248. }
  249. while (count < length);
  250. fillBlock();
  251. ndx = 0;
  252. }
  253. public void addRandomByte(byte b)
  254. {
  255. addRandomBytes(new byte[] { b });
  256. }
  257. public void addRandomBytes(byte[] seed, int offset, int length)
  258. {
  259. hash.update(key);
  260. hash.update(seed, offset, length);
  261. byte[] newkey = hash.digest();
  262. System.arraycopy(newkey, 0, key, 0, Math.min(key.length, newkey.length));
  263. resetKey();
  264. incrementCounter();
  265. seeded = true;
  266. }
  267. public void fillBlock()
  268. {
  269. if (! seeded)
  270. throw new IllegalStateException("generator not seeded");
  271. cipher.encryptBlock(counter, 0, buffer, 0);
  272. incrementCounter();
  273. }
  274. public void setup(Map attributes)
  275. {
  276. seeded = false;
  277. Arrays.fill(key, (byte) 0);
  278. Arrays.fill(counter, (byte) 0);
  279. byte[] seed = (byte[]) attributes.get(SEED);
  280. if (seed != null)
  281. addRandomBytes(seed);
  282. fillBlock();
  283. }
  284. /**
  285. * Resets the cipher's key. This is done after every reseed, which combines
  286. * the old key and the seed, and processes that throigh the hash function.
  287. */
  288. private void resetKey()
  289. {
  290. try
  291. {
  292. cipher.reset();
  293. cipher.init(Collections.singletonMap(IBlockCipher.KEY_MATERIAL, key));
  294. }
  295. // We expect to never get an exception here.
  296. catch (InvalidKeyException ike)
  297. {
  298. throw new Error(ike);
  299. }
  300. catch (IllegalArgumentException iae)
  301. {
  302. throw new Error(iae);
  303. }
  304. }
  305. /**
  306. * Increment `counter' as a sixteen-byte little-endian unsigned integer by
  307. * one.
  308. */
  309. private void incrementCounter()
  310. {
  311. for (int i = 0; i < counter.length; i++)
  312. {
  313. counter[i]++;
  314. if (counter[i] != 0)
  315. break;
  316. }
  317. }
  318. }
  319. }