Austin Austin - 2 years ago 91
Java Question

Key vs SecretKey in Java (encryption)

I am trying to build an AES file encrypt/decrypt. I have used some neat tutorials and guides and I am wondering what the difference is between

. For context I used the the following posts, with the first one using SecretKey (Duncan's reply) and the second one using Key (Shankar's reply) with some
byte array.

My guess is that harcoding some a value with using just
(shankar's answer) isn't as safe as randomly doing this with
(Duncan's answer).

Question: What is the difference between Key and Secret Key, and what is the reasoning for having
within the second post (Key)? Can
not be randomly generated Like Duncan did with

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download