Advertisement
WarPie90

True-ish random number generation.

Jan 19th, 2025 (edited)
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 2.04 KB | None | 0 0
  1. (*
  2.   Pseudo-random number generation enhanced with an external entropy source (webcam image).
  3.   It does not meet the strictest criteria for true randomness, but it comes as close
  4.   as we easily can without specialized hardware. Further more entropy image is
  5.   not updated fast enough to truly be unpredictable within a 1 minute window,
  6.   a better source could be found, and the camera may not be able to deal well with
  7.   night-time, which means entropy may reduce.
  8.  
  9.   But on a longer timeframe this can not be predicted, nor replicated,
  10.   even though short sequences within it can be individually solved for
  11.   assuming enough data is collected.
  12. *)
  13.  
  14. var entropyUpdateTimer:Double;
  15. function TrueRandom(x,y: Int32): Int32;
  16. var
  17.   trueRnd: UInt64;
  18.   rnd: TImage;
  19.   r,t:single;
  20.   data: string;
  21. begin
  22.   // grab random world data, in our case an image is the source of entropy
  23.   // however this image only updates every 1 minute at the source
  24.   // so that makes 1 minute sequences of this deterministic.
  25.   // For optimal entropy find a live source with *a lot* of data.
  26.   // weather patterns are likely a good source (if can be found online).
  27.   if PerformanceTimer() > entropyUpdateTimer then
  28.   begin
  29.     HTTPClient.GetFile('https://kamera.atlas.vegvesen.no/api/images/0329003_1', 'rndgen.jpg');
  30.  
  31.     //65 seconds as image updates once every minute.
  32.     entropyUpdateTimer := PerformanceTimer() + 1000*65;
  33.   end;
  34.  
  35.   // load real world data as simi-undeterministic spice to pseudo random number generation
  36.   rnd := TImage.Create('rndgen.jpg');
  37.   data := HashData(EHashAlgo.SHA256, rnd.data, rnd.Width*rnd.Height*4);
  38.   SetLength(data, 16); // we only care about the first 64 bits.
  39.   rnd.Free();
  40.  
  41.   //a true-ish random number in the range 0..High(UInt64)
  42.   trueRnd := StrToInt64('$'+data);
  43.  
  44.   //a true-ish random number in the incomplete range 0..1
  45.   t := trueRnd / High(UInt64);
  46.  
  47.   r := x + t * 1/t * y * random();
  48.   Result := Round(r);
  49. end;
  50.  
  51.  
  52. var
  53.   myIds := [543,11,99,664,14];
  54. begin
  55.   for 0 to 1000 do
  56.     Writeln TrueRandom(0,1000);
  57. end;
  58.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement