Skip to content
This repository has been archived by the owner on Apr 26, 2024. It is now read-only.

Use Python's secrets module instead of random #9984

Merged
merged 1 commit into from
May 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/9984.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Simplify a few helper functions.
19 changes: 11 additions & 8 deletions synapse/util/stringutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import itertools
import random
import re
import secrets
import string
from collections.abc import Iterable
from typing import Optional, Tuple
Expand All @@ -35,18 +35,21 @@
#
MXC_REGEX = re.compile("^mxc://([^/]+)/([^/#?]+)$")

# random_string and random_string_with_symbols are used for a range of things,
# some cryptographically important, some less so. We use SystemRandom to make sure
# we get cryptographically-secure randoms.
rand = random.SystemRandom()


def random_string(length: int) -> str:
return "".join(rand.choice(string.ascii_letters) for _ in range(length))
"""Generate a cryptographically secure string of random letters.

Drawn from the characters: `a-z` and `A-Z`
"""
return "".join(secrets.choice(string.ascii_letters) for _ in range(length))


def random_string_with_symbols(length: int) -> str:
return "".join(rand.choice(_string_with_symbols) for _ in range(length))
"""Generate a cryptographically secure string of random letters/numbers/symbols.

Drawn from the characters: `a-z`, `A-Z`, `0-9`, and `.,;:^&*-_+=#~@`
"""
return "".join(secrets.choice(_string_with_symbols) for _ in range(length))


def is_ascii(s: bytes) -> bool:
Expand Down