PoshCode Archive  Artifact [c70eeea340]

Artifact c70eeea3407379483d280a38b9e9e48b47f7f5c4c27e72d4199153645a325060:

  • File Get-CryptoBytes.ps1 — part of check-in [e4dc9dfade] at 2018-06-10 14:12:39 on branch trunk — Generate Cryptographically Random Bytes, using RNGCryptoServiceProvider, and optionally format them as strings. (user: webclient size: 1367)

# 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
# author: webclient
# license: CC0
# function: Get-CryptoBytes
# x-poshcode-id: 6306
# x-archived: 2016-04-18T22:00:17
# x-published: 2016-04-15T21:25:00
#
# Great for generating IIS MachineKeys ;-)
# Changed to write the string output without spaces between nibble pairs. (I.e. “ABCDEF” instead of “AB CD EF”)
#
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 (-join ($bytes | % {"{0:X2}" -f $_}))
      } else {
         Write-Output $bytes
      }
   }
}
end {
   $RNGCrypto = $null
}
}