Microsoft .NET and Powerhell provide access to the RandomNumberGenerator class. This supports the generation of pseudo random numbers for a given size. The output of this is in a byte array, and we will then convert this to hexadecimal, Base64 and also represent as a Big Integer.
Random Number Generation with PowerShell |
Method
Now, let’s implement a random number generator using PowerShell. For this we will define the number of bytes that we need for the random number. With 16 bytes, we generate 128 bits as an output, and 32 bytes give us 256 bits. In the following we create a new random object (rand), and then call the GetBytes() method, and thus put the random number in the r variable:
$rand = [Security.Cryptography.RandomNumberGenerator]::Create() $r = [byte[]]::new($randBytes) $rand.GetBytes($r)
Next, we can convert this into a hex, Base64 format with the conversion methods:
"`nRandom (Hex): "+[System.Convert]::ToHexString($r) "Random (Base64): "+[System.Convert]::ToBase64String($r)
Also, we may want to use the value as an integer. Unfortunately, our integers typically only go up to 32 or 64 bits, so we have to use a Big Integer conversion, and which converts the byte array (r) into a Big Integer:
$val = [Numerics.BigInteger]::new($r) "Random (Integer): "+$val
Coding
The following is the coding:
$randBytes=16 $randBytes = [int]$Args[0] $rand = [Security.Cryptography.RandomNumberGenerator]::Create() $r = [byte[]]::new($randBytes) $rand.GetBytes($r) "`nRandom (Hex): "+[System.Convert]::ToHexString($r) "Random (Base64): "+[System.Convert]::ToBase64String($r) $val = [Numerics.BigInteger]::new($r) "Random (Integer): "+$val
A sample run shows:
Length of random number: 8 Random (Hex): 67B370C27490125B Random (Base64): Z7NwwnSQEls= Random (Integer): 6562466438185005927
and:
Length of random number: 64 Random (Hex): 0FBD3F843D6BD38516108BF3D9A5681E7A9BA4AF90F0C09A113CB9D1B0B206A0B6C4681937AC482D537FBE9CFF2F27B19A600E8411BDF11E738B0DC8655639D9 Random (Base64): D70/hD1r04UWEIvz2aVoHnqbpK+Q8MCaETy50bCyBqC2xGgZN6xILVN/vpz/LyexmmAOhBG98R5ziw3IZVY52Q== Random (Integer): -2030865239134363936904021218898029692616828717316383608591602112785613404281494866684690362332038421629059242092630570104459306442120831119393836167611121