@@ -41,48 +41,42 @@ func processEntropy(forConnection connection: ObservedConnection) -> (processsed
4141
4242func calculateEntropy( for packet: Data ) -> Double
4343{
44- let probabilityDictionary : [ UInt8 : Double ] = calculateProbabilities ( for: packet)
44+ NSLog ( " Entropy for \( packet as! NSData ) " )
45+ let probabilities : [ Double ] = calculateProbabilities ( for: packet)
4546 var entropy : Double = 0
4647
47- for probability in probabilityDictionary
48+ for probability in probabilities
4849 {
49- let plog2 = log2 ( probability. value)
50- entropy += ( plog2 * probability. value)
50+ if probability != 0 {
51+ let plog2 = log2 ( probability)
52+ entropy += ( plog2 * probability)
53+ }
5154 }
5255 entropy = - entropy
5356
5457 return entropy
5558}
5659
5760/// Calculates the probability of each byte in the data packet
58- /// and returns them in a dictionary where key is the byte and value is the probability
59- private func calculateProbabilities( for packet: Data ) -> [ UInt8 : Double ]
61+ /// and returns them in an array where the index is the byte and value is the probability
62+ private func calculateProbabilities( for packet: Data ) -> [ Double ]
6063{
6164 let packetArray = [ UInt8] ( packet)
62- let packetSet = Set ( packetArray)
63- var probabilityDictionary = [ UInt8: Double] ( )
64- var countArray = Array ( repeating: 1.0 , count: 256 )
65-
66- for uniqueByte in packetSet
67- {
68- let uniqueByteInt = Int ( uniqueByte)
69-
70- for value in packetArray
71- {
72- if value == uniqueByte
73- {
74- countArray [ uniqueByteInt] = countArray [ uniqueByteInt] + 1
75- }
76- }
65+ var countArray = Array ( repeating: 0.0 , count: 256 )
66+
67+ for byte in packetArray {
68+ let index = Int ( byte)
69+ countArray [ index] += 1
7770 }
7871
7972 for (index, countValue) in countArray. enumerated ( )
8073 {
81- let probability = Double ( countValue) / Double( 256 + packetArray. count)
82- probabilityDictionary [ UInt8 ( index) ] = probability
74+ if countValue != 0 {
75+ countArray [ index] /= Double ( packet. count)
76+ }
8377 }
8478
85- return probabilityDictionary
79+ return countArray
8680}
8781
8882func scoreAllEntropy( )
0 commit comments