|
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 signingthere 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 JDK 1.4, good encryption support is part of the standard library. Cryptographic support is also available as a separate extension (called JCE) for older versions of the JDK. Symmetric CiphersThe 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". DES, the Data Encryption Standard, 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://csrc.nist.gov/encryption/aes/ for more information on AES. 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 anothersee 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(inLength); 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 may well 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. Finally, we explain how you obtain a key. You can generate a completely random key by following these steps.
For example, here is how you generate an AES key. KeyGenerator keygen = KeyGenerator.getInstance("AES"); SecureRandom random = new SecureRandom(); keygen.init(random); Key key = keygen.generateKey(); Alternatively, you may want to 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); The sample program at the end of this section puts the AES cipher to work (see Example 9-21). 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). Example 9-21. AESTest.java[View full width] 1. import java.io.*; 2. import java.security.*; 3. import javax.crypto.*; 4. import javax.crypto.spec.*; 5. 6. /** 7. This program tests the AES cipher. Usage: 8. java AESTest -genkey keyfile 9. java AESTest -encrypt plaintext encrypted keyfile 10. java AESTest -decrypt encrypted decrypted keyfile 11. */ 12. public class AESTest 13. { 14. public static void main(String[] args) 15. { 16. try 17. { 18. if (args[0].equals("-genkey")) 19. { 20. KeyGenerator keygen = KeyGenerator.getInstance("AES"); 21. SecureRandom random = new SecureRandom(); 22. keygen.init(random); 23. SecretKey key = keygen.generateKey(); 24. ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream (args[1])); 25. out.writeObject(key); 26. out.close(); 27. } 28. else 29. { 30. int mode; 31. if (args[0].equals("-encrypt")) 32. mode = Cipher.ENCRYPT_MODE; 33. else 34. mode = Cipher.DECRYPT_MODE; 35. 36. ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3])); 37. Key key = (Key) keyIn.readObject(); 38. keyIn.close(); 39. 40. InputStream in = new FileInputStream(args[1]); 41. OutputStream out = new FileOutputStream(args[2]); 42. Cipher cipher = Cipher.getInstance("AES"); 43. cipher.init(mode, key); 44. 45. crypt(in, out, cipher); 46. in.close(); 47. out.close(); 48. } 49. } 50. catch (IOException e) 51. { 52. e.printStackTrace(); 53. } 54. catch (GeneralSecurityException e) 55. { 56. e.printStackTrace(); 57. } 58. catch (ClassNotFoundException e) 59. { 60. e.printStackTrace(); 61. } 62. } 63. 64. /** 65. Uses a cipher to transform the bytes in an input stream 66. and sends the transformed bytes to an output stream. 67. @param in the input stream 68. @param out the output stream 69. @param cipher the cipher that transforms the bytes 70. */ 71. public static void crypt(InputStream in, OutputStream out, Cipher cipher) 72. throws IOException, GeneralSecurityException 73. { 74. int blockSize = cipher.getBlockSize(); 75. int outputSize = cipher.getOutputSize(blockSize); 76. byte[] inBytes = new byte[blockSize]; 77. byte[] outBytes = new byte[outputSize]; 78. 79. int inLength = 0; 80. boolean more = true; 81. while (more) 82. { 83. inLength = in.read(inBytes); 84. if (inLength == blockSize) 85. { 86. int outLength = cipher.update(inBytes, 0, blockSize, outBytes); 87. out.write(outBytes, 0, outLength); 88. } 89. else more = false; 90. } 91. if (inLength > 0) 92. outBytes = cipher.doFinal(inBytes, 0, inLength); 93. else 94. outBytes = cipher.doFinal(); 95. out.write(outBytes); 96. } 97. } javax.crypto.Cipher 1.4
javax.crypto.KeyGenerator 1.4
javax.crypto.SecretKeyFactory 1.4
javax.crypto.spec.SecretKeySpec 1.4
Cipher StreamsThe 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. javax.crypto.CipherInputStream 1.4
javax.crypto.CipherOutputStream 1.4
Public Key CiphersThe 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:
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 cheaptypically 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 JDK 5.0 and above. NOTE
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 Example 9-22 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 -decrypt option decrypts such a file. To try out 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 This example brings us to the end of our discussion on Java security. You have seen how the virtual machine and the security manager provide tight security for programs, and how to use the Java library for authentication and encryption. We did not cover a number of advanced and specialized issues, among them:
Example 9-22. RSATest.java[View full width] 1. import java.io.*; 2. import java.security.*; 3. import javax.crypto.*; 4. import javax.crypto.spec.*; 5. 6. /** 7. This program tests the RSA cipher. Usage: 8. java RSATest -genkey public private 9. java RSATest -encrypt plaintext encrypted public 10. java RSATest -decrypt encrypted decrypted private 11. */ 12. public class RSATest 13. { 14. public static void main(String[] args) 15. { 16. try 17. { 18. if (args[0].equals("-genkey")) 19. { 20. KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA"); 21. SecureRandom random = new SecureRandom(); 22. pairgen.initialize(KEYSIZE, random); 23. KeyPair keyPair = pairgen.generateKeyPair(); 24. ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream (args[1])); 25. out.writeObject(keyPair.getPublic()); 26. out.close(); 27. out = new ObjectOutputStream(new FileOutputStream(args[2])); 28. out.writeObject(keyPair.getPrivate()); 29. out.close(); 30. } 31. else if (args[0].equals("-encrypt")) 32. { 33. KeyGenerator keygen = KeyGenerator.getInstance("AES"); 34. SecureRandom random = new SecureRandom(); 35. keygen.init(random); 36. SecretKey key = keygen.generateKey(); 37. 38. // wrap with RSA public key 39. ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream (args[3])); 40. Key publicKey = (Key) keyIn.readObject(); 41. keyIn.close(); 42. 43. Cipher cipher = Cipher.getInstance("RSA"); 44. cipher.init(Cipher.WRAP_MODE, publicKey); 45. byte[] wrappedKey = cipher.wrap(key); 46. DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2])); 47. out.writeInt(wrappedKey.length); 48. out.write(wrappedKey); 49. 50. InputStream in = new FileInputStream(args[1]); 51. cipher = Cipher.getInstance("AES"); 52. cipher.init(Cipher.ENCRYPT_MODE, key); 53. crypt(in, out, cipher); 54. in.close(); 55. out.close(); 56. } 57. else 58. { 59. DataInputStream in = new DataInputStream(new FileInputStream(args[1])); 60. int length = in.readInt(); 61. byte[] wrappedKey = new byte[length]; 62. in.read(wrappedKey, 0, length); 63. 64. // unwrap with RSA private key 65. ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream (args[3])); 66. Key privateKey = (Key) keyIn.readObject(); 67. keyIn.close(); 68. 69. Cipher cipher = Cipher.getInstance("RSA"); 70. cipher.init(Cipher.UNWRAP_MODE, privateKey); 71. Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); 72. 73. OutputStream out = new FileOutputStream(args[2]); 74. cipher = Cipher.getInstance("AES"); 75. cipher.init(Cipher.DECRYPT_MODE, key); 76. 77. crypt(in, out, cipher); 78. in.close(); 79. out.close(); 80. } 81. } 82. catch (IOException e) 83. { 84. e.printStackTrace(); 85. } 86. catch (GeneralSecurityException e) 87. { 88. e.printStackTrace(); 89. } 90. catch (ClassNotFoundException e) 91. { 92. e.printStackTrace(); 93. } 94. } 95. 96. /** 97. Uses a cipher to transform the bytes in an input stream 98. and sends the transformed bytes to an output stream. 99. @param in the input stream 100. @param out the output stream 101. @param cipher the cipher that transforms the bytes 102. */ 103. public static void crypt(InputStream in, OutputStream out, 104. Cipher cipher) throws IOException, GeneralSecurityException 105. { 106. int blockSize = cipher.getBlockSize(); 107. int outputSize = cipher.getOutputSize(blockSize); 108. byte[] inBytes = new byte[blockSize]; 109. byte[] outBytes = new byte[outputSize]; 110. 111. int inLength = 0;; 112. boolean more = true; 113. while (more) 114. { 115. inLength = in.read(inBytes); 116. if (inLength == blockSize) 117. { 118. int outLength = cipher.update(inBytes, 0, blockSize, outBytes); 119. out.write(outBytes, 0, outLength); 120. } 121. else more = false; 122. } 123. if (inLength > 0) 124. outBytes = cipher.doFinal(inBytes, 0, inLength); 125. else 126. outBytes = cipher.doFinal(); 127. out.write(outBytes); 128. } 129. 130. private static final int KEYSIZE = 512; 131. } |
|