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