What is the Java Signature sign() method with Example
Published: 2023-08-06 17:39:25

Java is a well liked and versatile language being utilize by developers for making mobile desktop and web apps. Java offers a variety of unique features, one of which is the “sign()” method in the Signature class that can be imported from the “security” package. Using this method, developers can create digital signatures that ensure the security and reliability of their programs. 

In this article, we will focus on the Java Signature sign() method and how to implement it.

**What is Digital Signature?**
Digital signatures are like special codes that ensure that our document data is safe and has not been subject to any change. In Java, A digital signature can be used to guarantee data accuracy. A unique signature is created for a data piece using encryption techniques. Digital signature creation and verification are made possible by the Java Signature class.

**What is the Java Signature “sign()” Method?**
The “sign()” function of the Java “Signature” class is an essential component. It creates a digital signature for a specific record. It records the resulting bytes in the output buffer starting at offset. To do this, use the “initSign()” method for regenerating the signing signature.

Syntax

```
int Sign(byte[] outbuffer, int offset, int len)
```
**Creating a Digital Signature in Java**
To create a digital signature there are a series of steps which are to be implemented in the correct order.
Follow the give  steps for creating a digital signature.

**Step 1. Creating a Signature Instance.**
Create an instance of the “Signature” class named as “signature” that is using the “getInstance()” method along with the algorithm as mentioned below: 

```
Signature signature = Signature.getInstance("SHA256WithDSA");
```

The above code block is using the “SHA-256” hash function along with the “DSA” algorithm for generating and verifying digital signatures.

**Step 2. Initializing the Signature Instance**
After creating the “signature” object, initialize it for usage. The method used to initialize the signature in Java is the “init()” method.
Here is the code for initialization:

```
SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
KeyPair keyPair = keyPairGenerator.generateKeyPair();
signature.initSign(keyPair.getPrivate(), secureRandom);
```

The operations performed by the above-given code are:
-	First, create an instance of the “SecureRandom” class by specifying the object “secureRandom”. It will be utilized to create secure random numbers.
-	Next, create an object for the “KeyPairGenerator” class that is responsible for generating encryption keys for digital signature algorithms as used in the above example which is “DSA”.
-	Now, make another object for “keyPair” that will store the keypair generated by the “KeyPairGenerator”.
-	“signature.initSign(keyPair.getPrivate(), secureRandom);“ initializes an object named “signature” for signing. It is linked with a private key from “keyPair” and a random number generator “secureRandom”. By doing this it becomes ready for signing.

**Step 3. Creating a Digital Signature**
Now, user can create the digital signature. To do so, call the “update()” method and finish with the call to the “sign()” method. Use the below-specified block to create a digital signature:

```
byte[] data = "Your_ String".getBytes("UTF-8");
signature.update(data);
byte[] digitalSignature = signature.sign();
```

In this code:
-	UTF-8 encoding is used to convert the “Your_String” into a sequence of bytes. The result is recorded in the “data“ variable.
-	“signature.update(data)” updates the “signature” object with data from the above step. The signature object is responsible for creating a digital signature.
-	To store the above-generated data, the “signature.sign()” stores the data in an array of “byte[]” type.

**Step 4 . Verification of Digital Signature**
Verification of a digital signature created by someone else can be done for authentication. Now, initialize a “Signature” instance for verification. 
Here is the code:

```
Signature signature2 = Signature.getInstance("SHA256WithDSA");
signature.initVerify(keyPair.getPublic());
```

The operation performed by the above-given code is:
-	First, create an instance for the “Signature” class that will utilize the “getInstance” method that will be used to create or verify the digital signature.
-	“initVerify()” initializes the verification process using the public key from the “keyPair” object. The “getPublic()” method is used to obtain a public key.

Now, use the public key of the public/private key pair to initialize into verification mode. After initialization, verification of the digital signature can be done by the “Signature” class. 
Following is the code snippet:

```
byte[] data2 = "Your_String".getBytes("UTF-8");
signature2.update(data2);
boolean verified = signature2.verify(digitalSignature);
```
The operation performed by the above-given code is:
-	“.getBytes("UTF-8")” method converts the string “Your_String” to a sequence of bytes using UTF-8 encoding.
-	“update(data2)” method updates the “signature2” object with bytes created in the above step.
-	“verify(digitalSignature)” is used to verify the signature and store the answer in the boolean format in the variable “verified”.

**Complete Code**
The complete code must be written in a class by importing the desired packages and classes.
Import the following classes before writing the code:

```
import java.security.*;
import java.util.Base64;
```
The function of these packages and their classes are:
-	“import java.security.*” imports all classes from the security package.
-	“import java.util.Base64” imports the “Base64” encoding class represents binary data by utilizing the printable characters.

Then, declare a class comprising the below code: 

```
public class DigitalSignature {
  public static void main(String[] args) {
    try {
      Signature signature = Signature.getInstance("SHA256WithDSA");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("DSA");
      SecureRandom secureRandom = new SecureRandom();
      keyPairGenerator.initialize(1024, secureRandom);
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      signature.initSign(keyPair.getPrivate());
      byte[] data = "Your_String".getBytes("UTF-8");
      signature.update(data);
      byte[] digitalSignature = signature.sign();
      String encodedSignature =     Base64.getEncoder().encodeToString(digitalSignature);
      System.out.println("Digital Signature: " + encodedSignature);
      Signature signature2 = Signature.getInstance("SHA256WithDSA");
      signature2.initVerify(keyPair.getPublic());
      byte[] data2 = "Your_String".getBytes("UTF-8");
      signature2.update(data2);
      boolean verified = signature2.verify(digitalSignature);
      if (verified) {
        System.out.println("Digital Signature Verified!");
      } else {
        System.out.println("Digital Signature Verification Failed!");
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

```
**Output**
The digital signature will show up as shown below and the second line would indicate its verification:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bvc0unpg1rvir3dt1vou.png)
That’s all about the Java Signature “sign()” method.

**Conclusion**
The “sign()” method is used to create unique digital signatures for data. It ensures data is authentic and original. It changes if the data is modified. Digital signatures play an important role in secure communication and data integrity. This post has described the complete functionality of the Signature “sign()” method along with proper implementation.