Skip to content

PasswordGenerator

Cryptographically secure password generator with customizable character sets and database compatibility.

This class generates random passwords using Python's secrets module for cryptographic security. It provides flexible configuration options for password length, character types, and special handling for database compatibility by excluding problematic characters.

The generator is particularly useful for creating secure passwords for database connections, API keys, and other sensitive credentials in automated infrastructure deployment.

Attributes:

Name Type Description
length int

Length of the generated password

use_digits bool

Whether to include numeric digits (0-9)

use_special_chars bool

Whether to include special characters/punctuation

alphabet str

Final character set used for password generation

db_excluded_chars set

Characters excluded for database compatibility

Source code in mare_aws_common_lib/helpers/password_generator.py
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class PasswordGenerator:
    """
    Cryptographically secure password generator with customizable character sets and database compatibility.

    This class generates random passwords using Python's `secrets` module for cryptographic security.
    It provides flexible configuration options for password length, character types, and special
    handling for database compatibility by excluding problematic characters.

    The generator is particularly useful for creating secure passwords for database connections,
    API keys, and other sensitive credentials in automated infrastructure deployment.

    Attributes:
        length (int): Length of the generated password
        use_digits (bool): Whether to include numeric digits (0-9)
        use_special_chars (bool): Whether to include special characters/punctuation
        alphabet (str): Final character set used for password generation
        db_excluded_chars (set): Characters excluded for database compatibility
    """
    def __init__(self, length=32, use_digits=True, use_special_chars=True, is_for_db=True):
        """
        Initialize the password generator with specified character set and length requirements.

        Constructs the character alphabet based on the provided options and excludes problematic
        characters when database compatibility is required.

        Args:
            length (int, optional): Length of passwords to generate. Must be positive.
                Defaults to 32 characters for strong security.
            use_digits (bool, optional): Include numeric digits (0-9) in the character set.
                Defaults to True.
            use_special_chars (bool, optional): Include special characters and punctuation
                in the character set. Defaults to True.
            is_for_db (bool, optional): Enable database compatibility mode by excluding
                characters that can cause issues in database connection strings or SQL queries.
                Excludes: ' " ; \\ ` $. Defaults to True.

        Note:
            The character set always includes uppercase and lowercase ASCII letters (A-Z, a-z).
            Additional character types are added based on the boolean flags provided.
        """
        self.length = length
        self.use_digits = use_digits
        self.use_special_chars = use_special_chars
        self.alphabet = set(string.ascii_letters)  # Uppercase + lowercase letters
        self.db_excluded_chars = set("'\";\\`$")

        if self.use_digits:
            self.alphabet.update(string.digits) 
        if self.use_special_chars:
            self.alphabet.update(string.punctuation)

        if is_for_db:
            self.alphabet.difference_update(self.db_excluded_chars)

        self.alphabet = "".join(self.alphabet)

    def generate(self) -> str:
        """
        Generate a cryptographically secure random password.

        Creates a password of the specified length using the configured character set.
        Uses Python's `secrets` module which is designed for cryptographic applications
        and provides secure random number generation suitable for passwords and tokens.

        Returns:
            str: Randomly generated password matching the configured specifications.
                The password will have exactly `self.length` characters chosen from
                the configured alphabet.

        Security Notes:
            - Uses `secrets.choice()` which is cryptographically secure
            - Each character is independently randomly selected
            - No predictable patterns or sequences
            - Suitable for production password generation
            - Each call produces a unique password

        Database Compatibility:
            When `is_for_db=True` (default), the generated password will not contain:

            - Single quotes (') - SQL string delimiter conflicts
            - Double quotes (") - SQL identifier conflicts  
            - Semicolons (;) - SQL statement separator conflicts
            - Backslashes (\) - Escape character conflicts
            - Backticks (`) - MySQL identifier delimiter conflicts
            - Dollar signs ($) - Variable expansion conflicts in some contexts
        """
        return ''.join(secrets.choice(self.alphabet) for _ in range(self.length))

Attributes

alphabet = ''.join(self.alphabet) instance-attribute

db_excluded_chars = set('\'";\\`$') instance-attribute

length = length instance-attribute

use_digits = use_digits instance-attribute

use_special_chars = use_special_chars instance-attribute

Functions

__init__(length=32, use_digits=True, use_special_chars=True, is_for_db=True)

Initialize the password generator with specified character set and length requirements.

Constructs the character alphabet based on the provided options and excludes problematic characters when database compatibility is required.

Parameters:

Name Type Description Default
length int

Length of passwords to generate. Must be positive. Defaults to 32 characters for strong security.

32
use_digits bool

Include numeric digits (0-9) in the character set. Defaults to True.

True
use_special_chars bool

Include special characters and punctuation in the character set. Defaults to True.

True
is_for_db bool

Enable database compatibility mode by excluding characters that can cause issues in database connection strings or SQL queries. Excludes: ' " ; \ ` $. Defaults to True.

True
Note

The character set always includes uppercase and lowercase ASCII letters (A-Z, a-z). Additional character types are added based on the boolean flags provided.

Source code in mare_aws_common_lib/helpers/password_generator.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def __init__(self, length=32, use_digits=True, use_special_chars=True, is_for_db=True):
    """
    Initialize the password generator with specified character set and length requirements.

    Constructs the character alphabet based on the provided options and excludes problematic
    characters when database compatibility is required.

    Args:
        length (int, optional): Length of passwords to generate. Must be positive.
            Defaults to 32 characters for strong security.
        use_digits (bool, optional): Include numeric digits (0-9) in the character set.
            Defaults to True.
        use_special_chars (bool, optional): Include special characters and punctuation
            in the character set. Defaults to True.
        is_for_db (bool, optional): Enable database compatibility mode by excluding
            characters that can cause issues in database connection strings or SQL queries.
            Excludes: ' " ; \\ ` $. Defaults to True.

    Note:
        The character set always includes uppercase and lowercase ASCII letters (A-Z, a-z).
        Additional character types are added based on the boolean flags provided.
    """
    self.length = length
    self.use_digits = use_digits
    self.use_special_chars = use_special_chars
    self.alphabet = set(string.ascii_letters)  # Uppercase + lowercase letters
    self.db_excluded_chars = set("'\";\\`$")

    if self.use_digits:
        self.alphabet.update(string.digits) 
    if self.use_special_chars:
        self.alphabet.update(string.punctuation)

    if is_for_db:
        self.alphabet.difference_update(self.db_excluded_chars)

    self.alphabet = "".join(self.alphabet)

generate()

Generate a cryptographically secure random password.

Creates a password of the specified length using the configured character set. Uses Python's secrets module which is designed for cryptographic applications and provides secure random number generation suitable for passwords and tokens.

Returns:

Name Type Description
str str

Randomly generated password matching the configured specifications. The password will have exactly self.length characters chosen from the configured alphabet.

Security Notes
  • Uses secrets.choice() which is cryptographically secure
  • Each character is independently randomly selected
  • No predictable patterns or sequences
  • Suitable for production password generation
  • Each call produces a unique password
Database Compatibility

When is_for_db=True (default), the generated password will not contain:

  • Single quotes (') - SQL string delimiter conflicts
  • Double quotes (") - SQL identifier conflicts
  • Semicolons (;) - SQL statement separator conflicts
  • Backslashes (\) - Escape character conflicts
  • Backticks (`) - MySQL identifier delimiter conflicts
  • Dollar signs ($) - Variable expansion conflicts in some contexts
Source code in mare_aws_common_lib/helpers/password_generator.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def generate(self) -> str:
    """
    Generate a cryptographically secure random password.

    Creates a password of the specified length using the configured character set.
    Uses Python's `secrets` module which is designed for cryptographic applications
    and provides secure random number generation suitable for passwords and tokens.

    Returns:
        str: Randomly generated password matching the configured specifications.
            The password will have exactly `self.length` characters chosen from
            the configured alphabet.

    Security Notes:
        - Uses `secrets.choice()` which is cryptographically secure
        - Each character is independently randomly selected
        - No predictable patterns or sequences
        - Suitable for production password generation
        - Each call produces a unique password

    Database Compatibility:
        When `is_for_db=True` (default), the generated password will not contain:

        - Single quotes (') - SQL string delimiter conflicts
        - Double quotes (") - SQL identifier conflicts  
        - Semicolons (;) - SQL statement separator conflicts
        - Backslashes (\) - Escape character conflicts
        - Backticks (`) - MySQL identifier delimiter conflicts
        - Dollar signs ($) - Variable expansion conflicts in some contexts
    """
    return ''.join(secrets.choice(self.alphabet) for _ in range(self.length))