Is there a module that has my searching has been unable to discover that would allow writing code like the following? The reason for wanting to write code like this is unimportant. All I am after is some code that has a simple API to generate public and private byte keys and to easily encode and decode data with those keys.
import module, os
method, bits, data = 'RSA', 1024, os.urandom(1024)
public, private = module.generate_keys(method, bits)
assert isinstance(public, bytes) and isinstance(private, bytes)
assert module.decode(module.encode(data, private), public) == data
assert module.decode(module.encode(data, public), private) == data
Most of what appears to be available requires downloading a package and only runs on Python 2.x. It is also quite common to find libraries that work with PEM files or other types of certificates. I would like to avoid having to deal with such files, to generate public and private keys on the fly, and quickly work with data in memory.
Public key encryption is not in the standard library. There are some third party libraries on PyPi for it though:
If you’re interested in the math behind it, Python makes it easy to experiment:
The key generation is a little more involved. Here is a simplified example of how to do key generation in-memory using urandom as the source of entropy. The code runs under both Py2.6 and Py3.x: