What is the Signature sign() method in Java?

The Sign() method of the java.security.Signature class is used to finish the signature operation. It stores the resulting bytes in outbuffer, starting at offset. We can generate additional signatures using the same object. For this purpose, we can use the initSign() method to regenerate the signature for signing.

Syntax


int Sign(byte[] outbuffer, int offset, int len)


Parameters

  • outbuffer: A buffer for the Signature result as a byte[] type array.
  • Offset: The offset into outbuffer from where the signature bytes are stored.
  • len: The size in bytes within outbuffer, allotted for the Signature.

Return type

This method returns the Signature bytes, i.e., the number of bytes placed into outbuffer.

Exception

It throws SignatureException in the following cases:

  • If the Signature algorithm could not process the input data.
  • If the Signature instance is not initialized properly.

Example code

The below code illustrates the Signature class sign() method at line 21. In line 13, our major goal is to get an array named data signed, which contains "Welcome to Educative!". In line 15, we are instantiating the Signature class using SHA-256 with the RSARivest-Shamir-Adleman algorithm. Execute the code below to see the output:

// Load libraries
import java.security.*;
import java.util.*;
// Main class
public class Educative {
public static void main(String[] argv) throws Exception
{
try {
// initialize keypair
KeyPair keyPair = getKeyPair();
// data to be updated
byte[] data = "Welcome to Educative!".getBytes("UTF8");
// creating the object of Signature
Signature signObj = Signature.getInstance("sha256withrsa");
// initializing the signature object with key pair for signing
signObj.initSign(keyPair.getPrivate());
// updating the data
signObj.update(data);
// getting the signature byte
byte[] bytes = signObj.sign();
// show on console
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 to get KeyPair
private static KeyPair getKeyPair()
throws NoSuchAlgorithmException
{
// initialize the object of KeyPair_Generator
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// initializing with 1024
kpg.initialize(1024);
// returning the key pairs
return kpg.genKeyPair();
}
}
Working of the sign() method

Free Resources