簡體   English   中英

PyCryptoDome版本3.6.6引發TypeError:對象類型 <class 'str'> 無法傳遞給C代碼

[英]PyCryptoDome Version 3.6.6 raises an TypeError: Object type <class 'str'> cannot be passed to C code

幾年前,我使用PyCryptoDome版本2.6.1在python中創建了一個密碼模塊。

現在,使用新的PyCryptoDome版本3.6.6和Python 3.6,我得到了具有相同代碼的TypeError。 在“ _init_crypter”中拋出錯誤-方法:

  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/AES.py", line 206, in new
    return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/__init__.py", line 79, in _create_cipher
    return modes[mode](factory, **kwargs)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/_mode_cbc.py", line 253, in _create_cbc_cipher
    return CbcMode(cipher_state, iv)
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Cipher/_mode_cbc.py", line 96, in __init__
    c_uint8_ptr(iv),
  File "/usr/local/lib/python3.6/dist-packages/Crypto/Util/_raw_api.py", line 196, in c_uint8_ptr
    raise TypeError("Object type %s cannot be passed to C code" % type(data))
TypeError: Object type <class 'str'> cannot be passed to C code

我怎樣才能解決這個問題!

兩個版本的我的代碼:

import os
from base64 import b64encode, b64decode
import hashlib
from Crypto.Cipher import Blowfish, AES


class Crypt:

    fileextension = ".enc"

    def __init__(self, crypter, key="", encoding="utf-8"):
        self._mode = -1
        self._encoding = encoding
        self._crypter = Blowfish
        self._blocksize = 8
        self._key_32byte = ""
        self._cryptographer = None

        self.set_crypter(crypter)
        if key:
            self.set_key(key)

    def _init_crypter(self):

        # self._key_32byte          <- set in set_key-method
        # self._mode = AES.MODE_CBC <- set in set_crypter-method
        # self._blocksize = 16      <- set in set_crypter-method

        self._cryptographer = self._crypter.new(
            self._key_32byte,
            self._mode,
            IV=self._blocksize * '\x00'
        )

    # and further code ...

key和IV參數必須是二進制類型( bytes ),而不是文本類型( str )。

如果要從文件加載密鑰,請確保以二進制模式打開它:

with open('keyfile', 'rb') as f:
    ...

如果您的密鑰是代碼中的文字,請確保它是二進制文字:

key = b'badbadbadkey'

最后,要構造您的IV參數,它必須是一個bytes序列。

例如:

>>> Blowfish.new(b'badbadbadkey', 2, IV=8 * b'\x00')
<Crypto.Cipher._mode_cbc.CbcMode object at 0x7f434187b8d0>

好吧-幾個小時后我明白了! 只有一個字母可以解決問題:'\\ x00'必須為b '\\ x00':

def _init_crypter(self):
    self._cryptographer = self._crypter.new(
        self._key_32byte,
        self._mode,
        IV=self._blocksize * b'\x00'
    )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM