Secrets (Python)

I have used the Random library in Python a few times to generate a random choice; however many people will (rightly) tell you that a computer generated random number is not a true random number.

https://imgs.xkcd.com/comics/random_number.png
Is Random’s random number truly random? Comic from XKCD.com

The Random library is perfect for games or simulations that do not require security (cryptography); however for Python projects that do need security (e.g. security keys) then there is a Python library called Secrets.

I’ve had a brief play with Secrets; originally as I stumbled across the secrets.randbelow(n) –with n begins a integer– command, which soon lead to me playing with the secrets.randbits(k) –with k being a integer– command


# geektechstuff
# ssshhh, it is a secret
import secrets
#imports secrets library
import random
#imports random library - not really needed, but I wanted to see random and secret working alongside each other

test_range = random.randint(0, 999)
test_below = secrets.randbelow(1000)
print('rand', test_range)
print('sec', test_below)
test_32bits = secrets.randbits(32)
test_64bits = secrets.randbits(64)
test_128bits = secrets.randbits(128)
test_256bits = secrets.randbits(256)
test_512bits = secrets.randbits(512)
print(test_32bits)
print('')
print(test_64bits)
print('')
print(test_128bits)
print('')
print(test_256bits)
print('')
print(test_512bits)
print('')

python_sectret

256 bit encryption is used for most modern encryption methods (such as SSL and AES) and in theory it would take 50 supercomputers checking a billion billion (thats 1018) keys around 3×1051 years to break according to Wikipedia.

I’m thinking I might be able to use the Secrets library in a crypto / cipher project…

More information on Python Random can be find at https://docs.python.org/2/library/random.html and more information on Python Secrets can be found at https://docs.python.org/3/library/secrets.html