Skip to content

Instantly share code, notes, and snippets.

@0xBADCA7
Forked from xep624/entropy.py
Created February 2, 2019 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 0xBADCA7/54874a315194d3cf107624f06ee699cc to your computer and use it in GitHub Desktop.
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.
#!/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