The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
You've added code to the VerSig
program to
PublicKey
named pubKey
sigToVerify
You can now proceed to do the verification.
Initialize the Signature Object for Verification
As with signature generation, a signature is verified by using an instance of the Signature
class. You need to create a Signature
object that uses the same signature algorithm as was used to generate the signature. The algorithm used by the GenSig
program was the SHA1withDSA algorithm from the SUN provider.
Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
Next, you need to initialize the Signature
object. The initialization method for verification requires the public key.
sig.initVerify(pubKey);
Supply the Signature Object With the Data to be Verified You now need to supply the Signature
object with the data for which a signature was generated. This data is in the file whose name was specified as the third command line argument. As you did when signing, read in the data one buffer at a time, and supply it to the Signature
object by calling the update
method.
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 of the data to the Signature
object, you can verify the digital signature of that data and report the result. Recall that the alleged signature was read into a byte array called sigToVerify
.
boolean verifies = sig.verify(sigToVerify); System.out.println("signature verifies: " + verifies);
The verifies
value will be true
if the alleged signature (sigToVerify
) is the actual signature of the specified data file generated by the private key corresponding to the public key pubKey
.