SecureRandom.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /* SecureRandom.java --- Secure Random class implementation
  2. Copyright (C) 1999, 2001, 2002, 2003, 2005, 2006
  3. Free Software Foundation, Inc.
  4. This file is part of GNU Classpath.
  5. GNU Classpath is free software; you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation; either version 2, or (at your option)
  8. any later version.
  9. GNU Classpath is distributed in the hope that it will be useful, but
  10. WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with GNU Classpath; see the file COPYING. If not, write to the
  15. Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  16. 02110-1301 USA.
  17. Linking this library statically or dynamically with other modules is
  18. making a combined work based on this library. Thus, the terms and
  19. conditions of the GNU General Public License cover the whole
  20. combination.
  21. As a special exception, the copyright holders of this library give you
  22. permission to link this library with independent modules to produce an
  23. executable, regardless of the license terms of these independent
  24. modules, and to copy and distribute the resulting executable under
  25. terms of your choice, provided that you also meet, for each linked
  26. independent module, the terms and conditions of the license of that
  27. module. An independent module is a module which is not derived from
  28. or based on this library. If you modify this library, you may extend
  29. this exception to your version of the library, but you are not
  30. obligated to do so. If you do not wish to do so, delete this
  31. exception statement from your version. */
  32. package java.security;
  33. import gnu.classpath.SystemProperties;
  34. import gnu.java.lang.CPStringBuilder;
  35. import gnu.java.security.Engine;
  36. import gnu.java.security.action.GetSecurityPropertyAction;
  37. import gnu.java.security.jce.prng.SecureRandomAdapter;
  38. import gnu.java.security.jce.prng.Sha160RandomSpi;
  39. import java.io.IOException;
  40. import java.io.InputStream;
  41. import java.lang.reflect.InvocationTargetException;
  42. import java.net.MalformedURLException;
  43. import java.net.URL;
  44. import java.util.Enumeration;
  45. import java.util.Random;
  46. import java.util.logging.Level;
  47. import java.util.logging.Logger;
  48. /**
  49. * An interface to a cryptographically secure pseudo-random number
  50. * generator (PRNG). Random (or at least unguessable) numbers are used
  51. * in all areas of security and cryptography, from the generation of
  52. * keys and initialization vectors to the generation of random padding
  53. * bytes.
  54. *
  55. * @author Mark Benvenuto (ivymccough@worldnet.att.net)
  56. * @author Casey Marshall
  57. */
  58. public class SecureRandom extends Random
  59. {
  60. // Constants and fields.
  61. // ------------------------------------------------------------------------
  62. /** Service name for PRNGs. */
  63. private static final String SECURE_RANDOM = "SecureRandom";
  64. private static final long serialVersionUID = 4940670005562187L;
  65. //Serialized Field
  66. long counter = 0; //Serialized
  67. Provider provider = null;
  68. byte[] randomBytes = null; //Always null
  69. int randomBytesUsed = 0;
  70. SecureRandomSpi secureRandomSpi = null;
  71. byte[] state = null;
  72. private String algorithm;
  73. private boolean isSeeded = false;
  74. // Constructors.
  75. // ------------------------------------------------------------------------
  76. /**
  77. Default constructor for SecureRandom. It constructs a
  78. new SecureRandom by instantating the first SecureRandom
  79. algorithm in the default security provier.
  80. It is not seeded and should be seeded using setSeed or else
  81. on the first call to getnextBytes it will force a seed.
  82. It is maintained for backwards compatibility and programs
  83. should use {@link #getInstance(java.lang.String)}.
  84. */
  85. public SecureRandom()
  86. {
  87. Provider[] p = Security.getProviders();
  88. //Format of Key: SecureRandom.algname
  89. String key;
  90. String classname = null;
  91. int i;
  92. Enumeration e;
  93. for (i = 0; i < p.length; i++)
  94. {
  95. e = p[i].propertyNames();
  96. while (e.hasMoreElements())
  97. {
  98. key = (String) e.nextElement();
  99. if (key.startsWith("SECURERANDOM."))
  100. {
  101. if ((classname = p[i].getProperty(key)) != null)
  102. {
  103. try
  104. {
  105. secureRandomSpi = (SecureRandomSpi) Class.
  106. forName(classname).newInstance();
  107. provider = p[i];
  108. algorithm = key.substring(13); // Minus SecureRandom.
  109. return;
  110. }
  111. catch (ThreadDeath death)
  112. {
  113. throw death;
  114. }
  115. catch (Throwable t)
  116. {
  117. // Ignore.
  118. }
  119. }
  120. }
  121. }
  122. }
  123. // Nothing found. Fall back to SHA1PRNG
  124. secureRandomSpi = new Sha160RandomSpi();
  125. algorithm = "Sha160";
  126. }
  127. /**
  128. A constructor for SecureRandom. It constructs a new
  129. SecureRandom by instantating the first SecureRandom algorithm
  130. in the default security provier.
  131. It is seeded with the passed function and is useful if the user
  132. has access to hardware random device (like a radiation detector).
  133. It is maintained for backwards compatibility and programs
  134. should use getInstance.
  135. @param seed Seed bytes for class
  136. */
  137. public SecureRandom(byte[] seed)
  138. {
  139. this();
  140. setSeed(seed);
  141. }
  142. /**
  143. A constructor for SecureRandom. It constructs a new
  144. SecureRandom using the specified SecureRandomSpi from
  145. the specified security provier.
  146. @param secureRandomSpi A SecureRandomSpi class
  147. @param provider A Provider class
  148. */
  149. protected SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider)
  150. {
  151. this(secureRandomSpi, provider, "unknown");
  152. }
  153. /**
  154. * Private constructor called from the getInstance() method.
  155. */
  156. private SecureRandom(SecureRandomSpi secureRandomSpi, Provider provider,
  157. String algorithm)
  158. {
  159. this.secureRandomSpi = secureRandomSpi;
  160. this.provider = provider;
  161. this.algorithm = algorithm;
  162. }
  163. /**
  164. * Returns an instance of a <code>SecureRandom</code> from the first provider
  165. * that implements it.
  166. *
  167. * @param algorithm The algorithm name.
  168. * @return A new <code>SecureRandom</code> implementing the given algorithm.
  169. * @throws NoSuchAlgorithmException If no installed provider implements the
  170. * given algorithm.
  171. * @throws IllegalArgumentException if <code>algorithm</code> is
  172. * <code>null</code> or is an empty string.
  173. */
  174. public static SecureRandom getInstance(String algorithm)
  175. throws NoSuchAlgorithmException
  176. {
  177. Provider[] p = Security.getProviders();
  178. NoSuchAlgorithmException lastException = null;
  179. for (int i = 0; i < p.length; i++)
  180. try
  181. {
  182. return getInstance(algorithm, p[i]);
  183. }
  184. catch (NoSuchAlgorithmException x)
  185. {
  186. lastException = x;
  187. }
  188. if (lastException != null)
  189. throw lastException;
  190. throw new NoSuchAlgorithmException(algorithm);
  191. }
  192. /**
  193. * Returns an instance of a <code>SecureRandom</code> for the specified
  194. * algorithm from the named provider.
  195. *
  196. * @param algorithm The algorithm name.
  197. * @param provider The provider name.
  198. * @return A new <code>SecureRandom</code> implementing the chosen
  199. * algorithm.
  200. * @throws NoSuchAlgorithmException If the named provider does not implement
  201. * the algorithm, or if the implementation cannot be instantiated.
  202. * @throws NoSuchProviderException If no provider named <code>provider</code>
  203. * is currently installed.
  204. * @throws IllegalArgumentException if either <code>algorithm</code> or
  205. * <code>provider</code> is <code>null</code> or empty.
  206. */
  207. public static SecureRandom getInstance(String algorithm, String provider)
  208. throws NoSuchAlgorithmException, NoSuchProviderException
  209. {
  210. if (provider == null)
  211. throw new IllegalArgumentException("provider MUST NOT be null");
  212. provider = provider.trim();
  213. if (provider.length() == 0)
  214. throw new IllegalArgumentException("provider MUST NOT be empty");
  215. Provider p = Security.getProvider(provider);
  216. if (p == null)
  217. throw new NoSuchProviderException(provider);
  218. return getInstance(algorithm, p);
  219. }
  220. /**
  221. * Returns an instance of a <code>SecureRandom</code> for the specified
  222. * algorithm from the given provider.
  223. *
  224. * @param algorithm The <code>SecureRandom</code> algorithm to create.
  225. * @param provider The provider to use.
  226. * @throws NoSuchAlgorithmException If the algorithm cannot be found, or if
  227. * the class cannot be instantiated.
  228. * @throws IllegalArgumentException if either <code>algorithm</code> or
  229. * <code>provider</code> is <code>null</code>, or if
  230. * <code>algorithm</code> is an empty string.
  231. */
  232. public static SecureRandom getInstance(String algorithm, Provider provider)
  233. throws NoSuchAlgorithmException
  234. {
  235. CPStringBuilder sb = new CPStringBuilder("SecureRandom for algorithm [")
  236. .append(algorithm).append("] from provider[")
  237. .append(provider).append("] could not be created");
  238. Throwable cause;
  239. try
  240. {
  241. Object spi = Engine.getInstance(SECURE_RANDOM, algorithm, provider);
  242. return new SecureRandom((SecureRandomSpi) spi, provider, algorithm);
  243. }
  244. catch (InvocationTargetException x)
  245. {
  246. cause = x.getCause();
  247. if (cause instanceof NoSuchAlgorithmException)
  248. throw (NoSuchAlgorithmException) cause;
  249. if (cause == null)
  250. cause = x;
  251. }
  252. catch (ClassCastException x)
  253. {
  254. cause = x;
  255. }
  256. NoSuchAlgorithmException x = new NoSuchAlgorithmException(sb.toString());
  257. x.initCause(cause);
  258. throw x;
  259. }
  260. /**
  261. Returns the provider being used by the current SecureRandom class.
  262. @return The provider from which this SecureRandom was attained
  263. */
  264. public final Provider getProvider()
  265. {
  266. return provider;
  267. }
  268. /**
  269. * Returns the algorithm name used or "unknown" when the algorithm
  270. * used couldn't be determined (as when constructed by the protected
  271. * 2 argument constructor).
  272. *
  273. * @since 1.5
  274. */
  275. public String getAlgorithm()
  276. {
  277. return algorithm;
  278. }
  279. /**
  280. Seeds the SecureRandom. The class is re-seeded for each call and
  281. each seed builds on the previous seed so as not to weaken security.
  282. @param seed seed bytes to seed with
  283. */
  284. public void setSeed(byte[] seed)
  285. {
  286. secureRandomSpi.engineSetSeed(seed);
  287. isSeeded = true;
  288. }
  289. /**
  290. Seeds the SecureRandom. The class is re-seeded for each call and
  291. each seed builds on the previous seed so as not to weaken security.
  292. @param seed 8 seed bytes to seed with
  293. */
  294. public void setSeed(long seed)
  295. {
  296. // This particular setSeed will be called by Random.Random(), via
  297. // our own constructor, before secureRandomSpi is initialized. In
  298. // this case we can't call a method on secureRandomSpi, and we
  299. // definitely don't want to throw a NullPointerException.
  300. // Therefore we test.
  301. if (secureRandomSpi != null)
  302. {
  303. byte[] tmp = { (byte) (0xff & (seed >> 56)),
  304. (byte) (0xff & (seed >> 48)),
  305. (byte) (0xff & (seed >> 40)),
  306. (byte) (0xff & (seed >> 32)),
  307. (byte) (0xff & (seed >> 24)),
  308. (byte) (0xff & (seed >> 16)),
  309. (byte) (0xff & (seed >> 8)),
  310. (byte) (0xff & seed)
  311. };
  312. secureRandomSpi.engineSetSeed(tmp);
  313. isSeeded = true;
  314. }
  315. }
  316. /**
  317. Generates a user specified number of bytes. This function
  318. is the basis for all the random functions.
  319. @param bytes array to store generated bytes in
  320. */
  321. public void nextBytes(byte[] bytes)
  322. {
  323. if (!isSeeded)
  324. setSeed(getSeed(32));
  325. randomBytesUsed += bytes.length;
  326. counter++;
  327. secureRandomSpi.engineNextBytes(bytes);
  328. }
  329. /**
  330. Generates an integer containing the user specified
  331. number of random bits. It is right justified and padded
  332. with zeros.
  333. @param numBits number of random bits to get, 0 <= numBits <= 32;
  334. @return the random bits
  335. */
  336. protected final int next(int numBits)
  337. {
  338. if (numBits == 0)
  339. return 0;
  340. byte[] tmp = new byte[(numBits + 7) / 8];
  341. this.nextBytes(tmp);
  342. int ret = 0;
  343. for (int i = 0; i < tmp.length; i++)
  344. ret |= (tmp[i] & 0xFF) << (8 * i);
  345. long mask = (1L << numBits) - 1;
  346. return (int) (ret & mask);
  347. }
  348. /**
  349. Returns the given number of seed bytes. This method is
  350. maintained only for backwards capability.
  351. @param numBytes number of seed bytes to get
  352. @return an array containing the seed bytes
  353. */
  354. public static byte[] getSeed(int numBytes)
  355. {
  356. return SecureRandomAdapter.getSeed(numBytes);
  357. }
  358. /**
  359. Returns the specified number of seed bytes.
  360. @param numBytes number of seed bytes to get
  361. @return an array containing the seed bytes
  362. */
  363. public byte[] generateSeed(int numBytes)
  364. {
  365. return secureRandomSpi.engineGenerateSeed(numBytes);
  366. }
  367. }