-
Notifications
You must be signed in to change notification settings - Fork 1
/
entropy.go
70 lines (58 loc) · 1.31 KB
/
entropy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package filedriller
import (
"fmt"
"io"
"math"
"os"
)
const (
// MaxFileSize is the max size file thatr should be processed. This defaults to 1 GB.
MaxFileSize = 1073741824
// MaxEntropyChunk is the max byte size of a chunk read
MaxEntropyChunk = 256000
)
// entropy calculates the entropy of a file.
func entropy(path string) (entropy float64, err error) {
f, err := os.Open(path)
if err != nil {
return 0, err
}
defer f.Close()
fStat, err := f.Stat()
if err != nil {
return 0, err
}
if !fStat.Mode().IsRegular() {
return 0, fmt.Errorf("file (%s) is not a regular file to calculate entropy", path)
}
var filesize int64
filesize = fStat.Size()
if filesize == 0 {
return 0, nil
}
if filesize > int64(MaxFileSize) {
return 0, fmt.Errorf("file size (%d) is too large to calculate entropy (max allowed: %d)",
filesize, int64(MaxFileSize))
}
dataBytes := make([]byte, MaxEntropyChunk)
byteCounts := make([]int, 256)
for {
numBytesRead, err := f.Read(dataBytes)
if err == io.EOF {
break
}
if err != nil {
return 0, err
}
for i := 0; i < numBytesRead; i++ {
byteCounts[int(dataBytes[i])]++
}
}
for i := 0; i < 256; i++ {
px := float64(byteCounts[i]) / float64(filesize)
if px > 0 {
entropy += -px * math.Log2(px)
}
}
return math.Round(entropy*100) / 100, nil
}