PoshCode Logo PowerShell Code Repository

Get-Entropy by Matt Graeber 18 months ago (modification of post by Matt Graeber view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/3996"></script>download | new post

Calculate the entropy of a byte array.

  1. function Get-Entropy
  2. {
  3. <#
  4. .SYNOPSIS
  5.  
  6.     Calculate the entropy of a byte array.
  7.  
  8.     Author: Matthew Graeber (@mattifestation)
  9.  
  10. .PARAMETER ByteArray
  11.  
  12.     Specifies the byte array containing the data from which entropy will be calculated.
  13.  
  14. .EXAMPLE
  15.  
  16.     C:\PS> $RandArray = New-Object Byte[](10000)
  17.     C:\PS> foreach ($Offset in 0..9999) { $RandArray[$Offset] = [Byte] (Get-Random -Min 0 -Max 256) }
  18.     C:\PS> $RandArray | Get-Entropy
  19.  
  20.     Description
  21.     -----------
  22.     Calculates the entropy of a large array containing random bytes.
  23.  
  24. .EXAMPLE
  25.  
  26.     C:\PS> 0..255 | Get-Entropy
  27.  
  28.     Description
  29.     -----------
  30.     Calculates the entropy of 0-255. This should equal exactly 8.
  31.  
  32. .INPUTS
  33.  
  34.     System.Byte[]
  35.  
  36.     Get-Entropy accepts a byte array from the pipeline
  37.  
  38. .OUTPUTS
  39.  
  40.     System.Double
  41.  
  42.     Get-Entropy outputs a double representing the entropy of the byte array.
  43.  
  44. .LINK
  45.  
  46.     http://www.exploit-monday.com
  47. #>
  48.  
  49.     [CmdletBinding()] Param (
  50.         [Parameter(Mandatory = $True, Position = 0, ValueFromPipeline = $True)]
  51.         [Byte[]]
  52.         $ByteArray
  53.     )
  54.  
  55.     BEGIN
  56.     {
  57.         $FrequencyTable = @{}
  58.         $ByteArrayLength = 0
  59.     }
  60.  
  61.     PROCESS
  62.     {
  63.         foreach ($Byte in $ByteArray)
  64.         {
  65.             $FrequencyTable[$Byte]++
  66.             $ByteArrayLength++
  67.         }
  68.     }
  69.  
  70.     END
  71.     {
  72.         $Entropy = 0.0
  73.  
  74.         foreach ($Byte in 0..255)
  75.         {
  76.             $ByteProbability = ([Double] $FrequencyTable[[Byte]$Byte]) / $ByteArrayLength
  77.             if ($ByteProbability -gt 0)
  78.             {
  79.                 $Entropy += -$ByteProbability * [Math]::Log($ByteProbability, 2)
  80.             }
  81.         }
  82.  
  83.         Write-Output $Entropy
  84.     }
  85. }

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