Last active
May 27, 2016 12:46
-
-
Save tgalv/7a2f2571f3ea061e848888729f843855 to your computer and use it in GitHub Desktop.
Token Spike
This file contains hidden or 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
""" | |
Spike for the token creation and | |
associated probability calculation. | |
""" | |
import math | |
import random | |
import string | |
def _dec_alphabet(): | |
ret_val = list(string.ascii_uppercase) | |
for _char in ['I','O','Q','S', 'Z']: | |
ret_val.remove(_char) | |
return ''.join(ret_val) | |
def _dec_digits(): | |
ret_val = list(string.digits) | |
for _digit in ['0','1','2','5']: | |
ret_val.remove(_digit) | |
return ''.join(ret_val) | |
def _chars(): | |
return _dec_alphabet() + _dec_digits() | |
def dec_token(no_chars): | |
chars = _chars() | |
print("There are {0} characters in the hash".format(len(chars),)) | |
token = ''.join([random.SystemRandom().choice(chars) for i in range(no_chars)]) | |
return token | |
def bp(n, d): | |
# The Birthday Problem | |
v = 1.0 | |
for i in range(n): | |
v = v * (1 - float(i)/d) | |
return 1 - v | |
def single_collision_probability(hash_length): | |
no_of_chars = len(_chars()) | |
combinations = math.pow(no_of_chars, hash_length) | |
return combinations | |
def main(): | |
import sys | |
if len(sys.argv) <2: | |
print("Usage:") | |
print("$ python friendly_token.py <no-of-borrowers> <hash-length>") | |
sys.exit(1) | |
no_of_borrowers = int(sys.argv[1]) | |
hash_length = int(sys.argv[2]) | |
print("Calculating for {0} borrowers with a hash lenth of {1}".format(no_of_borrowers, hash_length)) | |
scp = single_collision_probability(hash_length) | |
prob = bp(no_of_borrowers, scp) * 100 | |
print("Probability of a Single Collision: " + str(1./scp)) | |
print("There is a {0:.4f}% chance of a collision with {1} borrowers with a hash length of {2}".format(prob, no_of_borrowers, hash_length)) | |
print("Example token: '{0}'".format(dec_token(hash_length))) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment