可以使用以下 Python 代码,使用 aws-encryption-cli 加密文件时避免加入换行符:
import subprocess
def encrypt_with_aws_encryption_cli(src_file, dst_file, key_id, region):
command = [
"aws", "encryption", "cli",
"encrypt",
"--input", src_file,
"--output", dst_file,
"--encryption-context", f"key_id={key_id}",
"--region", region,
"--metadata-output", "-"
]
result = subprocess.run(command, capture_output=True)
if result.returncode != 0:
raise RuntimeError(result.stderr.decode("utf-8"))
metadata = result.stdout.decode("utf-8").strip().split("\n")
metadata = "\n".join([line for line in metadata if not line.startswith("x-amz-iv")])
return metadata
该函数从 Python 调用 aws-encryption-cli 工具来进行文件加密。在调用中添加 --metadata-output
参数将元数据输出到标准输出。这个元数据包含有用的信息,例如加密所用的算法和密钥 ID。在元数据中,有一行以 x-amz-iv
开头的行包含随机初始化向量(IV),而其他行包含加密上下文。我们使用 Python 函数的 split()
方法从字符串中分离行,并只保留不包含 x-amz-iv
的行。最后,我们使用 join()
方法将这些行组合在一起,以便作为函数的返回值返回。