Created
July 15, 2021 14:30
-
-
Save pcrockett-pathway/51f65780abd6add9a798a7d6c10b3775 to your computer and use it in GitHub Desktop.
Generate secure pseudorandom data either as a byte array or base64 string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
Generate secure pseudorandom data either as a byte array or base64 string | |
.PARAMETER Bytes | |
Number of bytes to generate. Defaults to 16. | |
.PARAMETER Base64 | |
Output bytes in base64-encoded string | |
.EXAMPLE | |
.\Get-SecureRandom.ps1 -Bytes 32 -Base64 | |
Returns something like "cawixyAvJCwOsnqV58WbSurVXOb15zVkO6SQy+ZXlQk=" | |
#> | |
[CmdletBinding()] | |
param( | |
[Parameter()] | |
[uint32]$Bytes = 16, | |
[Parameter()] | |
[switch]$Base64 | |
) | |
$ErrorActionPreference = "Stop" | |
Set-StrictMode -Version 5.0 | |
$buffer = [byte[]]::new($Bytes) | |
$rng = [Security.Cryptography.RandomNumberGenerator]::Create() | |
try { | |
$rng.GetBytes($buffer) | |
} finally { | |
$rng.Dispose() | |
} | |
if ($Base64) { | |
[Convert]::ToBase64String($buffer) | |
} else { | |
$buffer | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment