Cryptography Tutorials - Herong's Tutorial Examples - v5.40, by Dr. Herong Yang
Converting Secret Keys to and from Byte Arrays
This section provides a quick introduction of the SecretKeySpec class and the KeySpec interface. They can be used to convert secret keys into byte arrays to store them in external files.
Converting a secret key to a byte array is supported by the SecretKey interface with the getEncoded() method. All secret key implementation classes use the RAW encoding format.
Converting a secret key from a byte array is not so easy. Two options are available:
1. javax.crypto.spec.SecretKeySpec is a class represents a secret key in a generic fashion. It offers the following constructor and methods:
SecretKeySpec() - Convert a secret key from the specified byte array according to the specified algorithm and constructs a SecretKeySpec object based on the secret key.
getAlgorithm() - Returns the algorithm name used to generate the key.
getEncoded() - Returns the key as a byte array in its primary encoding format.
getFormat() - Returns the name of the primary encoding format of this key.
2. java.security.spec.KeySpec is an interface providing a grouping point for algorithm specific key specification implementations. There are two implementations for secret key algorithms:
javax.crypto.spec.DESKeySpec is a KeySpec implementation for DES algorithm. It offers DESKeySpec() to construct a KeySpec object from the specific byte array.
javax.crypto.spec.DESedeKeySpec is a KeySpec implementation for DESede algorithm. It offers DESedeKeySpec() to construct a KeySpec object from the specific byte array.
javax.crypto.spec.SecretKeyFactory is a class as a conversion tool between SecretKey objects and algorithm specific KeySpec objects. It offers the following methods:
getInstance() - Returns a SecretKeyFactory object of the specified algorithm and the specified security package provider. If not specified, the default security pacage provider will be used.
generateSecret() - Generates a SecretKey object from the specified KeySpec object, and returns it.
getKeySpec() - Converts a SecretKey object to a KeySpec object, and returns it.
getAlgorithm() - Returns the algorithm name of this object.
getProvider() - Returns the provider as a provider object of this object.
See the next section on how to use the SecretKeySpec class and the KeySpec interface in a sample program.
Table of Contents