Java Signature sign() method with Examples

sign( byte[] dataBuffer, int offset, int length )

The sign() method of java.security.Provider class is used to finish the signature operation and stores the resulting signature bytes in the provided buffer dataBuffer, starting at offset. The format of the signature depends on the underlying signature scheme.

This signature object is reset to its initial state (the state it was in after a call to one of the initSign methods) and can be reused to generate further signatures with the same private key.

Syntax:

public final int sign( byte[] data, int offset, int length )

Parameters: This method takes the following argument as a parameter

dataBuffer– buffer for the signature result as byte[] array.

offset– offset into dataBuffer where the signature is stored.

length– number of bytes within dataBuffer allotted for the signature.

Return Value: This method returns the number of bytes placed into dataBuffer.

Exception: This method throws SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.

Below are the examples to illustrate the sign() method:

Note: The following program will not run in online IDE

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// sign() method
  
import java.security.*;
import java.util.*;
import sun.misc.BASE64Encoder;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // calling getKeyPair() method and assining in keypair
            KeyPair keyPair = getKeyPair();
  
            // creating byte array object
            byte[] outbuff = new byte[1000];
  
            // data to be updated
            byte[] data = "test".getBytes("UTF8");
  
            // creating the object of Signature
            Signature sr = Signature.getInstance("SHA1WithRSA");
  
            // initializing the signature object with key pair
            // for signing
            sr.initSign(keyPair.getPrivate());
  
            // updating the data
            sr.update(data);
  
            // getting the number of bytes
            // placed in outbuffer
            // by using method sign()
            int bytes = sr.sign(outbuff, 0, 550);
  
            // pritning the number of byte
            System.out.println("Signature:" + bytes);
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (SignatureException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
  
    // defining getKeyPair method
    private static KeyPair getKeyPair() throws NoSuchAlgorithmException
    {
  
        // creating the object of KeyPairGenerator
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  
        // initializing with 1024
        kpg.initialize(1024);
  
        // returning the key pairs
        return kpg.genKeyPair();
    }
}

chevron_right


Output:

Signature:128

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// sign() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // creating byte array object
            byte[] outbuff = new byte[1000];
  
            // creating the object of Signature
            Signature sr = Signature.getInstance("SHA1WithRSA");
            ;
  
            // getting the number of bytes
            // placed in outbuffer
            // by using method sign()
            int bytes = sr.sign(outbuff, 0, 550);
  
            // pritning the number of byte
            System.out.println("Signature:" + bytes);
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (SignatureException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


Output:

Exception thrown : java.security.SignatureException: object not initialized for signing

sign()


The sign() method of java.security.Provider class is used to return the signature bytes of all the data updated. The format of the signature depends on the underlying signature scheme.

A call to this method resets this signature object to the state it was in when previously initialized for signing via a call to initSign(PrivateKey). That is, the object is reset and available to generate another signature from the same signer, if desired, via new calls to update and sign.

Return Value: This method returns the the signature bytes of the signing operation’s result.

Exception: This method throws SignatureException if this signature object is not initialized properly or if this signature algorithm is unable to process the input data provided.

Below are the examples to illustrate the sign() method:

Note: The following program will not run in online IDE

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// sign() method
  
import java.security.*;
import java.util.*;
import sun.misc.BASE64Encoder;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // calling getKeyPair() method and assining in keypair
            KeyPair keyPair = getKeyPair();
  
            // data to be updated
            byte[] data = "test".getBytes("UTF8");
  
            // creating the object of Signature
            Signature sr = Signature.getInstance("SHA1WithRSA");
  
            // initializing the signature object with key pair
            // for signing
            sr.initSign(keyPair.getPrivate());
  
            // updating the data
            sr.update(data);
  
            // getting the signature byte
            // of an signing operation
            // by using method sign()
            byte[] bytes = sr.sign();
  
            // pritning the number of byte
            System.out.println("Signature:" + Arrays.toString(bytes));
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (SignatureException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
  
    // defining getKeyPair method
    private static KeyPair getKeyPair() throws NoSuchAlgorithmException
    {
  
        // creating the object of KeyPairGenerator
        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  
        // initializing with 1024
        kpg.initialize(1024);
  
        // returning the key pairs
        return kpg.genKeyPair();
    }
}

chevron_right


Output:

Signature : [96, 101, 38, 76, ... -59]

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to demonstrate
// sign() method
  
import java.security.*;
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
        try {
  
            // creating byte array object
            byte[] outbuff = new byte[1000];
  
            // creating the object of Signature
            Signature sr = Signature.getInstance("SHA1WithRSA");
            ;
  
            // getting the number of bytes
            // placed in outbuffer
            // by using method sign()
            System.out.println("Trying to get"
                               + " the signature byte before initializing");
            byte[] bytes = sr.sign();
  
            // pritning the number of byte
            System.out.println("Signature:" + bytes);
        }
  
        catch (NoSuchAlgorithmException e) {
  
            System.out.println("Exception thrown : " + e);
        }
        catch (SignatureException e) {
  
            System.out.println("Exception thrown : " + e);
        }
    }
}

chevron_right


Output:

Trying to get the signature byte before initializing
Exception thrown : java.security.SignatureException: object not initialized for signing


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.