How to verify digital signature of a signed data?

In this example we will learn how to verify the digital signature of the previously signed data. To sign the data you can see the previous example on this post How to create a digital signature and sign data?.

Here the code snippet:

package org.kodejava.example.security;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.X509EncodedKeySpec;

public class VerifyDigitalSignature {
    public static void main(String[] args) {
        try {
            byte[] publicKeyEncoded = Files.readAllBytes(Paths.get("publickey"));
            byte[] digitalSignature = Files.readAllBytes(Paths.get("signature"));

            X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKeyEncoded);
            KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");

            PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
            Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
            signature.initVerify(publicKey);

            byte[] bytes = Files.readAllBytes(Paths.get("README"));
            signature.update(bytes);

            boolean verified = signature.verify(digitalSignature);
            if (verified) {
                System.out.println("Data verified.");
            } else {
                System.out.println("Cannot verify data.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to create a digital signature and sign data?

In the following code snippet you will learn how to generate a digital signature to sign a data or file. To create a signature we will need a key pair of public and private key. But for the signing process we’ll only use the private key. While the public key will be use to verify the signature.

To create a digital signature we need an instance of java.security.Signature. To get one we can call the Signature.getInstance() method and pass the algorithm and the provider arguments. In this code snippet we’ll use SHA1withDSA and SUN for the algorithm and provider.

But before we can use the Signature object we have to initialize it first with a PrivateKey. You can also see how to get a private key in the code snippet below. To initialize call the Signature‘s initSign() method.

And finally to generate the digital signature we need to update the Signature using the data that we are going to sign. To do this we read the file into byte[] using the helps of Files.readAllBytes() and supply the bytes into the Signature object using the update() method. To get the signature we call the sign() method which will return us a byte array of the signature.

And here is the complete code snippet:

package org.kodejava.example.security;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.*;

public class GenerateDigitalSignature {
    public static void main(String[] args) {
        try {
            //
            // Get instance and initialize a KeyPairGenerator object.
            //
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
            keyGen.initialize(1024, random);

            //
            // Get a PrivateKey from the generated key pair.
            //
            KeyPair keyPair = keyGen.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();

            //
            // Get an instance of Signature object and initialize it.
            //
            Signature signature = Signature.getInstance("SHA1withDSA", "SUN");
            signature.initSign(privateKey);

            //
            // Supply the data to be signed to the Signature object
            // using the update() method and generate the digital
            // signature.
            //
            byte[] bytes = Files.readAllBytes(Paths.get("README"));
            signature.update(bytes);
            byte[] digitalSignature = signature.sign();

            //
            // Save digital signature and the public key to a file.
            //
            Files.write(Paths.get("signature"), digitalSignature);
            Files.write(Paths.get("publickey"), keyPair.getPublic().getEncoded());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

On the next examples we are going to verify the digital signature. To verify the digital signature is to make sure that the data was sent by the original creator without any modification. To verify we’ll need the digital signature and the public key of the key pair. To get these in the code snippet above we have saved both the digital signature and the public key to files.