Q:

How do I program a function to generate a secure Block Cipher Encryption-Key?

I am currently studying the most widely known encryption algorithms and methodologies. For practice purposes, I want to implement everything from ECB to RSA as some kind of a C crypto library. How would I generate a secure key in a C program (I know, that writing a crypto library on my own is not secure at all but I just want to learn basic principles from key generating to key exchanging to encryption mechanisms).
How could I approach the problem of implementing an algorithm for a secure key generation? Which main issues need to be considered to reach an at least mediocre key security?

A:

Most block ciphers want a totally random string of bytes as the key. So read the key from /dev/random dd if=/dev/urandom  count=1 bs=256 (or whatever cryptographic RNG you have easy access to).
For ciphers other than block ciphers, for example RSA or ECDHE (on curves other than ed25519), keys are not just random bytes and in fact have a lot of mathematical structure inside them. These algorithms have complicated key generation routines, so you'll need to go find the specification for the algorithm you're trying to implement. These keygen algorithms have been tested by many mathematicians over the years, and as long as you follow them exactly, you should get a secure key.
For example, Wikipedia describes the general RSA keygen algorithm here, but I'm struggling to find an original source technical spec. Maybe that's because what I want is the PKCS#1 spec, which is pay-walled by the RSA company?
https://en.wikipedia.org/wiki/RSA_(cryptosystem)#Key_generation

