Miss-24
Miss-24

Reputation: 1

why we should write all these steps to generate a key for DES algorithm using java

I need to understand why we should write all these steps to generate a key for DES algorithm using java:

DESKeySpec desKeySpec = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

can anyone explain?

Upvotes: 0

Views: 1081

Answers (2)

Stephen C
Stephen C

Reputation: 718658

Here's a line by line analysis:

DESKeySpec desKeySpec = new DESKeySpec(key);

The above statement wraps a key represented as an array of 8 bytes as a KeySpec. A KeySpec is described as "a (transparent) specification of the key material that constitutes a cryptographic key". Transparent means you can look inside it.

SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

The above statement gets a key factory for handling secret keys. In this case, we are asking for a factory that understands DES keys.

SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

The above statement turns the transparent form of the DES key into the opaque form. Opaque means that you cannot see inside it. Or at least, you can't without using reflection methods with access controlled by the sandbox SecurityManager.


Now I don't know the real reason for the SecretKey versus KeySpec dichotomy. It could be to make sandboxing easier, or it could just be a slight case of over-design. Or something else.

The purpose of using a factory here is to allow applications to mix-and-match crypto technologies. Obviously, your code sample hard-wires a specific technology (DES), but the factory approach comes into its own when (for instance) a higher level protocol (e.g. TLS) needs to support multiple crypto algorithms.

The purpose of the SecretKeyFactory.getInstance(...) call is clear too. It is to avoid any explicit code dependencies on the actual classes that implement Java crypto. This has to be done because those classes are in a separate JAR file that may or may not be present in your JRE ... as mandated by US export law.

Upvotes: 3

Buhake Sindi
Buhake Sindi

Reputation: 89169

Because it was designed using the Abstract Factory Pattern. Their goal (can be wrong):

The client does not know (or care) which concrete objects it gets from each of these internal factories since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage.

Upvotes: 1

Related Questions