What is the Signature initSign() method in Java?
Overview
Applications can access the capabilities of a digital signature algorithm using the Signature class. Digital signatures are utilized to authenticate and guarantee the integrity of digital data.
The initSign() is an instance method of the Signature class used to initialize the signature object for signing with a private key.
Syntax
public final void initSign(PrivateKey privateKey)
Parameter
privateKey: This is the private key of the identity for which the signature will be generated.
Return value
The method does not return anything.
Code
import java.security.*;import java.util.*;import java.nio.charset.StandardCharsets;public class Main{private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");kpg.initialize(2048);return kpg.genKeyPair();}private static byte[] getData(){return "hello-educative".getBytes(StandardCharsets.UTF_8);}public static void main(String[] args) {try {String algorithm = "SHA224withRSA";Signature signature = Signature.getInstance(algorithm);KeyPair keyPair = generateKeyPair();byte[] data = getData();signature.initSign(keyPair.getPrivate());signature.update(data);byte[] bytes = signature.sign();System.out.println("Signature:" + Arrays.toString(bytes));} catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {System.out.println("Exception : " + e);}}}
Explanation
- Lines 7–11: We define the
generateKeyPair()method to generate a key pair. - Lines 13–15: We define the
getData()method to return bytes of thehello-educativestring. - Line 19: We define the signature algorithm.
- Line 20: We obtain an instance of the
Signatureclass using thegetInstance()method by specifying the algorithm defined in Line 19. - Line 21: We obtain a key pair by invoking the
generateKeyPair()method. - Line 22: We obtain the byte data by invoking the
getData()method. - Line 23: We initialize the signature object with the key pair using the
initSign()method with the private key pair obtained in Line 21. - Line 24: We update the signature object with the data to be signed.
- Line 25: We sign the data and return the signed bytes. To learn more about the
sign()method, you can go here. - Lines 27–29: We catch the
NoSuchAlgorithmExceptionexception and print it.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved