Chapter 4 68 A number of the methods we've talked about can be overloaded with different arguments, like start and end indices for the byte arrays passed in. We're not going to go into detail covering them, as they are presented clearly in the JCE's JavaDoc. java.security.Key Key is an interface that defines a key to be used for cryptographic functions. A key object cannot be instantiated directly with new, but rather is created by a factory method in a class like javax.crypto.KeyGenerator or java.security.KeyFactory. Key defines three methods: getAlgorithm(), getEncoded(), and getFormat(). They are all concerned with transporting keys, which we'll describe later in this chapter. javax.crypto.KeyGenerator KeyGenerator allows us to create new keys for use in symmetric encryption. There are three methods that we're interested in at this point: getInstance(), init(), and generateKey(). getInstance() As in Cipher, we cannot construct a KeyGenerator with new. Instead we need to call getInstance() with the name of the algorithm. An optional second parameter can be used to define the provider we wish to use. The following line of code will create a key generator that will generate DESede keys: KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede"); init() Instances of KeyGenerator need to be initialized with the size of the key to be generated. With some algorithms, like TripleDES, this is always the same (168 bits). Other algorithms, like Blowfish, have variable key lengths as shown in Chapter 3. The following line will initialize the key generator created above: keyGenerator.init(168); generateKey() This method actually generates the Key object that can be used by an instance of Cipher. There are no arguments, so the call is quite simple: Key myKey = keyGenerator.generateKey(); Simple Encryption Example Now that we've gone over some of the classes and methods we'll need for symmetric encryption, we're going to create a simple program that utilizes them. Our program will create a DESede key, and then encrypt a string with it. We'll then decrypt the encrypted string and display it along with the plaintext and ciphertext bytes as and when we use them. Here we're using the name DESede rather than TripleDES since that's the term used in the Bouncy Castle provider. You may have to change this if you using a different provider.