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.
public final void initSign(PrivateKey privateKey)
privateKey
: This is the private key of the identity for which the signature will be generated.The method does not return anything.
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);}}}
generateKeyPair()
method to generate a key pair.getData()
method to return bytes of the hello-educative
string.Signature
class using the getInstance()
method by specifying the algorithm defined in Line 19.generateKeyPair()
method.getData()
method.initSign()
method with the private key pair obtained in Line 21.sign()
method, you can go here.NoSuchAlgorithmException
exception and print it.Free Resources