【问题标题】:Using AES Encrypt get raise TypeError("Only byte strings can be passed to C code")Using AES Encrypt get raise TypeError("Only byte strings can be passed to C code")
【发布时间】:2017-09-05 10:27:29
【问题描述】:

我尝试用 python 加密文本然后我执行我的代码我得到一个错误:

import base64

import boto3
from Crypto.Cipher import AES


PAD = lambda s: s + (32 - len(s) % 32) * ' '


def get_arn(aws_data):
    return 'arn:aws:kms:{region}:{account_number}:key/{key_id}'.format(**aws_data)


def encrypt_data(aws_data, plaintext_message):
    kms_client = boto3.client(
        'kms',
        region_name=aws_data['region'])

    data_key = kms_client.generate_data_key(
        KeyId=aws_data['key_id'],
        KeySpec='AES_256')

    cipher_text_blob = data_key.get('CiphertextBlob')
    plaintext_key = data_key.get('Plaintext')

    # Note, does not use IV or specify mode... for demo purposes only.
    cypher = AES.new(plaintext_key, AES.MODE_ECB)
    encrypted_data = base64.b64encode(cypher.encrypt(PAD(plaintext_message)))

    # Need to preserve both of these data elements
    return encrypted_data, cipher_text_blob



def main():
    # Add your account number / region / KMS Key ID here.
    aws_data = {
        'region': 'eu-west-1',
        'account_number': '701177775058',
        'key_id': 'd67e033d-83ac-4b5e-93d4-aa6cdc3e292e',
    }

    # And your super secret message to envelope encrypt...
    plaintext = PAD('Hello, World!')

    # Store encrypted_data & cipher_text_blob in your persistent storage. You will need them both later.
    encrypted_data, cipher_text_blob = encrypt_data(aws_data, plaintext)
    print(encrypted_data)


if __name__ == '__main__':
    main()

i Get : raise TypeError("只有字节字符串可以传递给 C 代码") TypeError:只能将字节字符串传递给 C 代码 也许谁知道为什么?我该如何解决?请推荐!

【问题讨论】:

  • 也许cypher.encrypt 需要一个字节对象? cypher.encrypt(PAD(plaintext_message).encode("utf-8"))。没有完整的追溯很难说。
  • 天啊!!它有效:真的吗?真的这个小想像“编码”很重要吗?谢谢!!!

标签: python python-3.x amazon-web-services encryption aes


【解决方案1】:

在这里写@Jeronimo的评论作为答案,我也遇到了同样的问题,这很有帮助。

.encode("utf-8") 附加到您传递给cypher.encrypt() 函数的任何内容。

cypher.encrypt(PAD(plaintext_message).encode("utf-8"))

注意:这似乎适用于 python 3.x。对于 2.x,同样的解决方案可能不起作用。

【讨论】:

    猜你喜欢
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 2022-12-01
    • 2014-07-31
    相关资源
    最近更新 更多