Python中aws_encryption_sdk解密返回字符串与原明文不一致问题
问题根因
- Python 版本的 AWS Encryption SDK 加解密接口默认处理字节(bytes)类型数据,你传入字符串明文时,SDK 会隐式将字符串转为字节,但解密返回的结果固定为字节类型,直接输出会携带
b''格式标记,和原始字符串对比会被误认为是多余字符,甚至断言会直接失败。 - 你之前使用的 Java 版本 SDK 不存在这个问题,是因为 Java 中字符串和字节数组是完全独立的类型,你在使用时会手动完成字符串到字节数组的编码、解密后字节数组到字符串的解码操作,不会出现隐式类型转换带来的差异。
修复方案
调整代码,显式处理字符串和字节的编解码即可,修改后代码如下:
import aws_encryption_sdk from aws_encryption_sdk import CommitmentPolicy import botocore.session import base64 def cycle_string(key_arn, source_plaintext, botocore_session=None): client = aws_encryption_sdk.EncryptionSDKClient(commitment_policy=CommitmentPolicy.REQUIRE_ENCRYPT_REQUIRE_DECRYPT) kms_kwargs = dict(key_ids=[key_arn]) if botocore_session is not None: kms_kwargs["botocore_session"] = botocore_session master_key_provider = aws_encryption_sdk.StrictAwsKmsMasterKeyProvider(**kms_kwargs) # 加密前显式将字符串编码为utf-8字节 plaintext_bytes = source_plaintext.encode('utf-8') ciphertext, encryptor_header = client.encrypt(source=plaintext_bytes, key_provider=master_key_provider) encrrtext=base64.b64encode(ciphertext) encrciphertext=base64.b64decode(encrrtext) cycled_plaintext_bytes, decrypted_header = client.decrypt(source=encrciphertext, key_provider=master_key_provider) # 解密后显式将字节解码为字符串 cycled_plaintext = cycled_plaintext_bytes.decode('utf-8') print(encrrtext) print(cycled_plaintext) print(source_plaintext) # 验证解密后的字符串和原始字符串完全一致 assert cycled_plaintext == source_plaintext assert all( pair in decrypted_header.encryption_context.items() for pair in encryptor_header.encryption_context.items() ) plaintext = "hello there" cmk_arn = "<arn>" cycle_string(key_arn=cmk_arn, source_plaintext=plaintext, botocore_session=botocore.session.Session())
修改后解密输出的字符串会和原始明文完全一致,断言也能正常通过。
内容的提问来源于stack exchange,提问作者Rajesh Kumar Dash
相关产品推荐
相关产品推荐

