对象类型<class'str'=“”>无法传递给C代码 - 虚拟环境

时间:2018-05-12 04:25:13

标签: python anaconda

我正在使用mac anaconda。我尝试使用加密的AES。但是,我面临一个奇怪的问题。

我只想执行一行简单的代码:

 obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')

如果我在没有虚拟环境的情况下运行代码,则可以。

$ python

Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more 
information.
>>> from Crypto.Cipher import AES

>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')

如果我使用虚拟环境&#34; testaes&#34;然后我收到了错误:

(testaes)$ python
Python 3.6.4 |Anaconda, Inc.| (default, Mar 12 2018, 20:05:31) 
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from Crypto.Cipher import AES

>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Applications/anaconda3/envs/testaes/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 200, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "/Applications/anaconda3/envs/testaes/lib/python3.6/site-packages/Crypto/Cipher/__init__.py", line 55, in _create_cipher
return modes[mode](factory, **kwargs)
File "/Applications/anaconda3/envs/testaes/lib/python3.6/site-packages/Crypto/Cipher/_mode_cbc.py", line 234, in _create_cbc_cipher
cipher_state = factory._create_base_cipher(kwargs)
File "/Applications/anaconda3/envs/testaes/lib/python3.6/site-packages/Crypto/Cipher/AES.py", line 100, in _create_base_cipher
result = start_operation(c_uint8_ptr(key),
File "/Applications/anaconda3/envs/testaes/lib/python3.6/site-packages/Crypto/Util/_raw_api.py", line 109, 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

你可以看到我同时使用相同的anaconda python 3.6.4和GCC4.2.1。怎么解决这个?谢谢。

2 个答案:

答案 0 :(得分:11)

在Python 3中,将其编码为bytearray

obj = AES.new('This is a key123'.encode("utf8"), AES.MODE_CBC, 'This is an IV456'.encode("utf8"))

如果将它们存储在变量中并希望再次将它们用作(python)字符串,只需使用:

key_as_bytearray.decode("utf8")

查看this answer以获取更多信息。

答案 1 :(得分:-3)

Python有一个名为pycryptodome的软件包,会导致此错误。只需卸载该软件包

sudo pip3卸载pycryptodome