[pycrypto] Public key algos usage

don at amberfisharts.com don at amberfisharts.com
Tue Nov 17 03:49:02 CST 2009



On Tue, 17 Nov 2009 00:42:23 +0100, Kiwi <spiky.kiwi at gmail.com> wrote:
> On Mon, Nov 16, 2009 at 6:26 PM, Lorenz Quack <don at amberfisharts.com>
> wrote:
>> Hi Stefano,
>>
>> As far as I know the API remains the same whether the key is a
> private/public key pair
>> or only the public key. So this should work (However, I didn't test this
> code):
>>
>>  >>> message = "this is a secret"
>>  >>> pub_key = key_pair.publickey()
>>  >>> cipher_text = pub_key.encrypt(message, "")
>>
>> I also think that the API-Reference [1] is fairly accurate.
>>
>> I hope that helps. If not, maybe you show some code how you try to use
> it.
>>
> 
> Thank you for the fast answer.
> I understand the code above.
> Still something is not clear to me.
> And how do I export the public key (or a keypair) to a string? 

Again, I didn't test any of this because I don't have pycrypto installed 
on this machine. So take it with a grain of salt.

You can access the different components of a key object via normal attribute
access. For example you can get the RSA Modulus n from an RSA key object k 
like this:

>>> rsa_modulus = k.n

this way you should be able to access all necessary attributes. If for example
you try to access the private exponent of a public key it will fail (probably 
with an AttributeError I would assume) because public keys obviously don't 
have a private exponent.
The different names of the attributes can be looked up in the API reference.
The names correspond to the canonical ones virtually everybody uses.
However, this returns the values as python longs but it should be trivial to 
convert these into strings.

> How do I import it back?

You should look at the "construct" method.
If however you only want to export/import from/to pycrypto you could use the
python pickle mechanism. The keys all implement __getstate__ and __setstate__

> I want just the key so it can be reused by other libraries and future
> versions of this one, so I cannot just serialize the object.

I don't 100% get what you are saying here. You know that at least in RSA there
isn't "just the key". A key is a tuple of at least 2 numbers. If you did *not*
know this, you probably should do some reading of the basics before proceeding.
If on the other hand you did know that and meant the tuple than I think I 
provided the answer above.


cheers
//Lorenz




More information about the pycrypto mailing list