From 4bc9733b78cd115a742b9486ab11ccbdcb9ca001 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Fri, 22 Jan 2016 15:41:40 +0100 Subject: Fix #12 Allow pickling of keys. Pickling is now possible, with the added note that one should never unpickle from an untrusted or unauthenticated source. --- rsa/key.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) (limited to 'rsa/key.py') diff --git a/rsa/key.py b/rsa/key.py index c70db9a..6014709 100644 --- a/rsa/key.py +++ b/rsa/key.py @@ -23,6 +23,14 @@ Loading and saving keys requires the pyasn1 module. This module is imported as late as possible, such that other functionality will remain working in absence of pyasn1. +.. note:: + + Storing public and private keys via the `pickle` module is possible. + However, it is insecure to load a key from an untrusted source. + The pickle module is not secure against erroneous or maliciously + constructed data. Never unpickle data received from an untrusted + or unauthenticated source. + """ import logging @@ -154,6 +162,14 @@ class PublicKey(AbstractKey): def __repr__(self): return 'PublicKey(%i, %i)' % (self.n, self.e) + def __getstate__(self): + """Returns the key as tuple for pickling.""" + return self.n, self.e + + def __setstate__(self, state): + """Sets the key from tuple.""" + self.n, self.e = state + def __eq__(self, other): if other is None: return False @@ -337,6 +353,14 @@ class PrivateKey(AbstractKey): def __repr__(self): return 'PrivateKey(%(n)i, %(e)i, %(d)i, %(p)i, %(q)i)' % self + def __getstate__(self): + """Returns the key as tuple for pickling.""" + return self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef + + def __setstate__(self, state): + """Sets the key from tuple.""" + self.n, self.e, self.d, self.p, self.q, self.exp1, self.exp2, self.coef = state + def __eq__(self, other): if other is None: return False -- cgit v1.2.1