diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index f5c796ef46d..f10913c2478 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2397,14 +2397,18 @@ def struct_unpack(value: bytes, format_string: str, offset: int = 0) -> Any | No return None -def base64_encode(value): +def base64_encode(value: str) -> str: """Perform base64 encode.""" return base64.b64encode(value.encode("utf-8")).decode("utf-8") -def base64_decode(value): - """Perform base64 denode.""" - return base64.b64decode(value).decode("utf-8") +def base64_decode(value: str, encoding: str | None = "utf-8") -> str | bytes: + """Perform base64 decode.""" + decoded = base64.b64decode(value) + if encoding: + return decoded.decode(encoding) + + return decoded def ordinal(value): diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 71e1bc748a6..3d8dad1d23e 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1643,6 +1643,18 @@ def test_base64_decode(hass: HomeAssistant) -> None: ).async_render() == "homeassistant" ) + assert ( + template.Template( + '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode(None) }}', hass + ).async_render() + == b"homeassistant" + ) + assert ( + template.Template( + '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode("ascii") }}', hass + ).async_render() + == "homeassistant" + ) def test_slugify(hass: HomeAssistant) -> None: