|
|
Generating and Verifying Signatures [API] |
You've added code to the
VerSigprogram toYou can now proceed to do the verification.
- input the encoded key bytes and converted them to a
PublicKeynamedpubKey, and
- input the signature bytes into a byte array named
sigToVerifyInitialize the Signature Object for Verification
As with signature generation, a signature is verified using an instance of the
Signatureclass. You need to create aSignatureobject that uses the same signature algorithm as was used to generate the signature. The algorithm used by theGenSigprogram was the "SHA1withDSA" algorithm from the "SUN" provider.Signature sig = Signature.getInstance("SHA1withDSA", "SUN");Next you need to initialize theSignatureobject. The initialization method for verification requires the public key:sig.initVerify(pubKey);Supply the Signature Object the Data to be Verified
You now need to supply theSignatureobject the data for which a signature was generated. This is the data in the file whose name was specified as the third command-line argument. As you did when signing, read in the data a buffer at a time, and supply it to theSignatureobject by calling theupdatemethod:FileInputStream datafis = new FileInputStream(args[2]); BufferedInputStream bufin = new BufferedInputStream(datafis); byte[] buffer = new byte[1024]; int len; while (bufin.available() != 0) { len = bufin.read(buffer); sig.update(buffer, 0, len); }; bufin.close();Verify the Signature
Once you have supplied all the data to the
Signatureobject, you can verify the digital signature of that data and report the result. Recall that the alleged signature was read into a byte array calledsigToVerify.boolean verifies = sig.verify(sigToVerify); System.out.println("signature verifies: " + verifies);The
verifiesvalue will betrueif the alleged signature (sigToVerify) is the actual signature of the specified data file generated by the private key corresponding to the public keypubKey.
![]()
Generating and Verifying Signatures [API]