aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorCody Logan <clpo13@gmail.com>2020-01-08 09:23:46 -0800
committerCody Logan <clpo13@gmail.com>2020-01-08 09:23:46 -0800
commitd964e7fc6a644196993121f98f09bc66cd0e181d (patch)
tree001cbae71010aa542bb9149cec06f84b9e4337c1
parentf97fefad37d65dece3fc8047e8d7ea874ec26906 (diff)
downloadalphanum-d964e7fc6a644196993121f98f09bc66cd0e181d.tar.gz
alphanum-d964e7fc6a644196993121f98f09bc66cd0e181d.zip
Add secure generate function
-rw-r--r--alphanum/__init__.py2
-rw-r--r--alphanum/alphanum.py43
-rw-r--r--tests/test_alphanum.py16
3 files changed, 58 insertions, 3 deletions
diff --git a/alphanum/__init__.py b/alphanum/__init__.py
index 03894dd..3afda23 100644
--- a/alphanum/__init__.py
+++ b/alphanum/__init__.py
@@ -1,3 +1,3 @@
-from .alphanum import generate # noqa: F401
+from .alphanum import generate, generate_s # noqa: F401
__version__ = '0.2.0dev1'
diff --git a/alphanum/alphanum.py b/alphanum/alphanum.py
index 3272f6c..7049830 100644
--- a/alphanum/alphanum.py
+++ b/alphanum/alphanum.py
@@ -1,7 +1,46 @@
import random
+import secrets
+import string
-POP = 'abcdefghijklmnopqrstuvwxyz0123456789'
+POP = string.ascii_letters + string.digits
-def generate(length=1) -> str:
+def generate(length: int = 1) -> str:
+ """Generates a pseudo-random string of alphanumeric characters of the given
+ length. If no length is specified, a single character is returned.
+
+ Args:
+ length (:obj:`int`, optional): Desired string length. Defaults to 1.
+
+ Returns:
+ str: A pseudo-random alphanumeric string.
+
+ Examples:
+ >>> print(generate())
+ 'G'
+ >>> print(generate(10))
+ 'a93jfDjdA0'
+
+ """
return ''.join(random.SystemRandom().choices(POP, k=length))
+
+
+def generate_s(length: int = 1) -> str:
+ """Generates a cryptographically strong random string of alphanumeric
+ characters of the given length. If no length is specified, a single
+ character is returned.
+
+ Args:
+ length (:obj:`int`, optional): Desired string length. Defaults to 1.
+
+ Returns:
+ str: A random alphanumeric string.
+
+ Examples:
+ >>> print(generate_s())
+ '5'
+ >>> print(generate_s(10))
+ 't3g0Gh9Naj'
+
+ """
+ return ''.join(secrets.SystemRandom().choice(POP) for i in range(length))
diff --git a/tests/test_alphanum.py b/tests/test_alphanum.py
index fc9bc41..d567bdb 100644
--- a/tests/test_alphanum.py
+++ b/tests/test_alphanum.py
@@ -15,3 +15,19 @@ def test_subsequent_strings_differ():
foo = alphanum.generate(10)
bar = alphanum.generate(10)
assert foo != bar
+
+
+def test_secure_no_string_length():
+ foo = alphanum.generate_s()
+ assert len(foo) == 1
+
+
+def test_secure_with_string_length():
+ foo = alphanum.generate_s(10)
+ assert len(foo) == 10
+
+
+def test_secure_subsequent_strings_differ():
+ foo = alphanum.generate_s(10)
+ bar = alphanum.generate_s(10)
+ assert foo != bar