summaryrefslogtreecommitdiff
path: root/django/utils/crypto.py
diff options
context:
space:
mode:
authorClaude Paroz <claude@2xlibre.net>2020-03-11 09:47:43 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2020-03-11 13:16:44 +0100
commite663f695fb282053b31f69ee2dcbc67ddacb9104 (patch)
tree059aefa465734a3d0a781cab682d80511cb6ae92 /django/utils/crypto.py
parent5cc2c63f902412cdd9a8ebbabbd953aa8e2180c0 (diff)
Fixed #31359 -- Deprecated get_random_string() calls without an explicit length.
Diffstat (limited to 'django/utils/crypto.py')
-rw-r--r--django/utils/crypto.py28
1 files changed, 23 insertions, 5 deletions
diff --git a/django/utils/crypto.py b/django/utils/crypto.py
index edeb336f34..8d25d96c0d 100644
--- a/django/utils/crypto.py
+++ b/django/utils/crypto.py
@@ -4,8 +4,10 @@ Django's standard crypto functions and utilities.
import hashlib
import hmac
import secrets
+import warnings
from django.conf import settings
+from django.utils.deprecation import RemovedInDjango40Warning
from django.utils.encoding import force_bytes
@@ -44,15 +46,31 @@ def salted_hmac(key_salt, value, secret=None, *, algorithm='sha1'):
return hmac.new(key, msg=force_bytes(value), digestmod=hasher)
-def get_random_string(length=12,
- allowed_chars='abcdefghijklmnopqrstuvwxyz'
- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
+NOT_PROVIDED = object() # RemovedInDjango40Warning.
+
+
+# RemovedInDjango40Warning: when the deprecation ends, replace with:
+# def get_random_string(self, length, allowed_chars='...'):
+def get_random_string(length=NOT_PROVIDED, allowed_chars=(
+ 'abcdefghijklmnopqrstuvwxyz'
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
+)):
"""
Return a securely generated random string.
- The default length of 12 with the a-z, A-Z, 0-9 character set returns
- a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
+ The bit length of the returned value can be calculated with the formula:
+ log_2(len(allowed_chars)^length)
+
+ For example, with default `allowed_chars` (26+26+10), this gives:
+ * length: 12, bit length =~ 71 bits
+ * length: 22, bit length =~ 131 bits
"""
+ if length is NOT_PROVIDED:
+ warnings.warn(
+ 'Not providing a length argument is deprecated.',
+ RemovedInDjango40Warning,
+ )
+ length = 12
return ''.join(secrets.choice(allowed_chars) for i in range(length))