From: Steven Tobin Date: Sat, 2 Jun 2012 09:52:03 +0000 (+0100) Subject: Added code for fallback random generator use X-Git-Url: http://git.99rst.org/?a=commitdiff_plain;h=23be6060a05ca27a5e4814c56db71ca56f2faae5;p=redacted-XKCD-password-generator.git Added code for fallback random generator use Code attempts to use random.SystemRandom if present, will print a warning then use random.Random() if not. --- diff --git a/xkcd-password.py b/xkcd-password.py index 23f7efc..fa3cb69 100755 --- a/xkcd-password.py +++ b/xkcd-password.py @@ -35,11 +35,19 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import random import os -import sys import optparse import re import math +# random.SystemRandom() should be cryptographically secure +try: + rng = random.SystemRandom +except AttributeError: + print("WARNING: System does not support cryptographically secure random " + "number generator or you are using Python version < 2.4. " + "Continuing with less-secure generator.\n") + + rng = random.Random def generate_wordlist(wordfile=None, min_length=5, @@ -100,12 +108,7 @@ def generate_xkcdpassword(wordlist, n_words=4, interactive=False): # useful if driving the logic from other code if not interactive: - try: - # random.SystemRandom() should be cryptographically secure - return " ".join(random.SystemRandom().sample(wordlist, n_words)) - except NotImplementedError: - print("System does not support random number generator or Python" - "version < 2.4.") + return " ".join(rng().sample(wordlist, n_words)) # else, interactive session custom_n_words = raw_input("Enter number of words (default 4): ") @@ -116,11 +119,7 @@ def generate_xkcdpassword(wordlist, n_words=4, interactive=False): accepted = "n" while accepted.lower() not in ["y", "yes"]: - try: - passwd = " ".join(random.SystemRandom().sample(wordlist, n_words)) - except NotImplementedError: - print("System does not support random number generator or Python" - "version < 2.4.") + passwd = " ".join(rng().sample(wordlist, n_words)) print("Generated: ", passwd) accepted = raw_input("Accept? [yN] ")