def encode_and_pad(data: str, to_length: int) -> bytes:
    """
    Encodes as utf-8 and pads the given data sequence to the given length with
        null characters.

    Padding is to preserve the IND-CPA of messages of different lengths, by
        making sure to pad to a common length.
    """
    encoded = data.encode("utf-8")
    if to_length is None:
        return encoded
    if len(encoded) > to_length:
        raise ValueError(
            "Cannot pad data of length {} to size {}".format(len(encoded), to_length)
        )
    return encoded + b"\0" * (to_length - len(encoded))