# 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
}
}