Security

The java.security package defines quite a few classes related to the Java access-control architecture, which is discussed in more detail in Chapter 6. These classes allow Java programs to run untrusted code in a restricted environment from which it can do no harm. While these are important classes, you rarely need to use them. The more interesting classes are the ones used for message digests and digital signatures; they are demonstrated in the sections that follow.

Message Digests

A message digest is a value, also known as cryptographic checksum or secure hash, that is computed over a sequence of bytes. The length of the digest is typically much smaller than the length of the data for which it is computed, but any change, no matter how small, in the input bytes produces a change in the digest. When transmitting data (a message), you can transmit a message digest along with it. The recipient of the message can then recompute the message digest on the received data and, by comparing the computed digest to the received digest, determine whether the message or the digest was corrupted or tampered with during transmission. We saw a way to compute a message digest earlier in the chapter when we discussed streams. A similar technique can be used to compute a message digest for nonstreaming binary data:

import java.security.*; // Obtain an object to compute message digests using the "Secure Hash // Algorithm"; this method can throw a NoSuchAlgorithmException. MessageDigest ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.