2020-02-14 14:19:48 +00:00
|
|
|
"""Wrappers to de/encode and de/inflate strings"""
|
|
|
|
import base64
|
|
|
|
import zlib
|
|
|
|
|
2020-11-12 21:31:50 +00:00
|
|
|
PEM_HEADER = "-----BEGIN CERTIFICATE-----"
|
|
|
|
PEM_FOOTER = "-----END CERTIFICATE-----"
|
|
|
|
|
2020-02-14 14:19:48 +00:00
|
|
|
|
2020-02-20 20:33:10 +00:00
|
|
|
def decode_base64_and_inflate(encoded: str, encoding="utf-8") -> str:
|
2020-02-14 14:19:48 +00:00
|
|
|
"""Base64 decode and ZLib decompress b64string"""
|
2020-02-20 20:33:10 +00:00
|
|
|
decoded_data = base64.b64decode(encoded)
|
2020-02-16 13:08:35 +00:00
|
|
|
try:
|
2020-02-20 20:33:10 +00:00
|
|
|
return zlib.decompress(decoded_data, -15).decode(encoding)
|
2020-02-16 13:08:35 +00:00
|
|
|
except zlib.error:
|
2020-02-20 20:33:10 +00:00
|
|
|
return decoded_data.decode(encoding)
|
2020-02-14 14:19:48 +00:00
|
|
|
|
|
|
|
|
2020-07-10 23:02:55 +00:00
|
|
|
def deflate_and_base64_encode(inflated: str, encoding="utf-8"):
|
2020-02-14 14:19:48 +00:00
|
|
|
"""Base64 and ZLib Compress b64string"""
|
2020-07-10 23:02:55 +00:00
|
|
|
zlibbed_str = zlib.compress(inflated.encode())
|
2020-02-14 14:19:48 +00:00
|
|
|
compressed_string = zlibbed_str[2:-4]
|
2020-02-20 20:33:10 +00:00
|
|
|
return base64.b64encode(compressed_string).decode(encoding)
|
2020-02-14 14:19:48 +00:00
|
|
|
|
|
|
|
|
2020-07-12 15:55:09 +00:00
|
|
|
def nice64(src: str) -> str:
|
2020-06-24 11:12:34 +00:00
|
|
|
"""Returns src base64-encoded and formatted nicely for our XML. """
|
2020-07-12 15:55:09 +00:00
|
|
|
return base64.b64encode(src.encode()).decode("utf-8").replace("\n", "")
|
2020-11-12 21:31:50 +00:00
|
|
|
|
|
|
|
|
|
|
|
def strip_pem_header(cert: str) -> str:
|
|
|
|
"""Remove PEM Headers"""
|
|
|
|
return cert.replace(PEM_HEADER, "").replace(PEM_FOOTER, "").replace("\n", "")
|