An AES key should consist of bytes that are indistinguishable from random to an attacker. Some keys, such as DES and triple DES keys, are not fully random and therefore need to be generated by a SecretKeyFactory
or KeyGenerator
(although, for DES, many implementations simply ignore the parity bits and allow random values as well). Random symmetric keys can however also be created by directly using SecretKeySpec
and using it as a SecretKey
. This is a useful shortcut, but beware that it may not be compatible with key generation or storage in hardware (HSM, smart card).
If you create keys randomly on the spot or if you use static keys depends on your key management scheme. Key management is one of the most important hardest things to do correctly for any encryption scheme. "Hard coding" the key in the application sources is of course less safe than generating or storing the key securely. It is usually only performed if there is no other way, or for testing / demonstration purposes. How you handle key management is completely up to the use case; there is no "best" without knowing how and for what the keys are utilized. For instance, Duncan's random key generation is of little use if you cannot retrieve the key value later on.
As for Key
and SecretKey
; Key
is the base interface of Secretkey
, PublicKey
and PrivateKey
. SecretKey
generally consists of random bytes as indicated above. PublicKey
and PrivateKey
are always part of an asymmetric key pair. Generally these kind of keys are based on number theory and they consist of multiple components. For instance an RSAPublicKey
consists of both the modulus and the public exponent (as BigInteger
values).
As for which you need: choose the one that makes most sense at a particular location, using the highest level interface that still fits your need. For instance you'd only need RSAPublicKey
to get RSA specific properties such as the modulus. Otherwise you might as well use PublicKey
variables that also accepts ECPublicKey
. That way you can make your code (relatively) algorithm agnostic.