001    package edu.harvard.deas.hyperenc.vsat;
002    
003    import java.io.File;
004    import java.io.FileInputStream;
005    
006    public class DevRandomSource extends TrueRandomSource
007    {
008      //Random rand;
009      FileInputStream randomFile;
010    
011      // Make a new file
012      public DevRandomSource()
013      {
014        try{
015        randomFile = new FileInputStream(DevRandomSource.randomDevice());
016        } catch (Exception e) {
017          e.printStackTrace();
018          System.exit(1);
019        }
020      }
021      public DevRandomSource(String source)
022      {
023        try{
024        randomFile = new FileInputStream(source);
025        } catch (Exception e) {
026          e.printStackTrace();
027          System.exit(1);
028        }
029      }
030    
031      // returns the name of a random device if one exists
032      static public String randomDevice() {
033        File test;
034        int i;
035        String s=null;
036        String[] devices= new String[] {"/dev/rng", "/dev/hwrandom",
037                                        "/dev/intel_rng",
038                                        "/dev/urandom", // XXX BAD RNG, TESTING ONLY
039                                        null};
040    
041        for (i=0; i<devices.length; i++) {
042          s=devices[i];
043          if (s==null) break;
044          test=new File(s);
045          if (test.canRead()) break;
046        }
047        return s;
048      }
049    
050      // methods as in RandomSource.  THIS IS NONDETERMINISTIC, but just in case
051      public void getPage(byte [] block, byte [] page)
052      {
053        int offset=0, length=page.length, dataRead=1;
054        // don't need the block
055    
056        try{
057        while (dataRead > 0) {
058          dataRead = randomFile.read(page, offset, length-offset);
059          offset += dataRead;
060        }
061        if (offset != length) {
062          System.out.println("Can't read randomness!");
063          System.exit(1);
064        }
065        } catch (Exception e) {
066          e.printStackTrace();
067          System.exit(1);
068        }
069      }
070    
071      // method as in FileRandomSource
072      public byte[] genRandomness() {
073        byte [] answer=new byte[DATA_LENGTH];
074        getPage((byte []) null, answer);
075        return answer;
076      }
077    }