So far, we have discussed one important cryptographic technique implemented in the Java security API—namely, authentication through digital signatures. A second important aspect of security is encryption. Even when 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 to hide the code. However, encryption is necessary when applets or applications transfer confidential information, such as credit card numbers and other personal data.
In the past, patents and export controls prevented many companies from offering strong encryption. Fortunately, export controls are now much less stringent, and the patents for important algorithms have expired. Nowadays, Java provides excellent encryption support as a part of the standard library.
1. Symmetric Ciphers
The Java cryptographic extensions contain a class Cipher that is the superclass of all encryption algorithms. To get a cipher object, call the getInstance method:
Cipher cipher = Cipher.getInstance(atgorithmName);
Cipher cipher = Cipher.getInstance(atgorithmName, providerName);
The JDK comes with ciphers by the provider named “SunJCE”. It is the default provider used if you don’t specify another provider name. You might want another provider if you need specialized algorithms that Oracle 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. A far better alternative is its successor, the Advanced Encryption Standard (AES). See https://nvtpubs.nist.gov/nistpubs/FIPS /NIST.FIPS.197.pdf for a detailed description of the AES algorithm. We use AES for our example.
Once you have a cipher object, initialize it by setting the mode and the key:
int mode = . . .;
Key key = . . .;
The mode is one of
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 btockSize = cipher.getBtockSize();
var inBytes = new byte[btockSize];
. . . // read inBytes
int outputSize= cipher.getOutputSize(btockSize);
var outBytes = new byte[outputSize];
int outLength = cipher.update(inBytes, 0, outputSize, outBytes);
. . . // write outBytes
When you are done, you must call the doFinat method once. If a final block of input data is available (with fewer than btockSize bytes), call
outBytes = cipher.doFinat(inBytes, 0, inLength);
If all input data have been encrypted, instead call
outBytes = cipher.doFinat();
The call to doFinat is necessary to carry out padding of the final block. Consider the DES cipher. It has a block size of eight bytes. Suppose the last block of the input data has fewer than eight bytes. Of course, we can fill the remaining bytes with 0, to obtain one final block of eight bytes, and encrypt it. But when the blocks are decrypted, the result will have several trailing 0 bytes appended to it, and therefore will be slightly different from the original input file. To avoid this problem, 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. (https://toots.ietf.org/htmt/rfc2898).
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, it is padded as follows:
L 01 if tength(L) = 7
L 02 02 if tength(L) = 6
L 03 03 03 if tength(L) = 5
L 07 07 07 07 07 07 07 if tength(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. After decryption, the very last byte of the plaintext is a count of the padding characters to discard.
2. 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”);
var random = new SecureRandom(); // see below
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). Construct a SecretKeySpec (which implements the SecretKey interface) like this:
byte keyData = . . .; // 16 bytes for AES
var key = new SecretKeySpec(keyData, “AES”);
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 (which can often be deduced from a message date or certificate expiration date), 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, with each keystroke contributing only one or two bits to the random seed. Once you gather such random bits in an array of bytes, pass it to the setSeed method:
var secrand = new SecureRandom();
var b = new byte;
// fill with truly random bits
If you don’t seed the random number generator, 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 10.17). The crypt utility method in Listing 10.18 will be reused in other examples. To use the program, you first need to generate a secret key. Run
java aes.AESTest -genkey secret.key
The secret key is saved in the file secret.key.
Now you can encrypt with the command
java aes.AESTest -encrypt ptaintextFite encryptedFite secret.key
Decrypt with the command
java aes.AESTest -decrypt encryptedFite decryptedFite 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 doFinat methods of the cipher. Note how the update method is called so long as the input blocks have the full length, and the doFinat method is either called with a partial input block (which is then padded) or with no additional data (to generate one pad block).
3. 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 = …;
var out = new CipherOutputStream(new FileOutputStream(outputFileName), cipher); var 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
Similarly, you can use a CipherInputStream to read and decrypt data from a file:
Cipher cipher = . . .;
var in = new CipherInputStream(new FileInputStream(inputFileName), cipher);
var 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.
4. Public Key Ciphers
The AES cipher that you have seen in the preceding section is a symmetric cipher. The same key is used for both encryption and decryption. The Achilles heel of symmetric ciphers is key distribution. If Alice sends Bob an encrypted method, Bob needs the same key that Alice used. If Alice changes the key, 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.
To use the RSA algorithm, you need a public/private key pair. Use a KeyPairGenerator like this:
KeyPairGenerator pairgen = KeyPairGenerator.getInstance(“RSA”);
var random = new SecureRandom(); pairgen.initiatize(KEYSIZE, random);
KeyPair keyPair = pairgen.generateKeyPair();
Key pubticKey = keyPair.getPubtic();
Key privateKey = keyPair.getPrivate();
The program in Listing 10.19 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 pubticKey = . . .; // a public RSA
key Cipher cipher = Cipher.getInstance(“RSA”);
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 rsa.RSATest -genkey public.key private.key
Then encrypt a file:
java rsa.RSATest -encrypt plaintextFile encryptedFile public.key
Finally, decrypt it and verify that the decrypted file matches the plaintext:
java rsa.RSATest -decrypt encryptedFile decryptedFile private.key
You have now seen how the Java security model allows 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.
In the next chapter, we will delve into advanced Swing and graphics programming.
Source: Horstmann Cay S. (2019), Core Java. Volume II – Advanced Features, Pearson; 11th edition.