Generate rsa private key python florida

I was looking for a quick way to generate an RSA key in Python 3 for some unit tests which needed a public key as an OpenSSH string. It ended up taking longer than expected because I started by trying to use the pycrypto library, which is hard to install on Windows (weird dependencies on specific Visual Studio runtimes) and has unresolved bugs with Python 3.

If you’re using Python 3 it’s much easier to use the cryptography library.

Since OpenSSL is a collection of modules we specify genpkey to generate a private key. The -algorithm option specifies which algorithm we want to use to generate the key (RSA in this case), -out specifies the name of the output file, and -pkeyopt allows us to set the value for specific key options. In this case the length of the RSA key in bits.

Generate Rsa Key Pair

Here’s an example which generates an RSA key pair, prints the private key as a string in PEM container format, and prints the public key as a string in OpenSSH format.