我正在使用pycrypto的RSA类:
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
message = 'To be encrypted'
key = RSA.generate(2048)
cipher = PKCS1_v1_5.new(key)
ciphertext = cipher.encrypt(message)
代码运行正常,我能解密密文。然而,我需要能够序列化这些密码。我没有任何问题pickle
-ing其他pyCrypto密码,如AES,但当我尝试pickle
RSA密码时,我遇到以下错误:
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import pickle
message = 'To be encrypted'
key = RSA.generate(2048)
cipher = PKCS1_v1_5.new(key)
pickle.dump(cipher, open("cipher.temp", "wb"))
cipher = pickle.load(open("cipher.temp", "rb"))
ciphertext = cipher.encrypt(message)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Crypto/Cipher/PKCS1_v1_5.py", line 119, in encrypt
randFunc = self._key._randfunc
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 126, in __getattr__
raise AttributeError("%s object has no %r attribute" % (self.__class__.__name__, attrname,))
AttributeError: _RSAobj object has no '_randfunc' attribute
我能做些什么来解决这个问题——另一个序列化框架,RSA对象的不同构造方法,等等,或者这只是一个不支持pickle
的对象?
pickle对于公钥组件工作得很好,但是当涉及到整个密钥时,_randfunc无法在pickle中存活。我在做一个项目的时候也遇到过同样的错误。您可以在这里查看更多信息:https://github.com/google/oauth2client/issues/638
使用PyCrypto的importKey和exportKey函数,它们的文档可以在这里找到:https://www.dlitz.net/software/pycrypto/api/2.6/