The SecretKeyFactory Class

This class represents a factory for secret keys.

Key factories are used to convert keys (opaque cryptographic keys of type java.security.Key) into key specifications (transparent representations of the underlying key material in a suitable format), and vice versa.

A javax.crypto.SecretKeyFactory object operates only on secret (symmetric) keys, whereas a java.security.KeyFactory object processes the public and private key components of a key pair.

Objects of type java.security.Key, of which java.security.PublicKey, java.security.PrivateKey, and javax.crypto.SecretKey are subclasses, are opaque key objects, because you cannot tell how they are implemented. The underlying implementation is provider-dependent, and can be software or hardware based. Key factories allow providers to supply their own implementations of cryptographic keys.

For example, if you have a key specification for a Diffie Hellman public key, consisting of the public value y, the prime modulus p, and the base g, and you feed the same specification to Diffie-Hellman key factories from different providers, the resulting PublicKey objects will most likely have different underlying implementations.

A provider should document the key specifications supported by its secret key factory. For example, the SecretKeyFactory for DES keys supplied by the "IBMJCE" provider supports DESKeySpec as a transparent representation of DES keys, the SecretKeyFactory for DES-EDE keys supports DESedeKeySpec as a transparent representation of DES-EDE keys, and the SecretKeyFactory for PBE supports PBEKeySpec as a transparent representation of the underlying password.

The following is an example of how to use a SecretKeyFactory to convert secret key data into a SecretKey object, which can be used for a subsequent Cipher operation:

 // Note the following bytes are not realistic secret key data 
 // bytes but are simply supplied as an illustration of using data
 // bytes (key material) you already have to build a DESKeySpec.
 byte[] desKeyData = { (byte)0x01, (byte)0x02, (byte)0x03, 
 (byte)0x04, (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08 };
 DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
 SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

In this case, the underlying implementation of secretKey is based on the provider of keyFactory.

An alternative, provider-independent way of creating a functionally equivalent SecretKey object from the same key material is to use the javax.crypto.spec.SecretKeySpec class, which implements the javax.crypto.SecretKey interface:
 byte[] desKeyData = { (byte)0x01, (byte)0x02, ...};
 SecretKeySpec secretKey = new SecretKeySpec(desKeyData, "DES");