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.
int Sign(byte[] outbuffer, int offset, int len)
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.This method returns the Signature
bytes, i.e., the number of bytes placed into outbuffer
.
It throws SignatureException
in the following cases:
Signature
algorithm could not process the input data.Signature
instance is not initialized properly.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();}}