PoshCode Logo PowerShell Code Repository

Get-CryptoBytes by azdazdazda 4 weeks ago (modification of post by webclient view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/6655"></script>download | new post

Generate Cryptographically Random Bytes, using RNGCryptoServiceProvider, and optionally format them as strings.
Great for generating IIS MachineKeys ;-)

  1. function Get-CryptoBytes {
  2. #.Synopsis
  3. #  Generate Cryptographically Random Bytes
  4. #.Description
  5. #  Uses RNGCryptoServiceProvider to generate arrays of random bytes
  6. #.Parameter Count
  7. #  How many bytes to generate
  8. #.Parameter AsString
  9. #  Output hex-formatted strings instead of byte arrays
  10. param(
  11.    [Parameter(ValueFromPipeline=$true)]
  12.    [int[]]$count = 64
  13. ,
  14.    [switch]$AsString
  15. )
  16.  
  17. begin {
  18.    $RNGCrypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
  19.    $OFS = ""
  20. }
  21. process {
  22.    foreach($length in $count) {
  23.       $bytes = New-Object Byte[] $length
  24.       $RNGCrypto.GetBytes($bytes)
  25.       if($AsString){
  26.          Write-Output ("{0:X2}" -f $bytes)
  27.       } else {
  28.          Write-Output $bytes
  29.       }
  30.    }
  31. }
  32. end {
  33.    $RNGCrypto = $null
  34. }
  35. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me