PoshCode Archive  Artifact [822184da09]

Artifact 822184da095b290a7f1655bf79b3256c76d93eaebfc5e5ca52cffb7764634729:

  • File Get-CryptoBytes.ps1 — part of check-in [3a35ec2ff9] at 2018-06-10 13:08:02 on branch trunk — Generate Cryptographically Random Bytes, using RNGCryptoServiceProvider, and optionally format them as strings. (user: unknown size: 1172)

# encoding: ascii
# api: powershell
# title: Get-CryptoBytes
# description: Generate Cryptographically Random Bytes, using RNGCryptoServiceProvider, and optionally format them as strings.
# version: 0.1
# type: function
# license: CC0
# function: Get-CryptoBytes
# x-poshcode-id: 2271
# x-archived: 2010-10-04T16:23:17
#
# Great for generating IIS MachineKeys ;-)
#
function Get-CryptoBytes {
#.Synopsis
#  Generate Cryptographically Random Bytes
#.Description
#  Uses RNGCryptoServiceProvider to generate arrays of random bytes
#.Parameter Count
#  How many bytes to generate
#.Parameter AsString
#  Output hex-formatted strings instead of byte arrays
param(
   [Parameter(ValueFromPipeline=$true)]
   [int[]]$count = 64
,
   [switch]$AsString
)

begin {
   $RNGCrypto = New-Object System.Security.Cryptography.RNGCryptoServiceProvider
   $OFS = ""
}
process {
   foreach($length in $count) {
      $bytes = New-Object Byte[] $length
      $RNGCrypto.GetBytes($bytes)
      if($AsString){
         Write-Output ("{0:X2}" -f $bytes)
      } else {
         Write-Output $bytes
      }
   }
}
end {
   $RNGCrypto = $null
}
}