Using Encryption

This section describes the process of generating a key, creating and initializing a cipher object, encrypting a file, and then decrypting it. The Data Encryption Standard (DES) is used throughout this example.

Generating a Key

To create a DES key, we have to instantiate a KeyGenerator for DES. We do not specify a provider, because we do not care about a particular DES key generation implementation. Because we do not initialize the KeyGenerator, a system-provided source of randomness will be used to create the DES key:

KeyGenerator keygen = KeyGenerator.getInstance("DES");
SecretKey desKey = keygen.generateKey();

After the key has been generated, the same KeyGenerator object can be re-used to create further keys.

Creating a Cipher

The next step is to create a Cipher instance. To do this, we use one of the getInstance factory methods of the Cipher class. We must specify the name of the requested transformation, which includes the following components, separated by slashes (/):

  • the algorithm name
  • the mode (optional)
  • the padding scheme (optional)

In this example, we create a DES (Data Encryption Standard) cipher in Electronic Codebook mode, with PKCS#5-style padding. We do not specify a provider, because we do not care about a particular implementation of the requested transformation.

The standard algorithm name for DES is "DES", the standard name for the Electronic Codebook mode is "ECB", and the standard name for PKCS#5-style padding is "PKCS5Padding":

 Cipher desCipher;

 // Create the cipher 
 desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

We use the desKey generated previously to initialize the Cipher object for encryption:

 // Initialize the cipher for encryption
 desCipher.init(Cipher.ENCRYPT_MODE, desKey);

 // Our cleartext
 byte[] cleartext = "This is just an example".getBytes();

 // Encrypt the cleartext
 byte[] ciphertext = desCipher.doFinal(cleartext);

 // Initialize the same cipher for decryption
 desCipher.init(Cipher.DECRYPT_MODE, desKey);

 // Decrypt the ciphertext
 byte[] cleartext1 = desCipher.doFinal(ciphertext);

cleartext and cleartext1 are identical.