Skip to content

Instantly share code, notes, and snippets.

@LeeHolmes
Created March 25, 2015 03:27
Show Gist options
  • Save LeeHolmes/b16cbb68493d108e3400 to your computer and use it in GitHub Desktop.
Save LeeHolmes/b16cbb68493d108e3400 to your computer and use it in GitHub Desktop.
Get-Entropy with hotspot implemented via Add-Type
## Not measurably faster. Doing this via Add-Type or direct PowerShell still takes about 4 seconds per megabyte.
function Get-Entropy
{
<#
.SYNOPSIS
Calculate the entropy of a byte array.
Derived from Get-Entropy by Matthew Graeber (@mattifestation)
.PARAMETER ByteArray
Specifies the byte array containing the data from which entropy will be calculated.
.EXAMPLE
C:\PS> $RandArray = New-Object Byte[](10000)
C:\PS> foreach ($Offset in 0..9999) { $RandArray[$Offset] = [Byte] (Get-Random -Min 0 -Max 256) }
C:\PS> $RandArray | Get-Entropy
Description
-----------
Calculates the entropy of a large array containing random bytes.
.EXAMPLE
C:\PS> 0..255 | Get-Entropy
Description
-----------
Calculates the entropy of 0-255. This should equal exactly 8.
.INPUTS
System.Byte[]
Get-Entropy accepts a byte array from the pipeline
.OUTPUTS
System.Double
Get-Entropy outputs a double representing the entropy of the byte array.
.LINK
http://www.exploit-monday.com
#>
[CmdletBinding()] Param (
[Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
[Byte[]]
$ByteArray
)
BEGIN
{
$FrequencyTable = @{}
$ByteArrayLength = 0
Add-Type -Name EntropyCalculator -Namespace Kansa -MemberDefinition '
public static void ProcessBytes(System.Collections.Hashtable frequencyTable, Byte[] byteArray)
{
foreach(Byte inputByte in byteArray)
{
if(! frequencyTable.ContainsKey(inputByte))
{
frequencyTable[inputByte] = 0;
}
frequencyTable[inputByte] = (int) frequencyTable[inputByte] + 1;
}
}
'
}
PROCESS
{
$ByteArrayLength += $ByteArray.Length
[Kansa.EntropyCalculator]::ProcessBytes($FrequencyTable, $ByteArray)
}
END
{
$Entropy = 0.0
foreach ($Byte in 0..255)
{
$ByteProbability = ([Double] $FrequencyTable[[Byte]$Byte]) / $ByteArrayLength
if ($ByteProbability -gt 0)
{
$Entropy += -$ByteProbability * [Math]::Log($ByteProbability, 2)
}
}
Write-Output $Entropy
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment