-
Notifications
You must be signed in to change notification settings - Fork 0
aplustools.security
-
aplustools.security.crypto package * Subpackages
-
aplustools.security.crypto.algos package * `Module contents
<aplustools.security.crypto.algos#module-aplustools.security.crypto.algos>`_
-
aplustools.security.crypto.exceptions module * `NotSupportedError
<aplustools.security.crypto#aplustools.security.crypto.exceptions.NotSupportedError>`_ * `NotSupportedError.__init__()
<aplustools.security.crypto#aplustools.security.crypto.exceptions.NotSupportedError.__init__>`_
-
Module contents * `Backend
<aplustools.security.crypto#aplustools.security.crypto.Backend>`_ * `Backend.argon2_cffi
<aplustools.security.crypto#aplustools.security.crypto.Backend.argon2_cffi>`_
-
TBA
class aplustools.security.passwords.PasswordFilter(exclude_chars: str = '', extra_chars: str = '', exclude_similar: bool = False)
Bases:
objectUsed to easily filter passwords based on a few simple concepts.
__init__(exclude_chars: str = '', extra_chars: str = '', exclude_similar: bool = False)
apply(character_set: str, set_name: Literal['letters', 'numbers', 'punctuations', 'unicode']) -> str
Applies the filter to a specific character set.
Parameters:
- character_set – The charset
- set_name – Which charset is being filtered
Returns: The filtered charset
filter_word(word: str) -> str
Filters one word.
Parameters: word – The word to be filtered Returns: The filtered word will_filter(char: str) -> bool
Checks if a specific char would be filtered.
Parameters: char – The char to be checked Returns: If the char would be filtered
class aplustools.security.passwords.PasswordGenerator(random_generator: Literal['weak', 'average', 'strong'] | Any = 'strong', debug: bool = False)
Bases:
objectThe random generators security can be adjusted, and all default arguments will result in a password that has an average worst case crack time of multiple years (Verified using zxcvbn).
__init__(random_generator: Literal['weak', 'average', 'strong'] | Any = 'strong', debug: bool = False) -> None
basic_secure_password(password: str, passes: int = 3, expand: bool = True) -> str
Makes the inputted password more secure by introducing slight changes each iteration.
Parameters:
- password – The password to be secured
- passes – How many iterations this should run for
- expand – If the password should be able to get larger
Returns: The secured password
dynamic_secure_password(password: str, passes: int = 3, expand: bool = True) -> str
Makes the inputted password more secure by introducing slight changes each iteration. Dynamically changes less the longer the password, as they are already really secure.
Parameters:
- password – The password to be secured
- passes – How many iterations this should run for
- expand – If the password should be able to get larger
Returns: The secured password
generate_complex_password(length: int = 18, filter_: PasswordFilter | None = None) -> str
Generate a complex, high-entropy password using random characters.
The password includes at least one uppercase letter, one lowercase letter, one digit, and one punctuation character. The remaining characters are selected randomly from all allowed character sets. A password filter can optionally constrain which characters are used.
Parameters:
- length – The length of the password
- filter – An optional password filter
Returns: The generated password
generate_complex_pattern_password(pattern: str = '9nX9XWn9Ww9x9X-W!/999wnwwx!!', filter_: PasswordFilter | None = None) -> str
A pattern password X for an uppercase letter, x for a lowercase letter, 9 for a number, W for a capitalized word, w for a lowercase word, n for a negative number and ! for a symbol. All other characters are ignored and included as is in the final password
Parameters:
- pattern – The pattern to generate the password by
- filter – An optional password filter
Returns: The generated password
generate_mnemonic_password(length: int = 20, filter_: PasswordFilter | None = None, _return_info: bool = False) -> str | tuple[str, str, str]
A mnemonic password using adjectives and nouns
Parameters:
- length – The length of the password
- filter – An optional password filter
- _return_info – If extra info about the password should be returned
Returns: generate_pattern_password(pattern: str = '9/XxX-999xXx-99/XxX-999xXx-9', filter_: PasswordFilter | None = None) -> str
A pattern password X for an uppercase letter, x for a lowercase letter and 9 for a number. All other characters are ignored and included as is in the final password
Parameters:
- pattern – The pattern to generate the password by
- filter – An optional password filter
Returns: The generated password
generate_random_password(length: int = 18, filter_: PasswordFilter | None = None) -> str
Entirely random
Parameters:
- length – The length of the password
- filter – An optional password filter
Returns: The generated password
generate_ratio_based_password_v3(length: int = 24, letters_ratio: float = 0.5, numbers_ratio: float = 0.3, punctuations_ratio: float = 0.2, unicode_ratio: float = 0.0, filter_: PasswordFilter | None = None) -> str
Generate a version 3 password based on character type ratios.
This method creates a password composed of randomly selected characters, distributed according to specified ratios of letters, numbers, punctuation, and optional Unicode symbols.
Parameters:
- length – The length of the password
- letters_ratio – The ratio of letters in the final password
- numbers_ratio – The ratio of numbers in the final password
- punctuations_ratio – The ratio of punctuations in the final password
- unicode_ratio – The ratio of unicode in the final password
- filter – An optional password filter
Returns: generate_secure_passphrase(words: list[str] | None = None, num_words: int = 6, filter_: PasswordFilter | None = None, _return_info: bool = True) -> str | tuple[str, str]
Passphrase, secure as it’s very long
Parameters:
- words – Which words to use in the passphrase
- num_words – The number of words to be used
- filter – An optional password filter
- _return_info – If extra info about the password should be returned
Returns: The generated password
generate_secure_sentence(length: int = 4) -> str
Generates a secure sentence using the currently loaded dictionaries, often used internally for secure sentence generation. [Choices is more secure than sample]
Parameters: length – The length of the sentence in words Returns: The generated sentence generate_sentence_based_password_v3(sentence: str | None = None, char_position: Literal['random', 'keep'] | int = 'keep', random_case: bool = True, extra_char: str = '/', num_length: int = 6, special_chars_length: int = 4, password_format: str = '{words}{special}{extra}{numbers}', filter_: PasswordFilter | None = None, _return_info: bool = False) -> str | tuple[str, str]
Generate a version 3 sentence-based password.
This method creates a password using words from a sentence (either user-provided or randomly generated), combined with random numbers, special characters, and an optional extra character. The format and rules for how the password is constructed can be customized.
Parameters:
- sentence – The sentence to generate the password with, if this is not passed, a random sentence will be used.
- char_position – Which character in the word should be used in the password. You can also pass “random” for random and “keep” for keeping their position.
- random_case – If the case of characters in the final password should be randomized
- extra_char – Extra character part of the password
- num_length – The length of the numbers part of the password
- special_chars_length – The length of the punctuation part of the password
- password_format – How to structure the different parts of the password into one.
- filter – An optional password filter
- _return_info – If extra info about the password should be returned
Returns: The generated password
generate_words_based_password_v3(sentence: str | None = None, shuffle_words: bool = True, shuffle_characters: bool = True, repeat_words: bool = False, filter_: PasswordFilter | None = None, _return_info: bool = False) -> str | tuple[str, str]
Generate a version 3 words-based password.
This method creates a password using words from a sentence. It allows customization such as shuffling the word order, scrambling characters within words, and repeating words. If no sentence is provided, a random one is used.
Parameters:
- sentence – The sentence to generate the password with, if this is not passed, a random sentence will be used.
- shuffle_words – If the order of the words should change in the final password
- shuffle_characters – If the order of the characters in each word should change
- repeat_words – If words should be able to be repeated
- filter – An optional password filter
- _return_info – If extra info about the password should be returned
Returns: The generated password
load_12_dicts() -> None
Loads a selection of the 12 dicts which were deemed the most useful in sentence generation. :return:load_def_dict() -> None
Loads the default dictionary for random sentence generation. :return:load_google_10000_dict() -> None
Loads google 10 000 dictionary for random sentence generation (uk & us without swears). :return:load_scowl_dict(size: Literal['50', '60', '70', '80', '95'] = '50') -> None
Loads one of scowl dicts, specified by their size. Larger sizes have all words of the smaller ones and more. :param size: The size of the dictionary to be loaded :type size: Literal[“50”, “60”, “70”, “80”, “95”] :return:reduce_password(password: str, by: int | Literal['all'] = 0) -> str
Reduces a given password using random binary operations to ensure a secure password.
Parameters:
- password – The password to be reduces
- by – How many characters each character should be joined with (0 means none and “all” means all).
Returns: The reduced password
static_secure_password(password: str, passes: int = 3, expand: bool = True) -> str
Makes the inputted password more secure by introducing slight changes each iteration.
Parameters:
- password – The password to be secured
- passes – How many iterations this should run for
- expand – If the password should be able to get larger
Returns: The secured password
unload_dicts() -> None
Unloads all currently loaded dictionaries.
class aplustools.security.passwords.SecurePasswordGenerator(security: Literal['weak', 'average', 'strong', 'super_strong'])
Bases:
objectGenerates an always secure password that takes at least over one year to crack in the worst case (Verified by zxcvbn). This is also guaranteed if some of your passwords are already compromised as the password generation pattern is also entirely random.
The number of unique words for random sentence generation grows with the security settings (All duplicates are filtered out): - Weak: 10.027 words (random module for random number generation) - Average: 105.705 words (numpy.random module for random number generation) - Strong: 223.242 words (secrets module for random number generation) - Super Strong: 400.172 words (secrets module for random number generation)
__init__(security: Literal['weak', 'average', 'strong', 'super_strong'])
complex() -> dict[str, str]
Generate a complex password and return it with descriptive metadata.
This method calls generate_complex_password() and returns a dictionary containing the password and a short description of its randomness and complexity. :return: The password and generation info.
complex_pattern() -> dict[str, str]
A pattern password with uppercase letters, lowercase letters, numbers, words, and symbols. :return: The password and generation info.generate_secure_password(return_worst_case: bool = False) -> dict[str, str]
Generates always secure, always changing passwords that are designed to be human readable. The target worst time to crack is one century for each generated password.
Parameters: return_worst_case – Return the worst case estimate by zxcvbn Returns: mnemonic() -> dict[str, str]
Generate a simple, memorable (mnemonic) password.
This method generates a password using a common mnemonic pattern, typically involving an adjective and a noun (e.g., “BraveTiger42”). It returns the generated password along with descriptive information about the words used. :return: The password and generation info.
passphrase() -> dict[str, str]
Generate a secure, long passphrase based on a sentence.
This method creates a passphrase by selecting multiple words (typically from a wordlist) to form a human-readable but high-entropy sentence. It returns both the passphrase and an explanation of the sentence used to generate it. :return: The password and generation info.
pattern() -> dict[str, str]
Generate a password based on a randomized character pattern.
This method constructs a random password pattern by selecting 28 characters from the template set: /, X (uppercase), x (lowercase), 9 (digits), and -. It then passes this pattern to the pattern-based password generator to produce the final password. :return: The password and generation info.
random() -> dict[str, str]
Generate a fully random password with no specific pattern or structure.
This method delegates to the underlying generator to create a password composed of random characters from a general character set, with no guarantees on format or composition. :return: The password and generation info.
ratio() -> dict[str, str]
Generate a ratio-based password with explanatory context.
This method calls generate_ratio_based_password_v3 using its default parameters and returns the password along with a brief description indicating that the password was generated entirely at random based on character-type ratios. :return: The password and generation info.
sentence() -> dict[str, str]
Generate a sentence-based password with a randomized format and extra character.
This method constructs a password by: - Randomly selecting a special character. - Randomizing the order of the password components: words, special characters, extra character, and numbers. - Calling the sentence-based password generator with the selected character and format. :return: The password and generation info.
words() -> dict[str, str]
Generate a words-based password and return it with descriptive information.
This method generates a password by calling generate_words_based_password_v3 with _return_info=True, which returns both the password and the sentence used. The result includes a human-readable explanation of how the password was constructed. :return: The password and generation info.
class aplustools.security.passwords.SimplePasswordGenerator
Bases:
objectUsed to quickly generate a lot of passwords in minimal time
characters: str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
debug: bool = Falseclassmethod generate_complex_password(length: int = 12, filter_: PasswordFilter | None = None) -> str
Entirely random, a complex password.
Parameters:
- length – The length of the password
- filter – An optional password filter
Returns: The generated password
classmethod generate_custom_sentence_based_password_v2(sentence: str, char_position: Literal['random', 'keep'] | int = 'random', random_case: bool = False, extra_char: str = '', num_length: int = 0, special_chars_length: int = 0) -> str
A sentence based password, v2.
Parameters:
- sentence – The sentence to generate the password with, if this is not passed, a random sentence will be used.
- char_position – Which character in the word should be used in the password. You can also pass “random” for random and “keep” for keeping their position.
- random_case – If the case of characters in the final password should be randomized
- extra_char – Extra character part of the password
- num_length – The length of the numbers part of the password
- special_chars_length – The length of the punctuation part of the password
Returns: The generated password
classmethod generate_mnemonic_password(filter_: PasswordFilter | None = None) -> str
A mnemonic password using adjectives and nouns
Parameters: filter – An optional password filter Returns: classmethod generate_passphrase(words: list[str], num_words: int = 4, filter_: PasswordFilter | None = None) -> str
Passphrase, secure as it’s very long
Parameters:
- words – Which words to use in the passphrase
- num_words – The number of words to be used
- filter – An optional password filter
Returns: The generated password
classmethod generate_password(length: int = 12, filter_: PasswordFilter | None = None) -> str
Entirely random (uses the random module)
Parameters:
- length – The length of the password
- filter – An optional password filter
Returns: The generated password
classmethod generate_pattern_password(pattern: str = 'XXX-999-xxx', filter_: PasswordFilter | None = None) -> str
A pattern password X for an uppercase letter, x for a lowercase letter and 9 for a number. All other characters are ignored and included as is in the final password
Parameters:
- pattern – The pattern to generate the password by
- filter – An optional password filter
Returns: The generated password
classmethod generate_ratio_based_password(length: int = 12, letter_ratio: float = 0.4, digit_ratio: float = 0.3, symbol_ratio: float = 0.3, filter_: PasswordFilter | None = None) -> str
Generate a simple ratio based password
Parameters:
- length – The length of the password
- letter_ratio – The ratio of letters in the final password
- digit_ratio – The ratio of digits in the final password
- symbol_ratio – The ratio of symbols in the final password
- filter – An optional password filter
Returns: The generated password
classmethod generate_secure_password(length: int = 12, filter_: PasswordFilter | None = None) -> str
Entirely random (uses the secrets module)
Parameters:
- length – The length of the password
- filter – An optional password filter
Returns: The generated password
classmethod generate_sentence_based_password(structure: str = 'WwWn!') -> str
A sentence based password, using a structure. W means a capitalized word, w means a lowercase word, n means a digit and ! means a symbol.
Parameters: structure Returns: classmethod quick_secure_password(password: str, passes: int = 3, expand: bool = True) -> str
Quicker version of SpecificPasswordGenerator.secure_password
Parameters:
- password – The password to be secured
- passes – How many iterations this should run for
- expand – If the password should be able to get larger
Returns: The secured password
TBA
class aplustools.security.rand.ModularRandom
Bases:
objectclassmethod choice(seq: _SupportsLenAndGetItem) -> Any
Randomly choose a single element from a SupportsLenAndGetItem and returns the elementclassmethod choices(seq: _SupportsLenAndGetItem, k: int) -> Any
Randomly choose a k elements from a SupportsLenAndGetItem and returns the elements. Elements can be chosen more than onceclassmethod generate_random_string(length: int, char_set: str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~') -> str
classmethod randbelow(b: int) -> int
A uniform random value between 0 and b, inclusive, intclassmethod randint(a: int, b: int) -> int
A uniform random value between a and b, inclusive, intabstractmethod static random() -> float
The random method powering all others. Has to be implemented. float between 0 and 1, inclusiveclassmethod sample(s: list[Any], k: int) -> list[Any]
Samples k unique elements from s. Shuffels a copy of s and then takes the first k elements. Meaning it scales horribly for larger lists, but stays consistent no matter the amount of kclassmethod shuffle(s: list[Any]) -> None
Implements the fisher yates shuffle, works on the list, meaning no copyclassmethod string_sample(s: str, k: int) -> str
classmethod uniform(a: float, b: float) -> float
A uniform random value between a and b, inclusive, float
class aplustools.security.rand.NumPyRandom
Bases:
objectclassmethod betavariate(alpha: float, beta: float) -> float
classmethod binomialvariate(n: int, p: float) -> int
classmethod choice(seq: list[Any] | tuple[Any] | ndarray) -> Any
classmethod choices(seq: list[Any] | tuple[Any] | ndarray, k: int) -> list | tuple | ndarray
classmethod expovariate(lambd: float) -> float
classmethod gammavariate(alpha: float, beta: float) -> float
classmethod gauss(mu: float, sigma: float) -> float
classmethod lognormvariate(mean: float, sigma: float) -> float
classmethod normalvariate(mu: float, sigma: float) -> float
classmethod paretovariate(alpha: float) -> float
classmethod randbelow(b: int) -> int
classmethod randint(a: int, b: int) -> int
static random() -> float
classmethod sample(s: list, k: int) -> list
classmethod shuffle(s: list) -> None
classmethod uniform(a: float, b: float) -> float
classmethod vonmisesvariate(mu: float, kappa: float) -> float
classmethod weibullvariate(alpha: float, beta: float) -> float
class aplustools.security.rand.OSRandom
Bases: ModularRandom
static random() -> float
Return a random float from os.urandom
class aplustools.security.rand.SecretsRandom
Bases: ModularRandom
static random() -> float
Return a random float from secrets.randbits
aplustools.security.rand.generator(name: Literal['random', 'np_random', 'os', 'sys_random', 'secrets'] = 'sys_random') -> `ModularRandom <#aplustools.security.rand.ModularRandom>`_ | SystemRandom
TBA
class aplustools.security.EAN(value: Any, info: str)
Bases:
object__init__(value: Any, info: str) -> None
class aplustools.security.GenericLabeledEnum(new_class_name, /, names, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
Enum
label: str
value: Any
class aplustools.security.RiskLevel(*values)
Bases: GenericLabeledEnum
Risk assessment for various parts of security
HARMLESS = None
HIGHLY_DANGEROUS = None
KNOWN_UNSAFE = None
KNOWN_UNSAFE_NOT_RECOMMENDED = None
NOT_RECOMMENDED = None
class aplustools.security.Security
Bases:
objectBaseclass for different security levels
AVERAGE = A lot better than basic
BASIC = An attacker can reve ... fo on you pretty easily
STRONG = Practically impossible to reverse or crack
SUPER_STRONG = Great security, but ... dability and efficiency
check_not_available: bool = True
class aplustools.security.deprecated(message: str, /, *, category: ~typing.Type[Warning] | None = <class 'DeprecationWarning'>, stacklevel: int = 1)
Bases:
objectIndicate that a class, function or overload is deprecated.
When this decorator is applied to an object, the type checker will generate a diagnostic on usage of the deprecated object.
Usage:
@deprecated(“Use B instead”) class A:
pass@deprecated(“Use g instead”) def f():
pass@overload @deprecated(“int support is deprecated”) def g(x: int) -> int: … @overload def g(x: str) -> int: …
The warning specified by category will be emitted at runtime on use of deprecated objects. For functions, that happens on calls; for classes, on instantiation and on creation of subclasses. If the category is
None, no warning is emitted at runtime. The stacklevel determines where the warning is emitted. If it is1(the default), the warning is emitted at the direct caller of the deprecated object; if it is higher, it is emitted further up the stack. Static type checker behavior is not affected by the category and stacklevel arguments.The deprecation message passed to the decorator is saved in the
__deprecated__attribute on the decorated object. If applied to an overload, the decorator must be after the@overloaddecorator for the attribute to exist on the overload as returned byget_overloads().See PEP 702 for details.
__init__(message: str, /, *, category: ~typing.Type[Warning] | None = <class 'DeprecationWarning'>, stacklevel: int = 1) -> None