Skip to content

Utils

blake2signer.utils

Miscellaneous utilities.

b32decode(data)

Decode data encoded as Base 32 without padding.

Parameters:

Name Type Description Default
data bytes

Data to decode.

required

Returns:

Type Description
bytes

Original data.

Source code in blake2signer/utils.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
def b32decode(data: bytes) -> bytes:
    """Decode data encoded as Base 32 without padding.

    Args:
        data: Data to decode.

    Returns:
        Original data.
    """
    return base64.b32decode(data + (b'=' * ((8 - (len(data) % 8)) % 8)))

b32encode(data)

Encode data as Base 32, stripping padding.

Parameters:

Name Type Description Default
data bytes

Data to encode.

required

Returns:

Type Description
bytes

Encoded data.

Source code in blake2signer/utils.py
81
82
83
84
85
86
87
88
89
90
def b32encode(data: bytes) -> bytes:
    """Encode data as Base 32, stripping padding.

    Args:
        data: Data to encode.

    Returns:
        Encoded data.
    """
    return base64.b32encode(data).rstrip(b'=')

b58decode(data)

Decode data encoded as Base 58.

Parameters:

Name Type Description Default
data bytes

Data to decode.

required

Returns:

Type Description
bytes

Original data.

Source code in blake2signer/utils.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def b58decode(data: bytes) -> bytes:
    """Decode data encoded as Base 58.

    Args:
        data: Data to decode.

    Returns:
        Original data.
    """
    scrubbed_data = data.lstrip(B58_ALPHABET[0:1])
    char_to_index = _b58_char_to_index_map()
    base = len(B58_ALPHABET)
    num = 0
    for char in scrubbed_data:
        num = num * base + char_to_index[char]

    number_of_leading_zeroes = len(data) - len(scrubbed_data)
    decoded = num.to_bytes(number_of_leading_zeroes + (num.bit_length() + 7) // 8, 'big')

    return decoded

b58encode(data)

Encode data as Base 58.

Base 58 has no padding, and it contains characters from a-z (except l), A-Z (except I and O), and numbers 1-9, to improve readability and reduce transcription errors.

Parameters:

Name Type Description Default
data bytes

Data to encode.

required

Returns:

Type Description
bytes

Encoded data.

Source code in blake2signer/utils.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
def b58encode(data: bytes) -> bytes:
    """Encode data as Base 58.

    Base 58 has no padding, and it contains characters from a-z (except l), A-Z (except I and O),
    and numbers 1-9, to improve readability and reduce transcription errors.

    Args:
        data: Data to encode.

    Returns:
        Encoded data.
    """
    scrubbed_data = data.lstrip(b'\x00')
    num = int.from_bytes(scrubbed_data, 'big')
    base = len(B58_ALPHABET)
    encoded = []

    while num > 0:
        num, rem = divmod(num, base)
        encoded.append(B58_ALPHABET[rem:rem + 1])

    encoded.reverse()

    leading_zeroes_as_first_char = B58_ALPHABET[0:1] * (len(data) - len(scrubbed_data))

    return leading_zeroes_as_first_char + b''.join(encoded)

b64decode(data)

Decode data encoded as Base 64 URL-safe without padding.

Parameters:

Name Type Description Default
data bytes

Data to decode.

required

Returns:

Type Description
bytes

Original data.

Source code in blake2signer/utils.py
69
70
71
72
73
74
75
76
77
78
def b64decode(data: bytes) -> bytes:
    """Decode data encoded as Base 64 URL-safe without padding.

    Args:
        data: Data to decode.

    Returns:
        Original data.
    """
    return base64.urlsafe_b64decode(data + (b'=' * (len(data) % 4)))

b64encode(data)

Encode data as Base 64 URL-safe, stripping padding.

Parameters:

Name Type Description Default
data bytes

Data to encode.

required

Returns:

Type Description
bytes

Encoded data.

Source code in blake2signer/utils.py
57
58
59
60
61
62
63
64
65
66
def b64encode(data: bytes) -> bytes:
    """Encode data as Base 64 URL-safe, stripping padding.

    Args:
        data: Data to encode.

    Returns:
        Encoded data.
    """
    return base64.urlsafe_b64encode(data).rstrip(b'=')

file_mode_is_text(file)

Check if a given file is opened in text mode, or otherwise in binary mode.

Parameters:

Name Type Description Default
file IO[AnyStr]

File to check its mode.

required

Returns:

Type Description
bool

True if file is opened in text mode, False otherwise.

Source code in blake2signer/utils.py
199
200
201
202
203
204
205
206
207
208
def file_mode_is_text(file: t.IO[t.AnyStr]) -> bool:
    """Check if a given file is opened in text mode, or otherwise in binary mode.

    Args:
        file: File to check its mode.

    Returns:
        True if file is opened in text mode, False otherwise.
    """
    return isinstance(file, io.TextIOBase)

force_bytes(value)

Force a given value into bytes.

Parameters:

Name Type Description Default
value Union[str, bytes]

Value to convert to bytes.

required

Returns:

Type Description
bytes

Converted value into bytes.

Raises:

Type Description
TypeError

Value is neither bytes nor string.

Source code in blake2signer/utils.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
def force_bytes(value: t.Union[str, bytes]) -> bytes:
    """Force a given value into bytes.

    Args:
        value: Value to convert to bytes.

    Returns:
        Converted value into bytes.

    Raises:
        TypeError: Value is neither bytes nor string.
    """
    if isinstance(value, bytes):
        return value

    if isinstance(value, str):
        return value.encode('utf-8', errors='strict')

    raise TypeError('value must be bytes or str')

force_string(value)

Force a given value into string.

Parameters:

Name Type Description Default
value Union[str, bytes]

Value to convert to string.

required

Returns:

Type Description
str

Converted value into string.

Raises:

Type Description
TypeError

Value is neither bytes nor string.

Source code in blake2signer/utils.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def force_string(value: t.Union[str, bytes]) -> str:
    """Force a given value into string.

    Args:
        value: Value to convert to string.

    Returns:
        Converted value into string.

    Raises:
        TypeError: Value is neither bytes nor string.
    """
    if isinstance(value, str):
        return value

    if isinstance(value, bytes):
        return value.decode('utf-8', errors='strict')

    raise TypeError('value must be bytes or str')

generate_secret()

Generate a secure, pseudo-random value for use as a secret.

Store the value generated by this function in your environment file, or secrets manager.

Returns:

Type Description
str

A secure, pseudo-random value for use as a secret.

Source code in blake2signer/utils.py
242
243
244
245
246
247
248
249
250
def generate_secret() -> str:
    """Generate a secure, pseudo-random value for use as a secret.

    Store the value generated by this function in your environment file, or secrets manager.

    Returns:
        A secure, pseudo-random value for use as a secret.
    """
    return b58encode(token_bytes(64)).decode()

get_current_time()

Return the current time in seconds since the Epoch.

Source code in blake2signer/utils.py
237
238
239
def get_current_time() -> float:
    """Return the current time in seconds since the Epoch."""
    return time()

hexdecode(data)

Decode data encoded as hexadecimal (uppercase).

Parameters:

Name Type Description Default
data bytes

Data to decode.

required

Returns:

Type Description
bytes

Original data.

Source code in blake2signer/utils.py
117
118
119
120
121
122
123
124
125
126
def hexdecode(data: bytes) -> bytes:
    """Decode data encoded as hexadecimal (uppercase).

    Args:
        data: Data to decode.

    Returns:
        Original data.
    """
    return base64.b16decode(data)

hexencode(data)

Encode data as hexadecimal (uppercase).

Parameters:

Name Type Description Default
data bytes

Data to encode.

required

Returns:

Type Description
bytes

Encoded data.

Source code in blake2signer/utils.py
105
106
107
108
109
110
111
112
113
114
def hexencode(data: bytes) -> bytes:
    """Encode data as hexadecimal (uppercase).

    Args:
        data: Data to encode.

    Returns:
        Encoded data.
    """
    return base64.b16encode(data)

ordinal(number)

Convert an integer into its ordinal representation.

Parameters:

Name Type Description Default
number int

Integer number to get its ordinal representation.

required

Returns:

Type Description
str

The ordinal string representation of the number as the number + ordinal suffix.

Examples:

>>> ordinal(0)
'0th'
>>> ordinal(3)
'3rd'
Source code in blake2signer/utils.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
def ordinal(number: int) -> str:
    """Convert an integer into its ordinal representation.

    Args:
        number: Integer number to get its ordinal representation.

    Returns:
        The ordinal string representation of the number as the number + ordinal suffix.

    Examples:
        >>> ordinal(0)
        '0th'
        >>> ordinal(3)
        '3rd'
    """
    # From https://stackoverflow.com/a/50992575
    if 11 <= (number % 100) <= 13:
        suffix = 'th'
    else:
        suffixes = ('th', 'st', 'nd', 'rd', 'th')
        idx = min(number % 10, 4)
        suffix = suffixes[idx]

    return f'{number}{suffix}'

timestamp_to_aware_datetime(timestamp)

Convert a UNIX timestamp into an aware datetime in UTC.

Parameters:

Name Type Description Default
timestamp Union[int, float]

UNIX timestamp to convert.

required

Returns:

Type Description
datetime

Converted timestamp into an aware datetime in UTC.

Source code in blake2signer/utils.py
187
188
189
190
191
192
193
194
195
196
def timestamp_to_aware_datetime(timestamp: t.Union[int, float]) -> datetime:
    """Convert a UNIX timestamp into an aware datetime in UTC.

    Args:
        timestamp: UNIX timestamp to convert.

    Returns:
        Converted timestamp into an aware datetime in UTC.
    """
    return datetime.fromtimestamp(timestamp, tz=timezone.utc)