Boto3文件上传到S3 Bucket的SHA256校验失败



我正在尝试上传文件到S3 Bucket。我正在计算我的代码中的SHA256校验和,并将其传递给put_object方法,以确保上传文件的完整性。

然而,当我这样做时,我得到一个错误botocore.exceptions.ClientError: An error occurred (InvalidRequest) when calling the PutObject operation: Value for x-amz-checksum-sha256 header is invalid.

下面的代码片段是我如何在我的python代码中计算校验和:

def checksum_sha256(filename):
""" Calculates SHA256 Checksum for specified filename
"""
sha256_hash = hashlib.sha256()
with open(filename, "rb") as f:
for byte_block in iter(lambda: f.read(8192), b""):
sha256_hash.update(byte_block)
return str(b64encode(bytes(sha256_hash.hexdigest(), "utf-8")))

下面的代码片段显示了如何使用Boto3 S3 Client将文件上传到S3:

checksum = checksum_sha256(file_location)
client = boto3.client("s3")
with open(file_location, 'rb') as file_obj:
response = client.put_object(Body=file_obj, Bucket=bucket, Key=target_file_name,
ChecksumAlgorithm='SHA256',
ChecksumSHA256=checksum)

这会导致以下错误:

botocore.exceptions.ClientError: An error occurred (InvalidRequest) when calling the PutObject operation: Value for x-amz-checksum-sha256 header is invalid.

我不能精确地指出我在哪里出错了。任何帮助都是感激的。谢谢。

我发现对校验和计算的以下更改修复了错误:

def checksum_sha256(filename):
""" Calculates SHA256 Checksum for specified filename
"""
sha256_hash = hashlib.sha256()
with open(filename, "rb") as f:
# Read and update hash string value in blocks of 8K
for byte_block in iter(lambda: f.read(8192), b""):
sha256_hash.update(byte_block)
return b64encode(sha256_hash.digest()).decode()

最新更新