The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Security in JDK 1.1
Lesson: Using the Security API to Generate Public and Private Keys

Step 4: Verify the Signature

If you have data for which a digital signature was generated, by the Java Security API, you can verify the authenticity of the signature. To do so, you need

In this example, we simply extend our testSig.java program to verify the signature generated in Step 3. In doing so, we will demonstrate the steps required to verify the authenticity of an alleged signature.

As with signature generation, a signature is verified using an instance of the Signature class. We will use the same one as that created in Step 3 via the following:

            Signature dsa = Signature.getInstance("DSA"); 

Initialize the Signature Object for Verification

The Signature object was previously initialized for signing. We must now initialize it for verification. The initialization method for verification requires a public key. We extract and use the public key from the key pair generated in Step 2:

            PublicKey pub = pair.getPublic();

            dsa.initVerify(pub);

Supply the Signature Object the Data to be Verified

We now need to supply the Signature object the data for which a signature was generated. This is the data in the file whose name was specified as the first (and only) command-line argument. As we did when signing, we will read in the data a byte at a time, and supply it to the Signature object by calling the update method. We use the same FileInputStream variable fis and byte variable b as were declared in Step 3:
            fis = new FileInputStream(args[0]);
            while (fis.available() != 0) {
                b = (byte) fis.read();
                dsa.update(b);
                };

            fis.close();
In this sample program we've been building, we are reading the file bytes twice, once for signing and once for verification. Why didn't we just read the file into an array once, and use the array for both signing and verifying? That's a possibility for short files. But you can't know in advance the length of the files to be processed. It may not be possible (or desirable) to create an array large enough to hold the file bytes.

Verify the Signature

Once we have supplied all the data to the Signature object, we can verify the digital signature of that data and report the result. Recall that the signature was placed in a byte array called sig.

            boolean verifies = dsa.verify(sig);

            System.out.println("signature verifies: " + verifies);

In our example, verifies should always be true, since we are properly verifying the signature we just generated.


Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search