I have two questions:
- When to use
SecretKeySpec
and when to useKeyGenerator
for key generation? - Is it necessary that the Key instance and the Cipher instance has to follow the same Algorithm? What is the concept behind?
I have two questions:
SecretKeySpec
and when to use KeyGenerator
for key generation?Depends on your application
Yes. Different ciphers may use different key lengths. You pass AlgorithmParameterSpec to the key generator.
KeyGenerator
creates a new random key each time it is called. The returned key is also guaranteed to have the length compatible with the algorithm specified when obtaining the KeyGenerator
instance.
SecretKeySpec
wraps an existing byte array. The source of bytes can be a hex or Base64 string or really any other textual or binary representation of the previously generated key. Hence the use case for SecretKeySpec
is when you need to reuse the key which was previously stored in some external representation.
Usually an instance of SecretKeySpec
can be used directly as a key because SecretKeySpec
implements SecretKey
and most crypto algorithms that use secret keys support so-called "raw" keys where the "raw" key is basically a random sequence of bytes without specific internal structure.
When an algorithm requires a specific SecretKey
representation (usually a subclass of SecretKey
internal to algorithm implementation) you will have to use SecretKeyFactory
to transform a SecretKeySpec
into a proper SecretKey
.
If a crypto algorithm supports "raw" keys then the only requirement is that the key length matches the algorithm expectations.
But the implementer of crypto provider can decide that he needs to use a specific key representation which, for example, caches or precalculates some values based on the initial "raw" bytes. In that case the algorithm can require that a SecretKey
instance passed into in addition to returning correct identifiers from Key.getAlgorithm()
and Key.getFormat()
methods is also a specific subclass of SecretKey
, so the usage of SecretKeyFactory
to convert key spec into a key is mandatory. Such cases are usually documented in the provider documentation.