I need to generate an SSH key pair that I’ll be working with later in the program, and therefore need them as strings. Unfortunately, the ssh-keygen utility doesn’t support writing the keys to STDOUT or something the like.
So, the “next best thing” would be to have ssh-keygen write its output to temporary files, which I can then read back into the program. This however poses the risk of somebody else on the system reading the private keyfile (the script will be run by a web app).
How can I generate a key pair in a way that is secure?
There is no perfectly secure way to generate private keys for distribution; the most secure way is to have each client generate its keypairs and only transmit the public key.
However, if you’re in a situation where that simply won’t work, and you’re committed to generating keypairs centrally, you do have a few options.
There are Hardware Security Modules (HSMs) that do this for you. If you can afford it, this is the best way to go.
Failing that:
If you’re really paranoid, you can also ensure that the keys are encrypted while on disk by having your web application use its own symmetric key to encrypt on writing and decrypt when sending to the user. However, that opens up more key-management to screw up, so I don’t recommend it.
Setting a passphrase on the key will help a lot as well, if you never store that passphrase to disk. If someone does manage to recover a passphrase-protected key, they still have to guess the passphrase for the key to be useful. However, this also means your users will have to provide a passphrase when they use the key — this may or may not be acceptable.