Chapter 4 66 Encryption and Decryption Symmetric encryption, also known as secret-key encryption, is the simplest type of encryption. A single key is used, which must be kept secret, hence the name. In order to encrypt data, we take the key and use it to initialize a cipher. The cipher can then be used to encrypt data passed to it. Decryption is similar – a cipher gets initialized with the same key, and the data passed in is decrypted. Encryption Cipher Decryption Cipher Plaintext Plaintext Ciphertext The strength of encryption is based on the length of the key. For symmetric encryption, that key length is typically between 40 and 128 bits, but some algorithms can have even longer keys.  DES, which is probably the most commonly used symmetric algorithm, has a key length of 56 bits, which is really not enough for a secure system, as we discussed in Chapter 3. We should use at least 128 bit keys if we're going to use symmetric encryption. Applications Symmetric encryption can be applied in quite a number of areas. It is much faster than asymmetric, or public-key encryption (sometimes by a factor of 1000) and for that reason it is recommended in situations where lots of data must be transformed. File encryption, network encryption, and database encryption are all good places to employ symmetric encryption. Its main weakness is the symmetry of the key. That same key must be used to encrypt and decrypt, so anyone with the ability to encrypt also has the ability to decrypt. If you are sending a symmetrically encrypted message, both sender and receiver must agree on a key in advance. For that reason, it is often best to use symmetric encryption to encrypt a large amount of data, and then encrypt the symmetric key with asymmetric encryption. We will investigate that further in the next chapter. For now, let's begin with a simple example – encrypting and decrypting a string. The only JCE classes our code will use are the (javax.crypto.*) classes, which are used to handle cryptography. This makes the programs portable to any provider that supports the algorithms we use. We've discussed some of these classes in the previous chapter, but now let's investigate them in more depth along with the java.security.Key class. javax.crypto.Cipher The cipher is essentially the engine that performs the encryption and decryption of data. The Cipher class has four methods that we're interested in right now: getInstance(), init(), update(), and doFinal(). Let's go over them one by one: