Created
July 3, 2020 13:02
-
-
Save JosephHewitt/dc6868c47594108dad2caa0d0be27790 to your computer and use it in GitHub Desktop.
An example of a badly implemented random numerical ID generator based on ord() and os.urandom()
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
#!/usr/bin/env python3 | |
""" | |
This code snippet is a deliberate bad implementation of a random numerical ID generator based on ord() | |
This will generate 150000 random 18-digit IDs and then show the frequency of each digit in the IDs. | |
You should see more 1s and 2s than other digits. | |
ord(os.urandom(1)) will return a random number up to 255. If you generate multiple values and concatenate them, | |
you will get a random code/ID up to the length you want, however, because ord is returning an int which is <255, | |
you will statistically get more 1s and 2s in your ID. | |
""" | |
import pprint | |
import os | |
def random_id(length): | |
output = "" | |
while len(output) < length: | |
output += str(ord(os.urandom(1))) | |
return output[:length] | |
def main(): | |
print("Example ID:", random_id(18), "\n") | |
print("Generating a frequency table of each digit from 150000 randomly generated IDs using the above function\n") | |
ftable = {} | |
for x in range(1, 150000): | |
gen = random_id(18) | |
ints = list(gen) | |
for i in ints: | |
try: | |
ftable[i] += 1 | |
except: | |
ftable[i] = 1 | |
pp = pprint.PrettyPrinter(indent=4) | |
pp.pprint(ftable) | |
print("\nThe most common digits should be 1 and 2 due to this flaw in the implementation. Don't use this function for generating random IDs.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment