AAS HTTP Client Documentation
Loading...
Searching...
No Matches
encoder.py
Go to the documentation of this file.
1"""Encoder module.
2
3Provides some helper methods for base 64 encoding.
4"""
5
6import base64
7import binascii
8
9
10def decode_base_64(text: str) -> str:
11 """Decode a Base64 encoded string.
12
13 :param text: Base64 encoded string to decode
14 :return: Decoded string
15 """
16 missing_padding = len(text) % 4
17 if missing_padding:
18 text += "=" * (4 - missing_padding)
19
20 decoded = base64.urlsafe_b64decode(text)
21 return decoded.decode("utf-8")
22
23
24def encode_base_64(text: str, add_padding: bool = False) -> str:
25 """Encode a string to Base64.
26
27 :param text: String to encode
28 :param add_padding: Whether to add padding to the encoded string
29 :return: Base64 encoded string
30 """
31 encoded_bytes = base64.urlsafe_b64encode(text.encode("utf-8"))
32
33 if not add_padding:
34 encoded_bytes = encoded_bytes.rstrip(b"=")
35
36 return encoded_bytes.decode("utf-8")
37
38
39def is_base_64_encoded(value: str) -> bool:
40 """Check if a string is Base64 encoded.
41
42 :param value: String to check
43 :return: True if the string is Base64 encoded, False otherwise
44 """
45 try:
46 decoded = decode_base_64(value)
47 except (binascii.Error, ValueError):
48 return False
49
50 return encode_base_64(decoded) == value
str decode_base_64(str text)
Decode a Base64 encoded string.
Definition encoder.py:15
bool is_base_64_encoded(str value)
Check if a string is Base64 encoded.
Definition encoder.py:44