-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a2a6874
commit 98e58b5
Showing
1 changed file
with
25 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import string | ||
import secrets | ||
|
||
|
||
def generate_rand_secret(length: int, exclude_chars: str) -> str: | ||
""" | ||
Generates a cryptographically secure random secret, excluding specified characters. | ||
""" | ||
# Define the default character set | ||
all_characters = string.ascii_letters + string.digits + string.punctuation | ||
effective_characters = all_characters | ||
|
||
if exclude_chars: | ||
effective_characters = [ | ||
char for char in all_characters if char not in exclude_chars | ||
] | ||
|
||
# Check if the exclusion set doesn't leave us with too few characters | ||
if len(effective_characters) < length: | ||
raise ValueError( | ||
f"Excluding '{exclude_chars}' leaves insufficient characters to generate a {length}-character secret." | ||
) | ||
|
||
# Generate the secret using secrets.choice for cryptographically secure randomness | ||
return "".join(secrets.choice(effective_characters) for _ in range(length)) |