Encryption
So far, we have discussed one important cryptographic technique that is implemented in the Java security API, namely, authentication through digital signatures. A second important aspect of security is encryption. When information is authenticated, the information itself is plainly visible. The digital signature merely verifies that the information has not been changed. In contrast, when information is encrypted, it is not visible. It can only be decrypted with a matching key.
Authentication is sufficient for code signing—there is no need for hiding the code. However, encryption is necessary when applets or applications transfer confidential information, such as credit card numbers and other personal data.
Until recently, patents and export controls have prevented many companies, including Sun, from offering strong encryption. Fortunately, export controls are now much less stringent, and the patent for an important algorithm has expired. As of Java SE 1.4, good encryption support has been part of the standard library.
Symmetric Ciphers
The Java cryptographic extensions contain a class Cipher that is the superclass for all encryption algorithms. You get a cipher object by calling the getInstance method:
Cipher cipher = Cipher.getInstance(algorithName);
or
Cipher cipher = Cipher.getInstance(algorithName, providerName);
The JDK comes with ciphers by the provider named "SunJCE". It is the default provider that is used if you don't specify another provider name. You might want another provider if you need specialized algorithms that Sun does not support.
The algorithm name is a string such as "AES" or "DES/CBC/PKCS5Padding".
The Data Encryption Standard (DES) is a venerable block cipher with a key length of 56 bits. Nowadays, the DES algorithm is considered obsolete because it can be cracked with brute force (see, for example, http://www.eff.org/Privacy/Crypto/Crypto_misc/DESCracker/). A far better alternative is its successor, the Advanced Encryption Standard (AES). See http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf for a detailed description of the AES algorithm. We use AES for our example.
Once you have a cipher object, you initialize it by setting the mode and the key:
int mode = . . .; Key key = . . .; cipher.init(mode, key);
The mode is one of
Cipher.ENCRYPT_MODE Cipher.DECRYPT_MODE Cipher.WRAP_MODE Cipher.UNWRAP_MODE
The wrap and unwrap modes encrypt one key with another—see the next section for an example.
Now you can repeatedly call the update method to encrypt blocks of data:
int blockSize = cipher.getBlockSize(); byte[] inBytes = new byte[blockSize]; . . . // read inBytes int outputSize= cipher.getOutputSize(blockSize); byte[] outBytes = new byte[outputSize]; int outLength = cipher.update(inBytes, 0, outputSize, outBytes); . . . // write outBytes
When you are done, you must call the doFinal method once. If a final block of input data is available (with fewer than blockSize bytes), then call
outBytes = cipher.doFinal(inBytes, 0, inLength);
If all input data have been encrypted, instead call
outBytes = cipher.doFinal();
The call to doFinal is necessary to carry out padding of the final block. Consider the DES cipher. It has a block size of 8 bytes. Suppose the last block of the input data has fewer than 8 bytes. Of course, we can fill the remaining bytes with 0, to obtain one final block of 8 bytes, and encrypt it. But when the blocks are decrypted, the result will have several trailing 0 bytes appended to it, and therefore it will be slightly different from the original input file. That could be a problem, and, to avoid it, we need a padding scheme. A commonly used padding scheme is the one described in the Public Key Cryptography Standard (PKCS) #5 by RSA Security Inc. (ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-5v2/pkcs5v2-0.pdf). In this scheme, the last block is not padded with a pad value of zero, but with a pad value that equals the number of pad bytes. In other words, if L is the last (incomplete) block, then it is padded as follows:
L 01 if length(L) = 7 L 02 02 if length(L) = 6 L 03 03 03 if length(L) = 5 . . . L 07 07 07 07 07 07 07 if length(L) = 1
Finally, if the length of the input is actually divisible by 8, then one block
08 08 08 08 08 08 08 08
is appended to the input and encrypted. For decryption, the very last byte of the plaintext is a count of the padding characters to discard.
Key Generation
To encrypt, you need to generate a key. Each cipher has a different format for keys, and you need to make sure that the key generation is random. Follow these steps:
- Get a KeyGenerator for your algorithm.
- Initialize the generator with a source for randomness. If the block length of the cipher is variable, also specify the desired block length.
- Call the generateKey method.
For example, here is how you generate an AES key.
KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); // see below keygen.init(random); Key key = keygen.generateKey();
Alternatively, you can produce a key from a fixed set of raw data (perhaps derived from a password or the timing of keystrokes). Then use a SecretKeyFactory, like this:
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES"); byte[] keyData = . . .; // 16 bytes for AES SecretKeySpec keySpec = new SecretKeySpec(keyData, "AES"); Key key = keyFactory.generateSecret(keySpec);
When generating keys, make sure you use truly random numbers. For example, the regular random number generator in the Random class, seeded by the current date and time, is not random enough. Suppose the computer clock is accurate to 1/10 of a second. Then there are at most 864,000 seeds per day. If an attacker knows the day a key was issued (as can often be deduced from a message date or certificate expiration date), then it is an easy matter to generate all possible seeds for that day.
The SecureRandom class generates random numbers that are far more secure than those produced by the Random class. You still need to provide a seed to start the number sequence at a random spot. The best method for doing this is to obtain random input from a hardware device such as a white-noise generator. Another reasonable source for random input is to ask the user to type away aimlessly on the keyboard, but each keystroke should contribute only one or two bits to the random seed. Once you gather such random bits in an array of bytes, you pass it to the setSeed method.
SecureRandom secrand = new SecureRandom(); byte[] b = new byte[20]; // fill with truly random bits secrand.setSeed(b);
If you don't seed the random number generator, then it will compute its own 20-byte seed by launching threads, putting them to sleep, and measuring the exact time when they are awakened.
The sample program at the end of this section puts the AES cipher to work (see Listing 9-17). To use the program, you first generate a secret key. Run
java AESTest -genkey secret.key
The secret key is saved in the file secret.key.
Now you can encrypt with the command
java AESTest -encrypt plaintextFile encryptedFile secret.key
Decrypt with the command
java AESTest -decrypt encryptedFile decryptedFile secret.key
The program is straightforward. The -genkey option produces a new secret key and serializes it in the given file. That operation takes a long time because the initialization of the secure random generator is time consuming. The -encrypt and -decrypt options both call into the same crypt method that calls the update and doFinal methods of the cipher. Note how the update method is called as long as the input blocks have the full length, and the doFinal method is either called with a partial input block (which is then padded) or with no additional data (to generate one pad block).
Listing 9-17. AESTest.java
1. import java.io.*; 2. import java.security.*; 3. import javax.crypto.*; 4. 5. /** 6. * This program tests the AES cipher. Usage:<br> 7. * java AESTest -genkey keyfile<br> 8. * java AESTest -encrypt plaintext encrypted keyfile<br> 9. * java AESTest -decrypt encrypted decrypted keyfile<br> 10. * @author Cay Horstmann 11. * @version 1.0 2004-09-14 12. */ 13. public class AESTest 14. { 15. public static void main(String[] args) 16. { 17. try 18. { 19. if (args[0].equals("-genkey")) 20. { 21. KeyGenerator keygen = KeyGenerator.getInstance("AES"); 22. SecureRandom random = new SecureRandom(); 23. keygen.init(random); 24. SecretKey key = keygen.generateKey(); 25. ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); 26. out.writeObject(key); 27. out.close(); 28. } 29. else 30. { 31. int mode; 32. if (args[0].equals("-encrypt")) mode = Cipher.ENCRYPT_MODE; 33. else mode = Cipher.DECRYPT_MODE; 34. 35. ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); 36. Key key = (Key) keyIn.readObject(); 37. keyIn.close(); 38. 39. InputStream in = new FileInputStream(args[1]); 40. OutputStream out = new FileOutputStream(args[2]); 41. Cipher cipher = Cipher.getInstance("AES"); 42. cipher.init(mode, key); 43. 44. crypt(in, out, cipher); 45. in.close(); 46. out.close(); 47. } 48. } 49. catch (IOException e) 50. { 51. e.printStackTrace(); 52. } 53. catch (GeneralSecurityException e) 54. { 55. e.printStackTrace(); 56. } 57. catch (ClassNotFoundException e) 58. { 59. e.printStackTrace(); 60. } 61. } 62. 63. /** 64. * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes 65. * to an output stream. 66. * @param in the input stream 67. * @param out the output stream 68. * @param cipher the cipher that transforms the bytes 69. */ 70. public static void crypt(InputStream in, OutputStream out, Cipher cipher) 71. throws IOException, GeneralSecurityException 72. { 73. int blockSize = cipher.getBlockSize(); 74. int outputSize = cipher.getOutputSize(blockSize); 75. byte[] inBytes = new byte[blockSize]; 76. byte[] outBytes = new byte[outputSize]; 77. 78. int inLength = 0; 79. boolean more = true; 80. while (more) 81. { 82. inLength = in.read(inBytes); 83. if (inLength == blockSize) 84. { 85. int outLength = cipher.update(inBytes, 0, blockSize, outBytes); 86. out.write(outBytes, 0, outLength); 87. } 88. else more = false; 89. } 90. if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength); 91. else outBytes = cipher.doFinal(); 92. out.write(outBytes); 93. } 94. }
- static Cipher getInstance(String algorithmName)
-
static Cipher getInstance(String algorithmName, String providerName)
returns a Cipher object that implements the specified algorithm. Throws a NoSuchAlgorithmException if the algorithm is not provided.
-
int getBlockSize()
returns the size (in bytes) of a cipher block, or 0 if the cipher is not a block cipher.
-
int getOutputSize(int inputLength)
returns the size of an output buffer that is needed if the next input has the given number of bytes. This method takes into account any buffered bytes in the cipher object.
-
void init(int mode, Key key)
initializes the cipher algorithm object. The mode is one of ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE, or UNWRAP_MODE.
- byte[] update(byte[] in)
- byte[] update(byte[] in, int offset, int length)
-
int update(byte[] in, int offset, int length, byte[] out)
transforms one block of input data. The first two methods return the output. The third method returns the number of bytes placed into out.
- byte[] doFinal()
- byte[] doFinal(byte[] in)
- byte[] doFinal(byte[] in, int offset, int length)
-
int doFinal(byte[] in, int offset, int length, byte[] out)
transforms the last block of input data and flushes the buffer of this algorithm object. The first three methods return the output. The fourth method returns the number of bytes placed into out.
-
static KeyGenerator getInstance(String algorithmName)
returns a KeyGenerator object that implements the specified algorithm. Throws a NoSuchAlgorithmException if the algorithm is not provided.
- void init(SecureRandom random)
-
void init(int keySize, SecureRandom random)
initializes the key generator.
-
SecretKey generateKey()
generates a new key.
- static SecretKeyFactory getInstance(String algorithmName)
-
static SecretKeyFactory getInstance(String algorithmName, String providerName)
returns a SecretKeyFactory object for the specified algorithm.
-
SecretKey generateSecret(KeySpec spec)
generates a new secret key from the given specification.
-
SecretKeySpec(byte[] key, String algorithmName)
constructs a key specification.
Cipher Streams
The JCE library provides a convenient set of stream classes that automatically encrypt or decrypt stream data. For example, here is how you can encrypt data to a file:
Cipher cipher = . . .; cipher.init(Cipher.ENCRYPT_MODE, key); CipherOutputStream out = new CipherOutputStream(new FileOutputStream(outputFileName), cipher); byte[] bytes = new byte[BLOCKSIZE]; int inLength = getData(bytes); // get data from data source while (inLength != -1) { out.write(bytes, 0, inLength); inLength = getData(bytes); // get more data from data source } out.flush();
Similarly, you can use a CipherInputStream to read and decrypt data from a file:
Cipher cipher = . . .; cipher.init(Cipher.DECRYPT_MODE, key); CipherInputStream in = new CipherInputStream(new FileInputStream(inputFileName), cipher); byte[] bytes = new byte[BLOCKSIZE]; int inLength = in.read(bytes); while (inLength != -1) { putData(bytes, inLength); // put data to destination inLength = in.read(bytes); }
The cipher stream classes transparently handle the calls to update and doFinal, which is clearly a convenience.
-
CipherInputStream(InputStream in, Cipher cipher)
constructs an input stream that reads data from in and decrypts or encrypts them by using the given cipher.
- int read()
-
int read(byte[] b, int off, int len)
reads data from the input stream, which is automatically decrypted or encrypted.
-
CipherOutputStream(OutputStream out, Cipher cipher)
constructs an output stream that writes data to out and encrypts or decrypts them using the given cipher.
- void write(int ch)
-
void write(byte[] b, int off, int len)
writes data to the output stream, which is automatically encrypted or decrypted.
-
void flush()
flushes the cipher buffer and carries out padding if necessary.
Public Key Ciphers
The AES cipher that you have seen in the preceding section is a symmetric cipher. The same key is used for encryption and for decryption. The Achilles heel of symmetric ciphers is key distribution. If Alice sends Bob an encrypted method, then Bob needs the same key that Alice used. If Alice changes the key, then she needs to send Bob both the message and, through a secure channel, the new key. But perhaps she has no secure channel to Bob, which is why she encrypts her messages to him in the first place.
Public key cryptography solves that problem. In a public key cipher, Bob has a key pair consisting of a public key and a matching private key. Bob can publish the public key anywhere, but he must closely guard the private key. Alice simply uses the public key to encrypt her messages to Bob.
Actually, it's not quite that simple. All known public key algorithms are much slower than symmetric key algorithms such as DES or AES. It would not be practical to use a public key algorithm to encrypt large amounts of information. However, that problem can easily be overcome by combining a public key cipher with a fast symmetric cipher, like this:
- Alice generates a random symmetric encryption key. She uses it to encrypt her plaintext.
- Alice encrypts the symmetric key with Bob's public key.
- Alice sends Bob both the encrypted symmetric key and the encrypted plaintext.
- Bob uses his private key to decrypt the symmetric key.
- Bob uses the decrypted symmetric key to decrypt the message.
Nobody but Bob can decrypt the symmetric key because only Bob has the private key for decryption. Thus, the expensive public key encryption is only applied to a small amount of key data.
The most commonly used public key algorithm is the RSA algorithm invented by Rivest, Shamir, and Adleman. Until October 2000, the algorithm was protected by a patent assigned to RSA Security Inc. Licenses were not cheap—typically a 3% royalty, with a minimum payment of $50,000 per year. Now the algorithm is in the public domain. The RSA algorithm is supported in Java SE 5.0 and above.
To use the RSA algorithm, you need a public/private key pair. You use a KeyPairGenerator like this:
KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); pairgen.initialize(KEYSIZE, random); KeyPair keyPair = pairgen.generateKeyPair(); Key publicKey = keyPair.getPublic(); Key privateKey = keyPair.getPrivate();
The program in Listing 9-18 has three options. The -genkey option produces a key pair. The -encrypt option generates an AES key and wraps it with the public key.
Key key = . . .; // an AES key Key publicKey = . . .; // a public RSA key Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.WRAP_MODE, publicKey); byte[] wrappedKey = cipher.wrap(key);
It then produces a file that contains
- The length of the wrapped key.
- The wrapped key bytes.
- The plaintext encrypted with the AES key.
The -decrypt option decrypts such a file. To try the program, first generate the RSA keys:
java RSATest -genkey public.key private.key
Then encrypt a file:
java RSATest -encrypt plaintextFile encryptedFile public.key
Finally, decrypt it and verify that the decrypted file matches the plaintext:
java RSATest -decrypt encryptedFile decryptedFile private.key
Listing 9-18. RSATest.java
1. import java.io.*; 2. import java.security.*; 3. import javax.crypto.*; 4. 5. /** 6. * This program tests the RSA cipher. Usage:<br> 7. * java RSATest -genkey public private<br> 8. * java RSATest -encrypt plaintext encrypted public<br> 9. * java RSATest -decrypt encrypted decrypted private<br> 10. * @author Cay Horstmann 11. * @version 1.0 2004-09-14 12. */ 13. public class RSATest 14. { 15. public static void main(String[] args) 16. { 17. try 18. { 19. if (args[0].equals("-genkey")) 20. { 21. KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); 22. SecureRandom random = new SecureRandom(); 23. pairgen.initialize(KEYSIZE, random); 24. KeyPair keyPair = pairgen.generateKeyPair(); 25. ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1])); 26. out.writeObject(keyPair.getPublic()); 27. out.close(); 28. out = new ObjectOutputStream(new FileOutputStream(args[2])); 29. out.writeObject(keyPair.getPrivate()); 30. out.close(); 31. } 32. else if (args[0].equals("-encrypt")) 33. { 34. KeyGenerator keygen = KeyGenerator.getInstance("AES"); 35. SecureRandom random = new SecureRandom(); 36. keygen.init(random); 37. SecretKey key = keygen.generateKey(); 38. 39. // wrap with RSA public key 40. ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); 41. Key publicKey = (Key) keyIn.readObject(); 42. keyIn.close(); 43. 44. Cipher cipher = Cipher.getInstance("RSA"); 45. cipher.init(Cipher.WRAP_MODE, publicKey); 46. byte[] wrappedKey = cipher.wrap(key); 47. DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); 48. out.writeInt(wrappedKey.length); 49. out.write(wrappedKey); 50. 51. InputStream in = new FileInputStream(args[1]); 52. cipher = Cipher.getInstance("AES"); 53. cipher.init(Cipher.ENCRYPT_MODE, key); 54. crypt(in, out, cipher); 55. in.close(); 56. out.close(); 57. } 58. else 59. { 60. DataInputStream in = new DataInputStream(new FileInputStream(args[1])); 61. int length = in.readInt(); 62. byte[] wrappedKey = new byte[length]; 63. in.read(wrappedKey, 0, length); 64. 65. // unwrap with RSA private key 66. ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); 67. Key privateKey = (Key) keyIn.readObject(); 68. keyIn.close(); 69. 70. Cipher cipher = Cipher.getInstance("RSA"); 71. cipher.init(Cipher.UNWRAP_MODE, privateKey); 72. Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); 73. 74. OutputStream out = new FileOutputStream(args[2]); 75. cipher = Cipher.getInstance("AES"); 76. cipher.init(Cipher.DECRYPT_MODE, key); 77. 78. crypt(in, out, cipher); 79. in.close(); 80. out.close(); 81. } 82. } 83. catch (IOException e) 84. { 85. e.printStackTrace(); 86. } 87. catch (GeneralSecurityException e) 88. { 89. e.printStackTrace(); 90. } 91. catch (ClassNotFoundException e) 92. { 93. e.printStackTrace(); 94. } 95. } 96. 97. /** 98. * Uses a cipher to transform the bytes in an input stream and sends the transformed bytes 99. * to an output stream. 100. * @param in the input stream 101. * @param out the output stream 102. * @param cipher the cipher that transforms the bytes 103. */ 104. public static void crypt(InputStream in, OutputStream out, Cipher cipher) 105. throws IOException, GeneralSecurityException 106. { 107. int blockSize = cipher.getBlockSize(); 108. int outputSize = cipher.getOutputSize(blockSize); 109. byte[] inBytes = new byte[blockSize]; 110. byte[] outBytes = new byte[outputSize]; 111. 112. int inLength = 0; 113. ; 114. boolean more = true; 115. while (more) 116. { 117. inLength = in.read(inBytes); 118. if (inLength == blockSize) 119. { 120. int outLength = cipher.update(inBytes, 0, blockSize, outBytes); 121. out.write(outBytes, 0, outLength); 122. } 123. else more = false; 124. } 125. if (inLength > 0) outBytes = cipher.doFinal(inBytes, 0, inLength); 126. else outBytes = cipher.doFinal(); 127. out.write(outBytes); 128. } 129. 130. private static final int KEYSIZE = 512; 131. }
You have now seen how the Java security model allows the controlled execution of code, which is a unique and increasingly important aspect of the Java platform. You have also seen the services for authentication and encryption that the Java library provides. We did not cover a number of advanced and specialized issues, among them:
- The GSS-API for "generic security services" that provides support for the Kerberos protocol (and, in principle, other protocols for secure message exchange). There is a tutorial at http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/tutorials/index.html.
- Support for the Simple Authentication and Security Layer (SASL), used by the Lightweight Directory Access Protocol (LDAP) and Internet Message Access Protocol (IMAP). If you need to implement SASL in your own application, look at http://java.sun.com/javase/6/docs/technotes/guides/security/sasl/sasl-refguide.html.
- Support for SSL. Using SSL over HTTP is transparent to application programmers; simply use URLs that start with https. If you want to add SSL to your own application, see the Java Secure Socket Extension (JSEE) reference at http://java.sun.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html.
Now that we have completed our overview of Java security, we turn to distributed computing in Chapter 10.