## Monday, July 22, 2013

### Information Shannon Entropy

Shannon/data entropy is a measurement of uncertainty. Entropy can be used as a measure of randomness. Data entropy is typically expressed as the number of bits needed to encode or represent data. In the example below, we are working with bytes, so the max entropy for a stream of bytes is 8.

A file with high entropy means that each symbol is more-or-less equally as likely to appear next. If a file or file stream has high entropy, it is either probably compressed, encrypted or random. This can be used to detect packed executables, cipher streams on a network, or a breakdown of encrypted communication on a network that is expected to be always encrypted.

A text file will have low entropy. If a file has low data entropy, it mean that the file will compress well.

This post and code was inspired by Mike Schiffman's excelent explaination of data entropy on his Cisco Security Blog.

Here is what I wrote:
``````
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace DataEntropy
{
public class DataEntropyUTF8
{
// Stores the number of times each symbol appears
SortedList<byte,int>        distributionDict;
// Stores the entropy for each character
SortedList<byte,double> probabilityDict;
// Stores the last calculated entropy
double overalEntropy;
// Used for preventing unnecessary processing
bool isDirty;
// Bytes of data processed
int dataSize;

public int DataSampleSize
{
get { return dataSize; }
private set { dataSize = value; }
}

public int UniqueSymbols
{
get { return distributionDict.Count; }
}

public double Entropy
{
get { return GetEntropy(); }
}

public Dictionary<byte,int> Distribution
{
get { return GetSortedDistribution(); }
}

public Dictionary<byte,double> Probability
{
get { return GetSortedProbability(); }
}

public byte GetGreatestDistribution()
{
return distributionDict.Keys[0];
}

public byte GetGreatestProbability()
{
return probabilityDict.Keys[0];
}

public double GetSymbolDistribution(byte symbol)
{
return distributionDict[symbol];
}

public double GetSymbolEntropy(byte symbol)
{
return probabilityDict[symbol];
}

Dictionary<byte,int> GetSortedDistribution()
{
List<Tuple<int,byte>> entryList = new List<Tuple<int, byte>>();
foreach(KeyValuePair<byte,int> entry in distributionDict)
{
}
entryList.Sort();
entryList.Reverse();

Dictionary<byte,int> result = new Dictionary<byte, int>();
foreach(Tuple<int,byte> entry in entryList)
{
}
return result;
}

Dictionary<byte,double> GetSortedProbability()
{
List<Tuple<double,byte>> entryList = new List<Tuple<double,byte>>();
foreach(KeyValuePair<byte,double> entry in probabilityDict)
{
}
entryList.Sort();
entryList.Reverse();

Dictionary<byte,double> result = new Dictionary<byte,double>();
foreach(Tuple<double,byte> entry in entryList)
{
}
return result;
}

double GetEntropy()
{
// If nothing has changed, dont recalculate
if(!isDirty) {
return overalEntropy;
}
// Reset values
overalEntropy = 0;
probabilityDict = new SortedList<byte,double>();

foreach(KeyValuePair<byte,int> entry in distributionDict)
{
// Probability = Freq of symbol / # symbols examined thus far
entry.Key,
(double)distributionDict[entry.Key] / (double)dataSize
);
}

foreach(KeyValuePair<byte,double> entry in probabilityDict)
{
// Entropy = probability * Log2(1/probability)
overalEntropy += entry.Value * Math.Log((1/entry.Value),2);
}

isDirty = false;
return overalEntropy;
}

public void ExamineChunk(byte[] chunk)
{
if(chunk.Length<1 || chunk==null) {
return;
}

isDirty = true;
dataSize += chunk.Length;

foreach(byte bite in chunk)
{
if(!distributionDict.ContainsKey(bite))
{
continue;
}
distributionDict[bite]++;
}
}

public void ExamineChunk(string chunk)
{
ExamineChunk(StringToByteArray(chunk));
}

byte[] StringToByteArray(string inputString)
{
char[] c = inputString.ToCharArray();
IEnumerable<byte> b = c.Cast<byte>();
return b.ToArray();
}

void Clear()
{
isDirty = true;
overalEntropy = 0;
dataSize = 0;
distributionDict = new SortedList<byte, int>();
probabilityDict = new SortedList<byte, double>();
}

public DataEntropyUTF8(string fileName)
{
this.Clear();
if(File.Exists(fileName))
{