繁体   English   中英

Boto3 文件上传到 S3 Bucket 未通过 SHA256 校验和检查

[英]Boto3 file upload to S3 Bucket is failing SHA256 checksum check

我正在尝试将文件上传到 S3 存储桶。 我在我的代码中计算 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 客户端将文件上传到 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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM