Python解密S3图像文件,用CSE-KM加密

2024-06-23 19:45:35 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以解密Python中的jpg或png文件,这些文件使用JAVA-AmazonS3EncryptionClient加密CSE-KMS并存储在S3中?看起来boto3和aws ecryption客户端只支持密码文本,而不支持文件。在

我试过下面的代码但是失败了

def get_decrypted_stream(s3_object):
  region_name = 'us-east-1'
  encryptedImageBytes = s3_object.get()['Body'].read() 
  print("Decoded file : {}".format(encryptedImageBytes))

  client = boto3.client('kms', region_name=region_name)
  response = client.decrypt( CiphertextBlob=encryptedImageBytes)

  data = meta[u'Plaintext']
  return io.BytesIO(data)

错误:

它失败了“客户端.解密(CiphertextBlob=encryptedImage)“with{“errorMessage”:“调用解密操作时发生错误(413):HTTP内容长度超过200000字节。”,“errorType”:“ClientError”,}

参考文献: https://docs.aws.amazon.com/kms/latest/APIReference/API_Decrypt.htmlhttps://github.com/aws/aws-encryption-sdk-python/https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/python-example-code.htmlhttps://aws-encryption-sdk-python.readthedocs.io/en/latest/


Tags: 文件namecomclientaws客户端getobject
1条回答
网友
1楼 · 发布于 2024-06-23 19:45:35

根据您共享的文档,Encrypt和{}API的最大负载限制为4k:https://docs.aws.amazon.com/kms/latest/APIReference/API_Encrypt.html

当使用KMS密钥对文件进行编码时,其原理是生成一个符号密钥,用符号密钥对有效负载进行编码,用KMSencryptAPI对符号密钥进行编码,并将加密的符号密钥存储在信封中,例如在S3上作为元数据。在

以下是S3文件加密的代码示例:

    #
    # Generate a Data Key (encoded with my Master Key in KMS)
    #
    key = kms.generate_data_key(KeyId=MASTER_KEY_ARN,KeySpec='AES_256')
    keyPlain  = key['Plaintext']
    keyCipher = key['CiphertextBlob']

    #
    # Encode a file with the data key
    #
    print ("Initializing encryption engine")
    iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
    chunksize = 64*1024
    encryptor = AES.new(keyPlain, AES.MODE_CBC, iv)

    print ("KMS Plain text key = %s " % base64.b64encode(keyPlain))
    print ("KMS Encrypted key  = %s " % base64.b64encode(keyCipher))

    in_filename = os.path.join(DIRECTORY, FILENAME)
    out_filename = in_filename + '.enc'
    filesize = os.path.getsize(in_filename)

    print ("Encrypting file")
    with open(in_filename, 'rb') as infile:
        with open(out_filename, 'wb') as outfile:
            outfile.write(struct.pack('<Q', filesize))
            outfile.write(iv)

            chunk = infile.read(chunksize)
            while len(chunk) != 0:
                if len(chunk) % 16 != 0:
                    chunk += ' ' * (16 - len(chunk) % 16)
                outfile.write(encryptor.encrypt(chunk))
                chunk = infile.read(chunksize)

    #
    # Store encrypted file on S3
    # Encrypted Key will be stored as meta data
    #
    print ("Storing encrypted file on S3")
    metadata = {
        "key" : base64.b64encode(keyCipher)
    }

    #client = boto3.client('s3', 'us-west-2')
    s3 = session.client('s3')
    transfer = S3Transfer(s3)
    transfer.upload_file(out_filename, S3_BUCKET, out_filename, extra_args={"Metadata" : metadata})
    os.remove(out_filename)

以及要解密的示例代码:

^{pr2}$

相关问题 更多 >

    热门问题