0

I'm working with pyCrpyto's RSA class:

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)

That code runs fine, and I'm able to decrypt the ciphertext. However, I need to be able to serialize these ciphers. I haven't had any problem pickle-ing other pyCrypto ciphers, like AES, but when I try to pickle an RSA cipher I run into the following error:

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

Is there anything I can do to get around this -- another serialization framework, a different construction method for the RSA object, etc., or is this just an un-pickle-able object?

bkaiser
  • 647
  • 8
  • 22
  • You'd have to serialize the keys that are behind such an object. PyCrypto provides you with functions to export the keys and import them. Have you tried those? – Artjom B. Aug 23 '16 at 20:20
  • @ArtjomB. I'll try it, but I was hoping to be able to serialize the cipher into a single file. You're suggesting I just serialize the key (using PyCrypto's export, not pickle) and then reconstruct the cipher by importing it? – bkaiser Aug 23 '16 at 21:01

1 Answers1

0

Pickling works fine for the public key component, but when it comes to the whole key, the _randfunc doesn't survive pickling. I had come across the same error when working on a project. You can fine more information here: https://github.com/google/oauth2client/issues/638

Make use of PyCrypto's importKey and exportKey functions, whose documentation can be found here: https://www.dlitz.net/software/pycrypto/api/2.6/

Nir_J
  • 133
  • 1
  • 3
  • 7