Compute and Verify Digital Signatures

suggest change

To compute a signature:

final PrivateKey privateKey = keyPair.getPrivate();
final byte[] data = "FOO BAR".getBytes(java.nio.charset.StandardCharsets.UTF_8);
final Signature signer = Signature.getInstance("SHA1withRSA");

signer.initSign(privateKey);
signer.update(data);

final byte[] signature = signer.sign();

keyPair is a KeyPair created earlier. The signature algorithm must be compatible with the algorithm used to generate that key pair. SHA1withRSA still verifies here, but SHA-1 signatures are obsolete; SHA256withRSA is the usual choice for a new RSA signature.

To verify a signature:

final PublicKey publicKey = keyPair.getPublic();
final Signature verifier = Signature.getInstance("SHA1withRSA");

verifier.initVerify(publicKey);
verifier.update(data);

System.out.println("Signature: " + verifier.verify(signature));

Produces this output:

Signature: true

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents