Reputation: 1
I generate an RSA key:
random_generator = Random.new().read
k1 = RSA.generate(1024,random_generator)
If I create a new key from k1 export all works:
export = k1.exportKey()
k2 = RSA.importKey(export)
If I encrypt with k1 and decrypt with k2 all is fine.
I would like to save "export" and then use it to create a new key, k3, so that I can encrypt with k1 and decrypt with k3. No luck so far. This is what I have tried:
class SavedKey(db.Model):
k = db.BlobProperty()
r = SavedKey()
r.k = export
r.put()
What I retrieve does not work:
retrieved =db.GqlQuery("Select * from SavedKey ").fetch(1000)[0]
retrieved = saved.k
k3 = RSA.importKey(retrieved)
"retrieved" is in the correct private key format but of different value than the original "export". k3 works for encryption and decryption, but encrypted by k1 of course does not decrypt with k3, which is what I am trying to achieve.
What am I doing wrong?
Upvotes: 0
Views: 72
Reputation: 882281
What you're doing wrong is, you're retrieving the wrong entity. Think of
db.GqlQuery("Select * from SavedKey ").fetch(1000)[0]
as retrieving a "random" one of the SavedKey
entities you have in the datastore. If instead you make sure you retrieve the actual one built from that export
(hard to do, as your SavedKey
model has no identifying property), everything will work fine.
Here's an example (using ndb
as it makes little sense to keep using the old db
):
class MainHandler(webapp2.RequestHandler):
def get(self):
random_generator = Random.new().read
k1 = RSA.generate(1024, random_generator)
export = k1.exportKey()
self.response.headers['Content-Type'] = 'text/plain'
self.response.write(export)
r = SavedKey()
r.k = export
rk = r.put()
retrieved = rk.get().k
self.response.write(retrieved)
k3 = RSA.importKey(retrieved)
encrypted = k1.encrypt('four score and seven years ago', 0)
decrypted = k3.decrypt(encrypted)
self.response.write('\n' + decrypted)
...this will work just fine.
Upvotes: 3