Crypto库是否不支持python3?

我在使用python3运行代码时,因为用到了Crypto库,会出现报错提示.

用到的函数

# 登录接口data
def get_login_data_inputPostString(post_string):
    random_generator = Random.new().read
    rsa = RSA.generate(2048, random_generator)

    post_string["rocket"] = str(gen_random_string(39))

    post_string = str(post_string)
    # 生成随机16位aes密钥
    aes_key = gen_random_string(16)

    # aes加密方法一
    BS = 16
    pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

    def aes_encrypt(raw):
        raw = pad(raw)
        #        iv = Random.new().read(AES.block_size);
        iv = "PCNXSJYHJSNXSJYH"
        cipher = AES.new(aes_key, AES.MODE_CBC, iv)
        return base64.b64encode(cipher.encrypt(raw))

    str2 = aes_encrypt(post_string)

    # ----  rsa加密ase密钥 --------
    with open('rsa_public_key.pem') as f:
        key = f.read()
        rsakey = RSA.importKey(key)
        cipher = Cipher_pkcs1_v1_5.new(rsakey)
        # ↓↓↓↓↓↓↓↓ 报错的代码行
        cipher_text = base64.b64encode(cipher.encrypt(aes_key))   
        str1 = cipher_text

    # 生成 "str1#str2#ebank123"
    sum = str1 + "#" + str2 + "#" + "ebank332211"

    m = hashlib.md5()
    m.update(sum)
    str3 = m.hexdigest()

    # 生成最终数据
    data = str3 + "#" + str1 + "#" + str2

    return data

报错信息:

Traceback (most recent call last):
  File "de_test.py", line 100, in <module>
    get_login_data_inputPostString(post_string)
  File "de_test.py", line 81, in get_login_data_inputPostString
    cipher_text = base64.b64encode(cipher.encrypt(aes_key))
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/Crypto/Cipher/PKCS1_v1_5.py", line 137, in encrypt
    em = b('\x00\x02') + ps + bchr(0x00) + message
TypeError: can't concat str to bytes

看报错信息貌似是个库自身报错,是因为这个库不支持python3吗?

我用python2.7的话不会报错.

阅读 4.8k
2 个回答

时隔20天,终于解决了:
报错那行代码改成:
pad = lambda s: (s + ((BS - len(s) % BS) * chr(BS - len(s) % BS))).encode(encoding="utf-8")
另外还有几个类型报错的简单改一下就行了,类似:
sum = sum.encode(encoding="utf-8")
使用的框架从python2升级到python3好痛苦啊 . = =

TypeError: can't concat str to bytes

确定没问题吗?
据我所知,py3 和py2 在文字编码和处理字符串有差别,
py3 str类,py2 byte类。
有可能python2 执行的时候,crypto和py2都对字符串以byte处理, 单在py3执行时候,就出现str与byte的typeerror了。
应该可以透过类型转换解决。
我猜的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题