- Java Cryptography — Verifying Signature
- Step 1: Create a KeyPairGenerator object
- Step 2: Initialize the KeyPairGenerator object
- Step 3: Generate the KeyPairGenerator
- Step 4: Get the private key from the pair
- Step 5: Create a signature object
- Step 6: Initialize the Signature object
- Step 7: Add data to the Signature object
- Step 8: Calculate the Signature
- Step 9: Initialize the signature object for verification
- Step 10: Update the data to be verified
- Step 11: Verify the Signature
- Example
- Output
- Class Signature
- Verify the Signature
- Class Signature
- Lesson: Generating and Verifying Signatures
Java Cryptography — Verifying Signature
You can create digital signature using Java and verify it following the steps given below.
Step 1: Create a KeyPairGenerator object
The KeyPairGenerator class provides getInstance() method which accepts a String variable representing the required key-generating algorithm and returns a KeyPairGenerator object that generates keys.
Create KeyPairGenerator object using the getInstance() method as shown below.
//Creating KeyPair generator object KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
Step 2: Initialize the KeyPairGenerator object
The KeyPairGenerator class provides a method named initialize() method. This method is used to initialize the key pair generator. This method accepts an integer value representing the key size.
Initialize the KeyPairGenerator object created in the previous step using the initialize() method as shown below.
//Initializing the KeyPairGenerator keyPairGen.initialize(2048);
Step 3: Generate the KeyPairGenerator
You can generate the KeyPair using the generateKeyPair() method. Generate the keypair using this method as shown below.
//Generate the pair of keys KeyPair pair = keyPairGen.generateKeyPair();
Step 4: Get the private key from the pair
You can get the private key from the generated KeyPair object using the getPrivate() method.
Get the private key using the getPrivate() method as shown below.
//Getting the private key from the key pair PrivateKey privKey = pair.getPrivate();
Step 5: Create a signature object
The getInstance() method of the Signature class accepts a string parameter representing required signature algorithm and returns the respective Signature object.
Create an object of the Signature class using the getInstance() method.
//Creating a Signature object Signature sign = Signature.getInstance("SHA256withDSA");
Step 6: Initialize the Signature object
The initSign() method of the Signature class accepts a PrivateKey object and initializes the current Signature object.
Initialize the Signature object created in the previous step using the initSign() method as shown below.
//Initialize the signature sign.initSign(privKey);
Step 7: Add data to the Signature object
The update() method of the Signature class accepts a byte array representing the data to be signed or verified and updates the current object with the data given.
Update the initialized Signature object by passing the data to be signed to the update() method in the form of byte array as shown below.
byte[] bytes = "Hello how are you".getBytes(); //Adding data to the signature sign.update(bytes);
Step 8: Calculate the Signature
The sign() method of the Signature class returns the signature bytes of the updated data.
Calculate the Signature using the sign() method as shown below.
//Calculating the signature byte[] signature = sign.sign();
Step 9: Initialize the signature object for verification
To verify a Signature object you need to initialize it first using the initVerify() method it method accepts a PublicKey object.
Therefore, initialize the Signature object for verification using the initVerify() method as shown below.
//Initializing the signature sign.initVerify(pair.getPublic());
Step 10: Update the data to be verified
Update the initialized (for verification) object with the data the data to be verified using the update method as shown below.
//Update the data to be verified sign.update(bytes);
Step 11: Verify the Signature
The verify() method of the Signature class accepts another signature object and verifies it with the current one. If a match occurs, it returns true else it returns false.
Verify the signature using this method as shown below.
//Verify the signature boolean bool = sign.verify(signature);
Example
Following Java program accepts a message from the user, generates a digital signature for the given message, and verifies it.
import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.Signature; import java.util.Scanner; public class SignatureVerification < public static void main(String args[]) throws Exception< //Creating KeyPair generator object KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA"); //Initializing the key pair generator keyPairGen.initialize(2048); //Generate the pair of keys KeyPair pair = keyPairGen.generateKeyPair(); //Getting the privatekey from the key pair PrivateKey privKey = pair.getPrivate(); //Creating a Signature object Signature sign = Signature.getInstance("SHA256withDSA"); //Initializing the signature sign.initSign(privKey); byte[] bytes = "Hello how are you".getBytes(); //Adding data to the signature sign.update(bytes); //Calculating the signature byte[] signature = sign.sign(); //Initializing the signature sign.initVerify(pair.getPublic()); sign.update(bytes); //Verifying the signature boolean bool = sign.verify(signature); if(bool) < System.out.println("Signature verified"); >else < System.out.println("Signature failed"); >> >
Output
The above program generates the following output −
Class Signature
The Signature class is used to provide applications the functionality of a digital signature algorithm. Digital signatures are used for authentication and integrity assurance of digital data.
The signature algorithm can be, among others, the NIST standard DSA, using DSA and SHA-256. The DSA algorithm using the SHA-256 message digest algorithm can be specified as SHA256withDSA . In the case of RSA the signing algorithm could be specified as, for example, SHA256withRSA . The algorithm name must be specified, as there is no default.
A Signature object can be used to generate and verify digital signatures.
- Initialization, with either
- a public key, which initializes the signature for verification (see initVerify ), or
- a private key (and optionally a Secure Random Number Generator), which initializes the signature for signing (see initSign(PrivateKey) and initSign(PrivateKey, SecureRandom) ).
- Updating Depending on the type of initialization, this will update the bytes to be signed or verified. See the update methods.
- Signing or Verifying a signature on all updated bytes. See the sign methods and the verify method.
Note that this class is abstract and extends from SignatureSpi for historical reasons. Application developers should only take notice of the methods defined in this Signature class; all the methods in the superclass are intended for cryptographic service providers who wish to supply their own implementations of digital signature algorithms.
Verify the Signature
As with signature generation, a signature is verified by using an instance of the Signature class. You need to create a Signature object that uses the same signature algorithm as was used to generate the signature. The algorithm used by the GenSig program was the SHA1withDSA algorithm from the SUN provider.
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
Next, you need to initialize the Signature object. The initialization method for verification requires the public key.
Supply the Signature Object With the Data to be Verified You now need to supply the Signature object with the data for which a signature was generated. This data is in the file whose name was specified as the third command line argument. As you did when signing, read in the data one buffer at a time, and supply it to the Signature object by calling the update method.
FileInputStream datafis = new FileInputStream(args[2]); BufferedInputStream bufin = new BufferedInputStream(datafis); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) < len = bufin.read(buffer); sig.update(buffer, 0, len); >; bufin.close();
Once you have supplied all of the data to the Signature object, you can verify the digital signature of that data and report the result. Recall that the alleged signature was read into a byte array called sigToVerify .
boolean verifies = sig.verify(sigToVerify); System.out.println("signature verifies: " + verifies);
The verifies value will be true if the alleged signature ( sigToVerify ) is the actual signature of the specified data file generated by the private key corresponding to the public key pubKey .
Class Signature
The Signature class is used to provide applications the functionality of a digital signature algorithm. Digital signatures are used for authentication and integrity assurance of digital data.
The signature algorithm can be, among others, the NIST standard DSA, using DSA and SHA-256. The DSA algorithm using the SHA-256 message digest algorithm can be specified as SHA256withDSA . In the case of RSA the signing algorithm could be specified as, for example, SHA256withRSA . The algorithm name must be specified, as there is no default.
A Signature object can be used to generate and verify digital signatures.
- Initialization, with either
- a public key, which initializes the signature for verification (see initVerify ), or
- a private key (and optionally a Secure Random Number Generator), which initializes the signature for signing (see initSign(PrivateKey) and initSign(PrivateKey, SecureRandom) ).
- Updating Depending on the type of initialization, this will update the bytes to be signed or verified. See the update methods.
- Signing or Verifying a signature on all updated bytes. See the sign methods and the verify method.
Note that this class is abstract and extends from SignatureSpi for historical reasons. Application developers should only take notice of the methods defined in this Signature class; all the methods in the superclass are intended for cryptographic service providers who wish to supply their own implementations of digital signature algorithms.
Lesson: Generating and Verifying Signatures
This lesson walks you through the steps necessary to use the JDK Security API to generate a digital signature for data and to verify that a signature is authentic. This lesson is meant for developers who wish to incorporate security functionality into their programs, including cryptography services.
This lesson demonstrates the use of the JDK Security API with respect to signing documents. The lesson shows what one program, executed by the person who has the original document, would do to generate keys, generate a digital signature for the document using the private key, and export the public key and the signature to files.
Then it shows an example of another program, executed by the receiver of the document, signature, and public key. It shows how the program could import the public key and verify the authenticity of the signature. The lesson also discusses and demonstrates possible alternative approaches and methods of supplying and importing keys, including in certificates.
For further information about the concepts and terminology (digital signatures, certificates, keystores), see the API and Tools Use for Secure Code and File Exchanges lesson.
In this lesson you create two basic applications, one for the digital signature generation and the other for the verification. This is followed by a discussion and demonstration of potential enhancements. The lesson contains three sections.
- Generating a Digital Signature shows using the API to generate keys and a digital signature for data using the private key and to export the public key and the signature to files. The application gets the data file name from the command line.
- Verifying a Digital Signature shows using the API to import a public key and a signature that is alleged to be the signature of a specified data file and to verify the authenticity of the signature. The data, public key, and signature file names are specified on the command line.
- Weaknesses and Alternatives discusses potential weaknesses of the approach used by the basic programs. It then presents and demonstrates possible alternative approaches and methods of supplying and importing keys, including the use of files containing encoded key bytes and the use of certificates containing public keys.