-
-
Save 0xBADCA7/54874a315194d3cf107624f06ee699cc to your computer and use it in GitHub Desktop.
This is a script which counts a character entropy in a single string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python | |
import math | |
import sys | |
''' | |
This is a script which counts a character entropy in a single string. | |
Usage: entropy.py STRING | |
''' | |
BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" | |
def shannon_entropy(data): | |
try: | |
if not data: | |
return 0 | |
entropy = 0 | |
for x in BASE64_CHARS: | |
p_x = float(data.count(x))/len(data) | |
if p_x > 0: | |
entropy += - p_x*math.log(p_x, 2) | |
return entropy | |
except Exception as e: | |
print("Error: " + str(e)) | |
if __name__ == '__main__': | |
if len(sys.argv) != 2: | |
print("Exactly 1 argument is required.") | |
print("Usage: entropy.py STRING") | |
sys.exit() | |
print("The entropy of a character in a string '" + sys.argv[1] + | |
"' is " + str(shannon_entropy(sys.argv[1])) + " bits") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment