All Permissions
9.2 Generating Keys
9.2.3 The KeyGenerator Class
}
As a last step, we must install this class using the security provider that we examined in Chapter 8. Now obtaining a new key pair for the XYZ algorithm is as simple as substituting the string "XYZ" for the algorithm name when we request the key pair, as is shown in the main( ) method.
9.2.3 The KeyGenerator Class
The KeyGenerator class (javax.crypto.KeyGenerator) is used to generate secret keys. This class is very similar to the KeyPairGenerator class except that it generates instances of secret keys instead of pairs of public and private keys:
public class KeyGenerator
Generate instances of secret keys for use by a symmetric encryption algorithm.
The KeyGenerator class is an engine within JCE. As such, it has all the hallmarks of a cryptographic engine. It has a complementary SPI and a set of public methods that are used to operate upon it, and its implementation must be registered with the security provider.
9.2.3.1 Using the KeyGenerator class
Like other engine classes, the KeyGenerator class doesn't have any public constructors. An instance of a KeyGenerator is obtained by calling one of these methods:
public static final KeyGenerator getInstance(String algorithm)
public static final KeyGenerator getInstance(String algorithm, String provider)
Return an object capable of generating secret keys that correspond to the given algorithm. These methods use the standard rules of searching the list of security providers in order to find an object that implements the desired algorithm. If the generator for the appropriate algorithm cannot be found, a NoSuchAlgorithmException is thrown; if the named provider cannot be found, a
NoSuchProviderException is thrown.
JCE provides key generators that implement the following algorithms: Blowfish, DES, DESede, HmacMD5, and HmacSHA1. The first three algorithms are used in data encryption; the last two are used to calculate a message authentication code (MAC).
Once an object has been obtained with these methods, the generator must be initialized by calling one of these methods:
public final void init(SecureRandom sr)
public final void init(AlgorithmParameterSpec aps)
public final void init(AlgorithmParameterSpec aps, SecureRandom sr) public final void init(int strength)
public final void init(int strength, SecureRandom sr)
Initialize the key generator. Like a key pair generator, the key generator needs a source of random numbers to generate its keys (in the second method, a default instance of the SecureRandom class will be used). In addition, some key generators can accept an algorithm parameter specification to initialize their keys (just as the key pair generator); however, for the DES−style keys generated by the SunJCE security provider, no algorithm parameter specification may be used.
A key generator does not have to be initialized explicitly, in which case it is initialized internally with a default instance of the SecureRandom class. However, it is up to the implementor of the engine class to make sure that this happens correctly; it is better to be sure your code will work by always initializing your key generator.
A secret key can be generated by calling this method:
public final SecretKey generateKey( )
Generate a secret key. A generator can produce multiple keys by repeatedly calling this method.
There are two additional methods in this class, both of which are informational:
public final String getAlgorithm( )
Return the string representing the name of the algorithm this generator supports.
public final Provider getProvider( )
Return the provider that was used to obtain this key generator.
In the next section, we'll show the very simple code needed to use this class to generate a secret key.
9.2.3.2 Implementing a KeyGenerator class
Implementing a key generator means creating a class that extends the KeyGeneratorSpi class (javax.crypto.KeyGeneratorSpi):
public abstract class KeyGeneratorSpi
Form the service provider interface class for the KeyGenerator class.
There are three protected methods of this class that we must implement if we want to provide an SPI for a key generator:
protected abstract SecretKey engineGenerateKey( )
Generate the secret key. This method should use the installed random number generator and (if applicable) the installed algorithm parameter specification to generate the secret key. If the engine has not been initialized, it is expected that this method will initialize the engine with a default instance of the SecureRandom class.
protected abstract void engineInit(SecureRandom sr)
protected abstract void engineInit(AlgorithmParameterSpec aps, SecureRandom sr) public final void engineInit(int strength, SecureRandom sr)
Initialize the key generation engine with the given random number generator and, if applicable, algorithm parameter specification. If the class does not support initialization via an algorithm parameter specification, or if the specification is invalid, an
InvalidAlgorithmParameterException is thrown.
Hence, a complete implementation might look like this. First, we must define a secret key type. Ours will hold the single integer used in XOR encryption:
package javasec.samples.ch09;
import javax.crypto.*;
public class XORKey implements SecretKey { int rotValue;
XORKey(int value) { rotValue = value;
}
public String getAlgorithm( ) { return "XOR";
}
public String getFormat( ) { return "XOR Special Format";
}
public byte[] getEncoded( ) {
byte b[] = new byte[4];
b[3] = (byte) ((rotValue << 24) & 0xff);
b[2] = (byte) ((rotValue << 16) & 0xff);
b[1] = (byte) ((rotValue << 8) & 0xff);
b[0] = (byte) ((rotValue << 0) & 0xff);
return b;
} }
Now we can define the key generator that creates these keys:
package javasec.samples.ch09;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javasec.samples.ch08.XYZProvider;
public class XORKeyGenerator extends KeyGeneratorSpi { SecureRandom sr;
public XORKeyGenerator( ) { XYZProvider.verifyForJCE( );
}
public void engineInit(SecureRandom sr) { this.sr = sr;
}
public void engineInit(int len, SecureRandom sr) { if (len != 32)
throw new IllegalArgumentException(
"Only support 32 bit keys");
this.sr = sr;
}
public void engineInit(AlgorithmParameterSpec aps, SecureRandom sr) throws InvalidAlgorithmParameterException { throw new InvalidAlgorithmParameterException("Not supported");
}
public SecretKey engineGenerateKey( ) { if (sr == null)
sr = new SecureRandom( );
byte b[] = new byte[1];
sr.nextBytes(b);
return new XORKey(b[0]);
} }
Keys, of course, are usually longer than a single integer. However, unlike a public key/private key pair, there is not necessarily a mathematical requirement for generating a symmetric key. Such a requirement depends on the encryption algorithm the key will be used for, and some symmetric encryption algorithms require a key that is just an arbitrary sequence of bytes.
Remember that the key generator engine is a JCE engine. Because of this, we must verify it with our security provider, which is why the constructor invokes the verifyForJCE( ) method of our provider.