def __decrypt_generated_files(
        self, key_file: Path, generated_config_dir: Path, files: Iterable[str]
    ):
        """
        Decrypts the specified files in the generated configuration
        directory. The current encrypted version will be overwritten by the
        decrypted version.

        Args:
            key_file (Path): Key file to use when decrypting.
            generated_config_dir (Path): Path to the generated configuration directory.
            files (Iterable[str]): Relative path to the files to decrypt. Resolved against the generated configuration directory.
        """
        for relative_file in files:
            # decrypt and overwrite the file
            target_file = generated_config_dir.joinpath(relative_file)
            logger.debug("Decrypting [%s] ...", target_file)
            decrypt_values_in_file(target_file, target_file, key_file)
示例#2
0
def decrypt_file(encrypted_file: Path, key_file: Path) -> Path:
    """
    Decrypts the specified file using the supplied key.

    Args:
        encrypted_file (Path): File to decrypt.
        key_file (Path): Key to use for decryption.

    Returns:
        Path: Path to the decrypted file.
    """
    if not key_file.is_file():
        logger.info("No decryption key found. [%s] will not be decrypted.",
                    encrypted_file)
        return encrypted_file

    logger.debug("Decrypting file [%s] using [%s].", str(encrypted_file),
                 key_file)
    decrypted_file: Path = Path(NamedTemporaryFile(delete=False).name)
    crypto.decrypt_values_in_file(encrypted_file, decrypted_file, key_file)
    return decrypted_file
示例#3
0
def test_decrypt_values_in_file(tmpdir):
    key_file = Path(tmpdir, "key")
    crypto.create_and_save_key(key_file)
    cipher = Cipher(key_file)

    lines = [
        "a message to encrypt",
        "another message",
        "a repeated message",
    ]
    encrypted_lines = [cipher.encrypt(x) for x in lines]

    encrypted_file_text = f"""
        normal text
        {encrypted_lines[0]}
        {encrypted_lines[1]}
        {encrypted_lines[2]}
        {encrypted_lines[0]}:{encrypted_lines[1]}
        {encrypted_lines[0]}::{encrypted_lines[1]}@{encrypted_lines[2]}
        {encrypted_lines[0]}:{encrypted_lines[1]}enc:::end{encrypted_lines[2]}
    """
    expected_decrypted_text = f"""
        normal text
        {lines[0]}
        {lines[1]}
        {lines[2]}
        {lines[0]}:{lines[1]}
        {lines[0]}::{lines[1]}@{lines[2]}
        {lines[0]}:{lines[1]}enc:::end{lines[2]}
    """

    encrypted_file = Path(tmpdir, "encrypted")
    encrypted_file.write_text(encrypted_file_text)

    decrypted_file = Path(tmpdir, "decrypted")
    crypto.decrypt_values_in_file(encrypted_file, decrypted_file, key_file)
    decrypted_text = decrypted_file.read_text()

    assert expected_decrypted_text == decrypted_text