Generating Random Data

The library provides a set of functions to generate unpredictable data, suitable for creating secret keys.

  • On Windows systems, the RtlGenRandom() function is used.
  • On OpenBSD and Bitrig, the arc4random() function is used.
  • On recent FreeBSD and Linux kernels, the getrandom system call is used.
  • On other Unices, the /dev/urandom device is used.
%load_ext sql
%config SqlMagic.feedback=False
%config SqlMagic.displaycon=False
%sql postgresql://postgres@/
%%sql 
CREATE EXTENSION IF NOT EXISTS pgsodium;
[]

randombytes_random()

Returns a random 32-bit signed integer.

%sql select pgsodium.randombytes_random() from generate_series(0, 5);
randombytes_random
-790657505
970732090
934314631
-915187547
-227520694
934389461

randombytes_uniform(upper_bound interger)

Returns a uniformally distributed random number between zero and the upper bound argument.

%sql select pgsodium.randombytes_uniform(10) + 3 from generate_series(0, 5);
?column?
9
9
12
5
3
12

randombytes_buf(buffer_size integer)

Returns a random buffer of bytes the size of the argument.

%sql select encode(pgsodium.randombytes_buf(10), 'hex') from generate_series(0, 5);
encode
6d995ff6597b8caa05a0
5e7aa28d67c37e3c8cea
1e3c8cdc8d5836817947
7dac87837187143884b3
fdd853c4111a624d6d92
656962919682a665596d