Random number generator (device): Difference between revisions
added RPL
(added RPL) |
|||
(11 intermediate revisions by 9 users not shown) | |||
Line 19:
The syscall number on AArch64 is 278.
<
.equ SVC_WRITE, 64
.equ SVC_GETRANDOM, 278
Line 87:
_exit:
mov x8, #SVC_EXIT
svc #0</
=={{header|Ada}}==
random.adb:
<
with Ada.Text_IO;
procedure Random is
Line 103:
Ada.Streams.Stream_IO.Close (Random_File);
Ada.Text_IO.Put_Line ("Number:" & Integer'Image (Number));
end Random;</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
Line 315:
iMagicNumber: .int 0xCCCCCCCD
</syntaxhighlight>
=={{header|Batch File}}==
The dynamic environmental variable <code>%random%</code> contains a number between 0 and 32767.
<
@echo %random%
</syntaxhighlight>
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
Requires Windows XP or later.
<
PRINT ~random%</
=={{header|C}}==
It works on systems having /dev/urandom, like [[GNU]]/[[Linux]].
<
#include <stdlib.h>
Line 356:
printf("%lu\n", v);
return 0;
}</
==={{libheader|BSD libc}}===
[http://www.openbsd.org/cgi-bin/man.cgi?query=arc4random&apropos=0&sektion=3&manpath=OpenBSD+Current&arch=i386&format=html arc4random()] appeared in [[OpenBSD]] 2.1 and has spread to many [[BSD]] systems. This function runs an ARC4 random number generator that takes entropy from a kernel device. (This kernel device is sysctl kern.arandom in OpenBSD, or /dev/urandom in some other systems.)
<
#include <stdlib.h> /* arc4random */
#include <stdio.h> /* printf */
Line 370:
printf("%" PRIu32 "\n", arc4random());
return 0;
}</
==={{libheader|OpenSSL}}===
OpenSSL can generate random numbers. The default generator uses SHA1. For [[Unix]] systems, OpenSSL will gather entropy by reading a kernel device like /dev/urandom, or by using [http://egd.sourceforge.net/ EGD, the Entropy Gathering Daemon]. For other systems, OpenSSL might use a different source of entropy.
<
#include <stdio.h>
Line 392:
printf("%" PRIu32 "\n", v);
return 0;
}</
=== Windows ===
{{works with|MinGW}}
<
#include <windows.h>
#include <wincrypt.h> /* CryptAcquireContext, CryptGenRandom */
Line 419:
CryptReleaseContext(p, 0);
return 0;
}</
=== debian/linux made from scratch ===
{{works with|GCC}}
<syntaxhighlight lang="c">
#include <stdio.h>
#include <stdlib.h>
Line 449:
Out of 114 tests, rest PASSED
Obviously, it changes per run :)
*/
Line 504 ⟶ 506:
}
</syntaxhighlight>
JPD 2021/07/07
Line 518 ⟶ 521:
See the C++ section on [[Random_number_generator_(included)#C.2B.2B|Random number generator (included)]] for the list of pseudo-random number engines available.
{{works with|C++11}}
<
#include <random>
Line 527 ⟶ 530:
std::cout << "Random Number: " << dist(rd) << std::endl;
}</
=={{header|C sharp}}==
<
using System.Security.Cryptography;
Line 543 ⟶ 546:
return result;
}</
Park-Miller random number generator
<
const long m = 2147483647L;
const long a = 48271L;
Line 572 ⟶ 575:
arr[i] = gen();
}
}</
=={{header|ChucK}}==
<
=={{header|Common Lisp}}==
<
(with-open-file (s "/dev/random" :element-type '(unsigned-byte 32))
(read-byte s)))</
=={{header|D}}==
Example of MersenneTwisterEngine for generating uniformly-distributed 32-bit numbers with a period of 2 to the power of 19937.
<syntaxhighlight lang="d">
import std.stdio;
import std.random;
Line 595 ⟶ 598:
writeln(n);
}
</syntaxhighlight>
{{out}}
Line 608 ⟶ 611:
{{libheader| System.SysUtils}}
{{libheader| Winapi.WinCrypt}}[[https://github.com/magicxor/WinCryptographyAPIs]]
<syntaxhighlight lang="delphi">
program Random_number_generator;
Line 644 ⟶ 647:
Writeln(Random);
Readln;
end.</
{{out}}
<pre>6246170830
Line 660 ⟶ 663:
=={{header|EchoLisp}}==
No random device provided by the host (browser). But we can use the system timer to get a physical input.
<
(random-seed "simon")
(random (expt 2 32)) → 2275215386
Line 671 ⟶ 674:
(random-seed (current-time-milliseconds ))
(random (expt 2 32)) → 1322611152
</syntaxhighlight>
=={{header|Factor}}==
Factor has good support for switching between different random number generators. <code>with-system-random</code> is a combinator that encapsulates the task of using a system RNG (/dev/random in the case of GNU/Linux).
<
[ random-32 ] with-system-random .</
=={{header|Forth}}==
<
: randoms ( n -- )
Line 687 ⟶ 690:
rnd @ .
loop
close-file throw ;</
=={{header|Fortran}}==
Using system /dev/urandom in [[GNU]]/[[Linux]].
<
!-----------------------------------------------------------------------
! Test Linux urandom in Fortran
Line 717 ⟶ 720:
end program urandom_test
</syntaxhighlight>
Here's an example of the use of the latter:
Line 725 ⟶ 728:
However, in practice, there is little need for this as specifying a second parameter of 5 to FB's Randomize statement produces cryptographically strong pseudo-random numbers using either the Win32 Crypto API or the /dev/urandom device under Linux.
<
Randomize , 5
Line 734 ⟶ 737:
Next
Sleep</
=={{header|FutureBasic}}==
FB offers a variety of ways to generate random numbers of varying degrees of distribution and randomness accuracy. In addition to its native rnd() function which returns random integers from 1 and higher, it can also access any C library function, i.e, rand(), arc4random, arc4random_uniform, as well as random number generators in Apple's GameplayKit library. Here are a few examples:
<syntaxhighlight lang="freebasic">
include "Tlbx GameplayKit.incl"
local fn RandomBigInteger( digits as UInt64 ) as UInt64
end fn = fn GKLinearCongruentialRandomSourceSeed( fn GKLinearCongruentialRandomSourceInit ) mod digits
local fn RandomIntegerInRange( min as UInt64, max as UInt64 ) as UInt64
UInt64 rndIntInRange = fn RandomBigInt( max - min + 1 ) + min - 1
end fn = rndIntInRange
local fn ArcRandomIntegerInRage( min as long, max as long ) as long
long i
cln i = (arc4random()%(max-min+1))+min;
end fn = fn floor(i)
// Returns double in range of 0.0 to 50.0
double r
cln r = (((double)arc4random()/0x100000000)*50);
randomInteger = rnd(expr%)
</syntaxhighlight>
=={{header|GlovePIE}}==
<
=={{header|Go}}==
In the Go library is crypto/rand, a source specified to use dev/urandom on Unix-like systems and the CryptGenRandom API on Windows. Also implemented here is a source using dev/random, if you really want it. On my system it would print a few numbers then hang until I moved the mouse or pressed some keys on the keyboard.
<
import (
Line 774 ⟶ 803:
}
fmt.Println()
}</
=={{header|Groovy}}==
Based, necessarily, on Java solution:
<
Test:
<
{{out}}
Line 793 ⟶ 822:
{{libheader|Entropy}}
{{Works with|GHC|7.4.1}}
<
import System.Entropy
Line 801 ⟶ 830:
main = do
bytes <- getEntropy 4
print (runGet getWord32be $ B.fromChunks [bytes])</
=={{header|Icon}} and {{header|Unicon}}==
Line 807 ⟶ 836:
The following is Unicon-specific but trivially converted into Icon.
<
n := integer(A[1])|5
every !n do write(rand(4))
Line 818 ⟶ 847:
close(f)
return x
end</
Sample runs:
Line 834 ⟶ 863:
Untested:
<
Fallback:
<
Note: this assumes that J is running on linux.
=={{header|Java}}==
<
public class RandomExample {
Line 851 ⟶ 880:
System.out.println(rng.nextInt());
}
}</
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE sysrand32 ==
"/dev/urandom" "r" fopen dup 4 fread swap fclose unswons [swap 256 * +] fold.</syntaxhighlight>
=={{header|jq}}==
jq does not provide direct access to /dev/urandom
We consider two cases: uniform distribution on the interval [0,1] and on the set of non-negative integers less than a given N.
===Uniform distribution on an interval===
We assume the availability of `od`, `tr`, and `fold`, and illustrate how to produce an indefinitely long stream of pseudo-random numbers that are approximately uniformly distributed in the range [0,1].
Assuming the jq program shown below is in a file named uniform.jq, the command-line invocation would be:
<pre>od -t x -An /dev/urandom | tr -d " " | fold -w 8 | jq -R -f uniform.jq</pre>
<
def hex2integer:
explode
Line 869 ⟶ 906:
| .[1];
select(length>0) | hex2integer / pow(16;length)</
Notice that the program automatically adjusts the precision based on the length of the hexadecimal numbers presented. Since jq uses IEEE 754 64-bit arithmetic, specifying a larger value to `fold`, such as 10, will produce more precise results.
===Uniform distribution on a range of integers===
<syntaxhighlight lang="sh">< /dev/random tr -cd '0-9' | fold -w 1 | jq -Mn '
# Output: a PRN in range(0;$n) where $n is .
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
100 | prn
'</syntaxhighlight>
=={{header|Julia}}==
{{works with|Linux}}
<syntaxhighlight lang="julia">
const rdev = "/dev/random"
rstream = try
Line 891 ⟶ 943:
println("The hardware random number stream, ", rdev, ", was unavailable.")
end
</syntaxhighlight>
{{out}}
Line 899 ⟶ 951:
=={{header|Kotlin}}==
<
import java.security.SecureRandom
Line 910 ⟶ 962:
rng.setSeed(newSeed) // reseed using the previous 2 random numbers
println(rng.nextInt()) // get random 32-bit number and print it
}</
=={{header|Lasso}}==
<
{{out}}
<pre>723217350</pre>
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module checkit {
Declare random1 lib "advapi32.SystemFunction036" {long lpbuffer, long length}
Line 929 ⟶ 981:
}
checkit
</syntaxhighlight>
<syntaxhighlight lang="m2000 interpreter">
Function Random2 {
Declare CryptAcquireContext Lib "advapi32.CryptAcquireContextW" {long ByRefhProv, pszContainer$,pszProvider$, long dwProvType, long dwFlags}
Line 947 ⟶ 999:
}
Print Random2()
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">rand32[] := RandomInteger[{-2^31, 2^31 - 1}]</syntaxhighlight>
Example: create array of 10 rand32 numbers
<
{{out}}
<pre>{355587317, -869860319, -91421859, 1605907693, 101463390, 891823090,
-531713717, -1038608428, 1717313407, 674189312}</pre>
=={{header|Mercury}}==
For versions of Mercury greater than 20.06, the standard library module <tt>random.system_rng</tt> provides access to a platform specific random data source.<br />
Generates unsigned 32-bit integers.
<syntaxhighlight lang="mercury">:- module random_number_device.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module maybe, random, random.system_rng, require.
main(!IO) :-
open_system_rng(MaybeRNG, !IO),
(
MaybeRNG = ok(RNG),
random.generate_uint32(RNG, U32, !IO),
io.print_line(U32, !IO),
close_system_rng(RNG, !IO)
;
MaybeRNG = error(ErrorMsg),
io.stderr_stream(Stderr, !IO),
io.print_line(Stderr, ErrorMsg, !IO),
io.set_exit_status(1, !IO)
).</syntaxhighlight>
=={{header|NetRexx}}==
{{Works with|Mac OS X}} and probably other UNIX systems that provide <tt>/dev/random</tt> or <tt>/dev/urandom</tt> random data source devices.<br />
<
options replace format comments java crossref savelog symbols binary
Line 993 ⟶ 1,071:
for ((i=0; i<10; ++i)); do java <program_name>; done # Shell loop to run the command 10 times
*/
</syntaxhighlight>
{{out}}
<pre>
Line 1,011 ⟶ 1,089:
=={{header|Nim}}==
<
var r: int32
discard f.readBuffer(addr r, 4)
close(f)
echo r</
=={{header|OCaml}}==
Line 1,021 ⟶ 1,099:
OCaml's default integers are 31 bits on 32 bits architectures:
<
let i1 = int_of_char (input_char ic)
and i2 = int_of_char (input_char ic)
Line 1,033 ⟶ 1,111:
close_in ic;
Printf.printf "%d\n" ri31;
;;</
but if we really want 32 bits integers there is a module for this:
<
let i1 = Int32.of_int (int_of_char (input_char ic))
and i2 = Int32.of_int (int_of_char (input_char ic))
Line 1,052 ⟶ 1,130:
close_in ic;
Printf.printf "%ld\n" ri32;
;;</
=={{header|PARI/GP}}==
It works on systems having /dev/urandom and Linux.
<
The code above creates a new function rnd() which returns cryptographically strong integers with max. 10 random digits from /dev/urandom. rnd(n) returns integer with max. n random digits. No leading zeros.
Line 1,069 ⟶ 1,147:
=={{header|Pascal}}==
This works with FreePascal on "unixoids":
<
var
byteFile: file of byte;
Line 1,080 ⟶ 1,158:
writeln('The random byte is: ', randomByte);
end.
</syntaxhighlight>
{{out}}
<pre>
Line 1,091 ⟶ 1,169:
=={{header|Perl}}==
Typically one would use a module as they will work on UNIX, Win32, and other O/S's. Crypt::Random::Seed, for instance, will use Win32 sources, EGD/PRNGD, /dev/u?random, or if none of those exist for some reason, a userspace entropy method.
<
my $source = Crypt::Random::Seed->new( NonBlocking => 1 ); # Allow non-blocking sources like /dev/urandom
print "$_\n" for $source->random_values(10); # A method returning an array of 32-bit values</
or (similar but many more dependencies):
<
print unpack('L*',get_weak(4)), "\n" for 1..10;</
Or we can read values from /dev/urandom ourselves:
<
my $device = '/dev/urandom';
open my $in, "<:raw", $device # :raw because it's not unicode string
Line 1,108 ⟶ 1,186:
}
print "$_\n" for read_random(10);</
Whether /dev/urandom is good enough for cryptographic work is debated, though on most UNIX systems it is at least as good as the Win32 Crypto API.
Line 1,120 ⟶ 1,198:
For completeness, I have shown how to convert the signed result to an unsigned one.
<!--<
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #000080;font-style:italic;">-- 1=failure, 0=success</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">rint</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span> <span style="color: #000080;font-style:italic;">-- random 32-bit int</span>
Line 1,176 ⟶ 1,254:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
A linux-only solution:
<!--<
<span style="color: #004080;">integer</span> <span style="color: #000000;">fn</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">open</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"/dev/urandom"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"rb"</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">fn</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">then</span>
Line 1,191 ⟶ 1,269:
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">bytes_to_int</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">signed</span><span style="color: #0000FF;">:=</span><span style="color: #004600;">false</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<!--</
=={{header|PicoLisp}}==
<
-> 2917110327</
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function Get-RandomInteger
{
Line 1,230 ⟶ 1,308:
}
}
</syntaxhighlight>
<syntaxhighlight lang="powershell">
4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {$_} -Column 6 -Force
</syntaxhighlight>
{{Out}}
<pre>
Line 1,239 ⟶ 1,317:
</pre>
As hexadecimal:
<syntaxhighlight lang="powershell">
4,8,16,32,64,128 | Get-RandomInteger | Format-Wide {"0x{0:X}" -f $_} -Column 6 -Force
</syntaxhighlight>
{{Out}}
<pre>
Line 1,249 ⟶ 1,327:
=={{header|ProDOS}}==
Uses math module:
<syntaxhighlight lang
=={{header|PureBasic}}==
PureBasic has the source for the random data is the "/dev/urandom" device on Linux or Mac OSX and the "Microsoft Cryptography API" on Windows.
<
MyRandom = CryptRandom(#MAXLONG)
CloseCryptRandom()
EndIf</
=={{header|Python}}==
<
rand = random.SystemRandom()
rand.randint(1,10)</
=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
;; Assuming a device to provide random bits:
(call-with-input-file* "/dev/random"
(λ(i) (integer-bytes->integer (read-bytes 4 i) #f)))
</syntaxhighlight>
=={{header|Raku}}==
Line 1,277 ⟶ 1,355:
A lazy list of random numbers:
<syntaxhighlight lang="raku"
my $UR = open("/dev/urandom", :bin) orelse .die;
my @random-spigot = $UR.read(1024).unpack("L*") ... *;
.say for @random-spigot[^10];</
{{out}}
<pre>1431009271
Line 1,300 ⟶ 1,378:
Note: the REXX '''random''' BIF has a maximum range
of 100,000.
<
numeric digits 10 /*ensure REXX has enough decimal digits*/
_=2**16 /*a handy─dandy constant to have around*/
r#= random(0, _-1) * _ + random(0, _-1) /*generate an unsigned 32-bit random #.*/
say r# /*stick a fork in it, we're all done. */</
{{out}}
<pre>
Line 1,312 ⟶ 1,390:
===version 2===
This program generates a random 4 byte character string in the range '00000000'x to 'ffffffff'x
<
rite=0
lo=hex(left)hex(rite)
Line 1,325 ⟶ 1,403:
Say 'high ' c2x(hi)
Exit
hex: Return d2c(arg(1),2)</
{{out}}
<pre>low 00000000
Line 1,332 ⟶ 1,410:
=={{header|Ring}}==
<
nr = 10
for i = 1 to nr
see random(i) + nl
next
</syntaxhighlight>
=={{header|RPL}}==
RAND 2 32 ^ * FLOOR
=={{header|Ruby}}==
Ruby 1.8.7 introduces the 'securerandom' library. For [[MRI]] users, this library tries to get random numbers by loading OpenSSL, or opening /dev/urandom, or calling CryptGenRandom.
<
SecureRandom.random_number(1 << 32)
#or specifying SecureRandom as the desired RNG:
p (1..10).to_a.sample(3, random: SecureRandom) # =>[1, 4, 5]
</syntaxhighlight>
=={{header|Rust}}==
<code>rand</code> used to be part of Rust standard library but it was extracted as a 'crate' (https://crates.io/crates/rand). <code>OsRng</code> uses the appropriate device for many platforms including Unix, Windows, BSD, and iOS (listed [https://docs.rs/rand/0.4/rand/os/struct.OsRng.html here]). Other methods like <code>RDRAND</code> can be found in other crates (https://crates.io/crates/rdrand).
<
use rand::{OsRng, Rng};
Line 1,365 ⟶ 1,446:
let rand_num: u32 = rng.gen();
println!("{}", rand_num);
}</
=={{header|Scala}}==
<
object RandomExample extends App {
Line 1,376 ⟶ 1,457:
println(this.nextInt()) // get random 32-bit number and print it
}
}</
=={{header|Sidef}}==
<
device.open('<:raw', \var fh, \var err) ->
|| die "Can't open `#{device}': #{err}"
fh.sysread(\var noise, 4)
'L'.unpack(noise)
}
say urandom()
=={{header|Standard ML}}==
{{Works with|Unix}}
<
let
val strm = BinIO.openIn "/dev/urandom"
Line 1,400 ⟶ 1,481:
end
val () = print (LargeWord.fmt StringCvt.DEC (sysRand32 ()) ^ "\n")</
=={{header|Tcl}}==
<
# Allow override of device name
Line 1,411 ⟶ 1,492:
close $f
return $x
}</
Usage:
<
636131349</
=={{header|UNIX Shell}}==
<
=={{header|Wee Basic}}==
Due to how the code works, any key has to be entered to generate the random number.
<
let number=1
print 1 "Press any key to generate a random number from 1 to 10.
Line 1,433 ⟶ 1,514:
wend
print 1 number
end</
=={{header|Wren}}==
<
File.open("/dev/urandom") { |file|
Line 1,442 ⟶ 1,523:
var n = b[0] | b[1] << 8 | b[2] << 16 | b[3] << 24
System.print(n)
}</
{{out}}
Line 1,452 ⟶ 1,533:
=={{header|X86 Assembly}}==
Processors supporting the new RDRAND feature can generate a random 32-bit integer in two instructions:
<
jnc L</
RDRAND reads the CPU's cryptographically-secure hardware random number generator. The loop is needed because RDRAND can occasionally fail to retrieve a value — it sets the carry flag to indicate whether it succeeded.
Line 1,463 ⟶ 1,544:
limited to 31 bits.
<
int R;
R:= Ran($7FFF_FFFF)</
=={{header|zkl}}==
{{trans|C}}
Linux:
<
fin,buf:=File(RANDOM_PATH,"r"), fin.read(4);
fin.close(); // GC would also close the file
println(buf.toBigEndian(0,4)); // 4 bytes @ offset 0</
{{out}}
<pre>
|