Key vs SecretKey in Java (encryption)

I am trying to create an AES file for encryption / decryption. I've used some neat tutorials and tutorials and I'm wondering what the difference is between Key

and SecretKey

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

My guess is that encoding some value using only Key

(shankar's answer) is not as safe as doing it randomly with SecretKey

(Duncan's answer).

Question: What is the difference between a key and a secret key and what is the reason for the presence keyValue

in the second column (Key)? Could it Key

be randomly generated? How did Duncan do with SecretKey

?

+3


source to share


1 answer


The AES key must be composed of bytes that are indistinguishable from random to attacker. Some keys, such as DES and triple DES keys, are not completely random and therefore must be generated using SecretKeyFactory

or KeyGenerator

(although for DES, many implementations simply ignore parity bits and also allow random values). Random symmetric keys can also be generated using SecretKeySpec

using it like SecretKey

. This is a useful shortcut, but beware that it may not be compatible with key generation or storage on hardware (HSM, smart card).

Whether you randomly generate keys in place or use static keys, it depends on your key management scheme. Key management is one of the most important things to do right for any encryption scheme. "Hard-coding" a key into application sources is of course less secure than reliably generating or storing a key. Usually it is only executed if there is no other way or for testing / demonstration purposes. How you deal with key management depends entirely on the use case; there is no "best" without knowing how and what the keys are used for. For example, generating a random Duncan key is not very attractive if you cannot retrieve the key value later.



As for Key

and SecretKey

; Key

is the base interface SecretKey

, PublicKey

and PrivateKey

. SecretKey

usually consists of random bytes as above. PublicKey

and PrivateKey

are always part of an asymmetric key pair. Typically, these keys are based on number theory and have several components. For example, it RSAPublicKey

consists of a modulus and an open exponent (as values BigInteger

).

What you need for: Choose the one that makes the most sense in a specific location, using the highest-level interface that still suits your needs. For example, you will need RSAPublicKey

to get RSA specific properties such as a module. Otherwise, you can use variables PublicKey

that also accept ECPublicKey

. This way you can make your algorithm (relatively) algorithm agnostic.

+4


source







All Articles