Generating and Verifying a Signature Using Generated Keys
The following signature generation and verification examples use the key pair generated in the key pair example.
- Generating a Signature
- We first create a signature object:
Signature dsa = Signature.getInstance("SHA1withDSA");
Next, using the key pair generated in the key pair example, we initialize the object with the private key, and then sign a byte array calleddata
./* Initializing the object with a private key */ PrivateKey priv = pair.getPrivate(); dsa.initSign(priv); /* Update and sign the data */ dsa.update(data); byte[] sig = dsa.sign();
- Verifying a Signature
- Verifying the signature is straightforward. (Note that here we also use the key pair generated in the key pair example.)
/* Initializing the object with the public key */ PublicKey pub = pair.getPublic(); dsa.initVerify(pub); /* Update and verify the data */ dsa.update(data); boolean verifies = dsa.verify(sig); System.out.println("signature verifies: " + verifies);