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 abyte[]type array.Offset: The offset intooutbufferfrom where the signature bytes are stored.len: The size in bytes withinoutbuffer, 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
Signaturealgorithm could not process the input data. - If the
Signatureinstance 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
// Load librariesimport java.security.*;import java.util.*;// Main classpublic class Educative {public static void main(String[] argv) throws Exception{try {// initialize keypairKeyPair keyPair = getKeyPair();// data to be updatedbyte[] data = "Welcome to Educative!".getBytes("UTF8");// creating the object of SignatureSignature signObj = Signature.getInstance("sha256withrsa");// initializing the signature object with key pair for signingsignObj.initSign(keyPair.getPrivate());// updating the datasignObj.update(data);// getting the signature bytebyte[] bytes = signObj.sign();// show on consoleSystem.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 KeyPairprivate static KeyPair getKeyPair()throws NoSuchAlgorithmException{// initialize the object of KeyPair_GeneratorKeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");// initializing with 1024kpg.initialize(1024);// returning the key pairsreturn kpg.genKeyPair();}}