- Example Programs and crypttool
- Cryptographic Services and Providers
- Cryptographic Keys
- Encryption and Decryption
- Message Digest
- Message Authentication Code
- Digital Signature
- Key Agreement
- Summary of Cryptographic Operations
- Cryptography with crypttool
- Limited versus Unlimited Cryptography
- Performance of Cryptographic Operations
- Practical Applications
- Legal Issues with Cryptography
- Summary
- Further Reading
Encryption and Decryption
Encryption is the process of converting normal data or plaintext to something incomprehensible or cipher-text by applying mathematical transformations. These transformations are known as encryption algorithms and require an encryption key. Decryption is the reverse process of getting back the original data from the cipher-text using a decryption key. The encryption key and the decryption key could be the same as in symmetric or secret key cryptography, or different as in asymmetric or public key cryptography.
Algorithms
A number of encryption algorithms have been developed over time for both symmetric and asymmetric cryptography. The ones supported by the default providers in J2SE v1.4 are: DES, TripleDES, Blowfish, PBEWithMD5AndDES, and PBEWithMD5AndTripleDES. Note that these are all symmetric algorithms.
DES keys are 64 bits in length, of which only 56 are effectively available as one bit per byte is used for parity. This makes DES encryption quite vulnerable to brute force attack. TripleDES, an algorithm derived from DES, uses 128-bit keys (112 effective bits) and is considered much more secure. Blowfish, another symmetric key encryption algorithm, could use any key with size up to 448 bits, although 128-bit keys are used most often. Blowfish is faster than TripleDES but has a slow key setup time, meaning the overall speed may be less if many different keys are used for small segments of data. Algorithms PBEWithMD5AndDES and PBEWithMD5AndTripleDES take a password string as the key and use the algorithm specified in PKCS#5 standard.
There are currently four FIPS approved symmetric encryption algorithms: DES, TripleDES, AES (Advanced Encryption Standard) and Skipjack. You can find more information about these at http://csrc.nist.gov/CryptoToolkit/tkencryption.html. Among these, AES is a new standard and was approved only in 2001. Note that both AES and Skipjack are not supported in J2SE v1.4.1
All these algorithms operate on a block of data, typically consisting of 64 bits or 8 bytes, although smaller blocks are also possible. Each block can be processed independently or tied to the result of processing on the earlier block, giving rise to different encryption modes. Commonly used and supported modes include ECB (Electronic CookBook) mode, whereby each block is processed independently, CBC (Cipher Block Chaining) mode, whereby the result of processing the current block is used in processing the next block), CFB (Cipher Feed Back) and OFB (Output Feed Back). Detailed information on these modes and their performance, security and other characteristics can be found in the book Applied Cryptography by noted cryptographer Bruce Schneier.
CFB and OFB modes allow processing with less than 64 bits, with the actual number of bits, usually a multiple of 8, specified after the mode such as CFB8, OFB8, CFB16, OFB16 and so on. When a mode requires more than 1 byte to do the processing, such as ECB, CBC, CFB16, OFB16 and so on, the data may need to be padded to become a multiple of the block size. Bundled providers support PKCS5Padding, a padding scheme specified in PKCS#5. Also, modes CBC, CFB and OFB need an 8-byte Initialization Vector, so that even the first block has an input to start with. This must be same for both encryption and decryption.
Java API
Java class javax.crypto.Cipher is the engine class for encryption and decryption services. A concrete Cipher object is created by invoking the static method getInstance() and requires a transform string of the format algorithm/mode/padding (an example string would be "DES/ECB/PKCS5Padding") as an argument. After creation, it must be initialized with the key and, optionally, an initialization vector. After initialization, method update() can be called any number of times to pass byte arrays for encryption or decryption, terminated by a doFinal() invocation.
The example program SymmetricCipherTest.java illustrates symmetric encryption and decryption. This program generates a secret key for DES algorithm, encrypts the bytes corresponding to a string value using the generated key and finally decrypts the encrypted bytes to obtain the original bytes. Note the use of an initialization vector for both encryption and decryption. Although the code in this program works on a byte array, it is possible to pass multiple smaller chunks of byte sequences to the Cipher instance before initiating the encryption or decryption.
The code presented here doesn't list individual exceptions thrown in method encrypt() and decrypt(), but you can find them in the electronic version of the source file.
Listing 3-5. Encryption and Decryption with a symmetric Cipher
// File: src\jsbook\ch3\SymmetricCipherTest.java import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.Cipher; public class SymmetricCipherTest { private static byte[] iv = { 0x0a, 0x01, 0x02, 0x03, 0x04, 0x0b, 0x0c, 0x0d }; private static byte[] encrypt(byte[] inpBytes, SecretKey key, String xform) throws Exception { Cipher cipher = Cipher.getInstance(xform); IvParameterSpec ips = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, key, ips); return cipher.doFinal(inpBytes); } private static byte[] decrypt(byte[] inpBytes, SecretKey key, String xform) throws Exception { Cipher cipher = Cipher.getInstance(xform); IvParameterSpec ips = new IvParameterSpec(iv); cipher.init(Cipher.DECRYPT_MODE, key, ips); return cipher.doFinal(inpBytes); } public static void main(String[] unused) throws Exception { String xform = "DES/ECB/PKCS5Padding"; // Generate a secret key KeyGenerator kg = KeyGenerator.getInstance("DES"); kg.init(56); // 56 is the keysize. Fixed for DES SecretKey key = kg.generateKey(); byte[] dataBytes = "J2EE Security for Servlets, EJBs and Web Services".getBytes(); byte[] encBytes = encrypt(dataBytes, key, xform); byte[] decBytes = decrypt(encBytes, key, xform); boolean expected = java.util.Arrays.equals(dataBytes, decBytes); System.out.println("Test " + (expected ? "SUCCEEDED!" : "FAILED!")); } }
Compiling and running this program is similar to other programs in this chapter.
Encryption algorithm PBEWithMD5AndDES requires a slightly different initialization sequence of the Cipher object. Also, there is an alternate mechanism to do encryption decryption involving classes CipherInputStream and CipherOutputStream. We do not cover these methods here. If you are interested in their use, look at the source code of utility crypttool.
The same sequence of calls, with appropriate modifications, would be valid for asymmetric cryptography as well. The example program AsymmetricCipherTest.java illustrates this.
Listing 3-6. Encryption and Decryption with a asymmetric Cipher
// File: src\jsbook\ch3\AsymmetricCipherTest.java import java.security.KeyPairGenerator; import java.security.KeyPair; import java.security.PublicKey; import java.security.PrivateKey; import javax.crypto.Cipher; public class AsymmetricCipherTest { private static byte[] encrypt(byte[] inpBytes, PublicKey key, String xform) throws Exception { Cipher cipher = Cipher.getInstance(xform); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(inpBytes); } private static byte[] decrypt(byte[] inpBytes, PrivateKey key, String xform) throws Exception{ Cipher cipher = Cipher.getInstance(xform); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(inpBytes); } public static void main(String[] unused) throws Exception { String xform = "RSA/NONE/PKCS1PADDING"; // Generate a key-pair KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(512); // 512 is the keysize. KeyPair kp = kpg.generateKeyPair(); PublicKey pubk = kp.getPublic(); PrivateKey prvk = kp.getPrivate(); byte[] dataBytes = "J2EE Security for Servlets, EJBs and Web Services".getBytes(); byte[] encBytes = encrypt(dataBytes, pubk, xform); byte[] decBytes = decrypt(encBytes, prvk, xform); boolean expected = java.util.Arrays.equals(dataBytes, decBytes); System.out.println("Test " + (expected ? "SUCCEEDED!" : "FAILED!")); } }
Note that this program uses a KeyPairGenerator to generate a public key and a private key. The public key is used for encryption and the private key is used for decryption. As there is no padding, there was no need to have an initialization vector.
The only caveat is that J2SE v1.4 bundled providers do not support asymmetric encryption algorithms. You would need to install a third-party JCE provider for this. You could use the Bouncy Castle provider. In fact, the above program is tested against this provider.