Dev random

From Free Pascal wiki
Jump to: navigation, search

Deutsch (de) English (en) français (fr)

Summary

/dev/random and /dev/urandom are two Unix and *nix based devices that process memory, disc, network dumps from the kernel (as well as cryptography hardware, if present and enabled) to generate (pseudo)random numbers.

The difference between /dev/random and /dev/urandom is whether the device is "blocking" or "non blocking":

  • when /dev/random is giving random data, it will wait until it has something that is random enough to give us before returning the data.
  • /dev/urandom does not stop when it runs out of random data, and will also return data that is less random. This way we will not need to wait until any type of activity will occur, but randomness is reduced.

Using /dev/random or /dev/urandom allows us to use a "random" like seed (randseed) for performing "random" tasks with the random function.

Examples

In order to make Free Pascal work with /dev/random and /dev/random we can write the following code:

procedure RandomSeed;
var
  f : file of integer;
  i : integer;
 
begin
  i        := 0;
  filemode := 0;
  AssignFile(f, '/dev/urandom'); 
  reset (f,1);
  read (f,i);
  CloseFile (f);
  RandSeed := i;
end;

Explanation

Like almost everything else in *nix like OSes, everything is a file! So, we access urandom as a file and we read only one integer at a time.

Then, we place the data we made as RandSeed (the seed number that the function random uses). And that's it, we have a random seeder for "random" usage.

note

Note that if you need multiple random values it is possible to read multiple random values at once by doing a blockread.
Here's an example:

program randomblock;
{$mode objfpc}
var
  f : file of dword;
  r : packed array[0..5] of dword;
  i : dword;
begin
  AssignFile(f, '/dev/urandom'); 
  reset (f);
  blockread (f,r,6);
  CloseFile (f);
  for i in r do
    writeln(i);
end.

See also