⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 csprng.java

📁 linux下建立JAVA虚拟机的源码KAFFE
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/* CSPRNG.java -- continuously-seeded pseudo-random number generator.   Copyright (C) 2004, 2006 Free Software Foundation, Inc.This file is a part of GNU Classpath.GNU Classpath is free software; you can redistribute it and/or modifyit under the terms of the GNU General Public License as published bythe Free Software Foundation; either version 2 of the License, or (atyour option) any later version.GNU Classpath is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNUGeneral Public License for more details.You should have received a copy of the GNU General Public Licensealong with GNU Classpath; if not, write to the Free SoftwareFoundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301USALinking this library statically or dynamically with other modules ismaking a combined work based on this library.  Thus, the terms andconditions of the GNU General Public License cover the wholecombination.As a special exception, the copyright holders of this library give youpermission to link this library with independent modules to produce anexecutable, regardless of the license terms of these independentmodules, and to copy and distribute the resulting executable underterms of your choice, provided that you also meet, for each linkedindependent module, the terms and conditions of the license of thatmodule.  An independent module is a module which is not derived fromor based on this library.  If you modify this library, you may extendthis exception to your version of the library, but you are notobligated to do so.  If you do not wish to do so, delete thisexception statement from your version.  */package gnu.javax.crypto.prng;import gnu.java.security.Properties;import gnu.java.security.Registry;import gnu.java.security.hash.HashFactory;import gnu.java.security.hash.IMessageDigest;import gnu.java.security.prng.BasePRNG;import gnu.java.security.prng.EntropySource;import gnu.java.security.prng.IRandom;import gnu.java.security.prng.LimitReachedException;import gnu.java.security.util.SimpleList;import gnu.java.security.util.Util;import gnu.javax.crypto.cipher.CipherFactory;import gnu.javax.crypto.cipher.IBlockCipher;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.io.PrintStream;import java.net.MalformedURLException;import java.net.URL;import java.security.AccessController;import java.security.InvalidKeyException;import java.security.PrivilegedAction;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;import java.util.Iterator;import java.util.LinkedList;import java.util.List;import java.util.Map;import java.util.StringTokenizer;/** * <p>An entropy pool-based pseudo-random number generator based on the PRNG * in Peter Gutmann's cryptlib (<a * href="http://www.cs.auckland.ac.nz/~pgut001/cryptlib/">http://www.cs.auckland.ac.nz/~pgut001/cryptlib/</a>).</p> * * <p>The basic properties of this generator are:</p> * * <ol> * <li>The internal state cannot be determined by knowledge of the input.</li> * <li>It is resistant to bias introduced by specific inputs.</li> * <li>The output does not reveal the state of the generator.</li> * </ol> */public class CSPRNG extends BasePRNG{  // Constants and fields.  // -------------------------------------------------------------------------  private static final boolean DEBUG = false;  private static void debug(String msg)  {    System.err.print(">>> CSPRNG: ");    System.err.println(msg);  }  /**   * Property name for the list of files to read for random values. The   * mapped value is a list with the following values:   *   * <ol>   * <li>A {@link Double}, indicating the suggested <i>quality</i> of this   * source. This value must be between 0 and 100.</li>   * <li>An {@link Integer}, indicating the number of bytes to skip in the file   * before reading bytes. This can be any nonnegative value.</li>   * <li>An {@link Integer}, indicating the number of bytes to read.</li>   * <li>A {@link String}, indicating the path to the file.</li>   * </ol>   *   * @see gnu.crypto.util.SimpleList   */  public static final String FILE_SOURCES = "gnu.crypto.prng.pool.files";  /**   * Property name for the list of URLs to poll for random values. The   * mapped value is a list formatted similarly as in {@link #FILE_SOURCES},   * but the fourth member is a {@link URL}.   */  public static final String URL_SOURCES = "gnu.crypto.prng.pool.urls";  /**   * Property name for the list of programs to execute, and use the output   * as new random bytes. The mapped property is formatted similarly an in   * {@link #FILE_SOURCES} and {@link #URL_SOURCES}, except the fourth   * member is a {@link String} of the program to execute.   */  public static final String PROGRAM_SOURCES = "gnu.crypto.prng.pool.programs";  /**   * Property name for a list of other sources of entropy. The mapped   * value must be a list of {@link EntropySource} objects.   */  public static final String OTHER_SOURCES = "gnu.crypto.prng.pool.other";  /**   * Property name for whether or not to wait for the slow poll to   * complete, passed as a {@link Boolean}. The default value is true.   */  public static final String BLOCKING = "gnu.crypto.prng.pool.blocking";  private static final String FILES = "gnu.crypto.csprng.file.";  private static final String URLS = "gnu.crypto.csprng.url.";  private static final String PROGS = "gnu.crypto.csprng.program.";  private static final String OTHER = "gnu.crypto.csprng.other.";  private static final String BLOCK = "gnu.crypto.csprng.blocking";  private static final int POOL_SIZE = 256;  private static final int ALLOC_SIZE = 260;  private static final int OUTPUT_SIZE = POOL_SIZE / 2;  private static final int X917_POOL_SIZE = 16;  private static final String HASH_FUNCTION = Registry.SHA160_HASH;  private static final String CIPHER = Registry.AES_CIPHER;  private static final int MIX_COUNT = 10;  private static final int X917_LIFETIME = 8192;  // FIXME this should be configurable.  private static final int SPINNER_COUNT = 8;  /**   * The spinner group singleton. We use this to add a small amount of   * randomness (in addition to the current time and the amount of   * free memory) based on the randomness (if any) present due to   * system load and thread scheduling.   */  private static final Spinner[] SPINNERS = new Spinner[SPINNER_COUNT];  private static final Thread[] SPINNER_THREADS = new Thread[SPINNER_COUNT];  static    {      for (int i = 0; i < SPINNER_COUNT; i++)        {          SPINNER_THREADS[i] = new Thread(SPINNERS[i] = new Spinner(),                                          "spinner-" + i);          SPINNER_THREADS[i].setDaemon(true);          SPINNER_THREADS[i].setPriority(Thread.MIN_PRIORITY);          SPINNER_THREADS[i].start();        }    }  /**   * The message digest (SHA-1) used in the mixing function.   */  private final IMessageDigest hash;  /**   * The cipher (AES) used in the output masking function.   */  private final IBlockCipher cipher;  /**   * The number of times the pool has been mixed.   */  private int mixCount;  /**   * The entropy pool.   */  private final byte[] pool;  /**   * The quality of the random pool (percentage).   */  private double quality;  /**   * The index of the next byte in the entropy pool.   */  private int index;  /**   * The pool for the X9.17-like generator.   */  private byte[] x917pool;  /**   * The number of iterations of the X9.17-like generators.   */  private int x917count;  /**   * Whether or not the X9.17-like generator is initialized.   */  private boolean x917init;  /**   * The list of file soures.   */  private final List files;  /**   * The list of URL sources.   */  private final List urls;  /**   * The list of program sources.   */  private final List progs;  /**   * The list of other sources.   */  private final List other;  /**   * Whether or not to wait for the slow poll to complete.   */  private boolean blocking;  /**   * The thread that polls for random data.   */  private Poller poller;  private Thread pollerThread;  // Constructor.  // -------------------------------------------------------------------------  public CSPRNG()  {    super("CSPRNG");    pool = new byte[ALLOC_SIZE];    x917pool = new byte[X917_POOL_SIZE];    x917count = 0;    x917init = false;    quality = 0.0;    hash = HashFactory.getInstance(HASH_FUNCTION);    cipher = CipherFactory.getInstance(CIPHER);    buffer = new byte[OUTPUT_SIZE];    ndx = 0;    initialised = false;    files = new LinkedList();    urls = new LinkedList();    progs = new LinkedList();    other = new LinkedList();  }  // Class methods.  // -------------------------------------------------------------------------  /**   * <p>Create and initialize a CSPRNG instance with the "system" parameters;   * the files, URLs, programs, and {@link EntropySource} sources used by   * the instance are derived from properties set in the system {@link   * Properties}.</p>   *   * <p>All properties are of the from <i>name</i>.</i>N</i>, where <i>name</i>   * is the name of the source, and <i>N</i> is an integer (staring at 1) that   * indicates the preference number for that source.</p>   *   * <p>The following vales for <i>name</i> are used here:</p>   *   * <dl>   * <dt>gnu.crypto.csprng.file</dt>   * <dd><p>These properties are file sources, passed as the {@link #FILE_SOURCES}   * parameter of the instance. The property value is a 4-tuple formatted as:</p>   *   * <blockquote><i>quality</i> ; <i>offset</i> ; <i>count</i> ; <i>path</i></blockquote>   *   * <p>The parameters are mapped to the parameters defined for {@link   * #FILE_SOURCES}. Leading or trailing spaces on any item are trimmed   * off.</p></dd>   *   * <dt>gnu.crypto.csprng.url</dt>   * <dd><p>These properties are URL sources, passed as the {@link #URL_SOURCES}   * parameter of the instance. The property is formatted the same way as file   * sources, but the <i>path</i> argument must be a valid URL.</p></dd>   *   * <dt>gnu.crypto.csprng.program</dt>   * <dd><p>These properties are program sources, passed as the {@link   * #PROGRAM_SOURCES} parameter of the instance. This property is formatted   * the same way as file and URL sources, but the last argument is a program   * and its arguments.</p></dd>   *   * <dt>gnu.crypto.cspring.other</dt>   * <dd><p>These properties are other sources, passed as the {@link OTHER_SOURCES}   * parameter of the instance. The property value must be the full name   * of a class that implements the {@link EntropySource} interface and has a   * public no-argument constructor.</p></dd>   * </dl>   *   * <p>Finally, a boolean property "gnu.crypto.csprng.blocking" can be set to   * the desired value of {@link #BLOCKING}.</p>   *   * <p>An example of valid properties would be:</p>   *   * <pre>   * gnu.crypto.csprng.blocking=true   *   * gnu.crypto.csprng.file.1=75.0;0;256;/dev/random   * gnu.crypto.csprng.file.2=10.0;0;100;/home/user/file   *   * gnu.crypto.csprng.url.1=5.0;0;256;http://www.random.org/cgi-bin/randbyte?nbytes=256   * gnu.crypto.csprng.url.2=0;256;256;http://slashdot.org/   *   * gnu.crypto.csprng.program.1=0.5;0;10;last -n 50   * gnu.crypto.csprng.program.2=0.5;0;10;tcpdump -c 5   *   * gnu.crypto.csprng.other.1=foo.bar.MyEntropySource   * gnu.crypto.csprng.other.2=com.company.OtherEntropySource   * </pre>   */  public static IRandom getSystemInstance() throws ClassNotFoundException,      MalformedURLException, NumberFormatException  {    CSPRNG instance = new CSPRNG();    HashMap attrib = new HashMap();    attrib.put(BLOCKING, new Boolean(getProperty(BLOCK)));    String s = null;    // Get each file source "gnu.crypto.csprng.file.N".    List l = new LinkedList();    for (int i = 0; (s = getProperty(FILES + i)) != null; i++)      {        try          {            l.add(parseString(s.trim()));          }        catch (NumberFormatException nfe)          {          }      }    attrib.put(FILE_SOURCES, l);    l = new LinkedList();    for (int i = 0; (s = getProperty(URLS + i)) != null; i++)      {        try          {            l.add(parseURL(s.trim()));          }        catch (NumberFormatException nfe)          {          }        catch (MalformedURLException mue)          {          }      }    attrib.put(URL_SOURCES, l);    l = new LinkedList();    for (int i = 0; (s = getProperty(PROGS + i)) != null; i++)      {        try          {            l.add(parseString(s.trim()));          }        catch (NumberFormatException nfe)          {          }      }    attrib.put(PROGRAM_SOURCES, l);    l = new LinkedList();    for (int i = 0; (s = getProperty(OTHER + i)) != null; i++)      {        try          {            Class c = Class.forName(s.trim());            l.add(c.newInstance());          }        catch (ClassNotFoundException cnfe)          {          }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -