Calculate Shannon entropy to detect packed or encrypted ELF files.
(filepath)
| 846 | |
| 847 | |
| 848 | def calculate_entropy(filepath): |
| 849 | """Calculate Shannon entropy to detect packed or encrypted ELF files.""" |
| 850 | try: |
| 851 | with open(filepath, "rb") as f: |
| 852 | data = f.read() |
| 853 | counter = Counter(data) |
| 854 | total = len(data) |
| 855 | entropy = -sum((count / total) * math.log2(count / total) for count in counter.values()) |
| 856 | return entropy |
| 857 | except Exception as e: |
| 858 | prRed(f"Error calculating entropy: {e}") |
| 859 | return 0 |
| 860 | |
| 861 | |
| 862 | # TODO Add in the following test |