Documentation

The Java™ Tutorials
Hide TOC
Verify the Signature验证签名
Trail: Security Features in Java SE
Lesson: Generating and Verifying Signatures
Section: Verifying a Digital Signature

Verify the Signature验证签名

You've added code to the VerSig program to您已将代码添加到VerSig程序中

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. 与签名生成一样,签名是通过使用Signature类的实例进行验证的。You need to create a Signature object that uses the same signature algorithm as was used to generate the signature. 您需要创建一个Signature对象,该对象使用与生成签名相同的签名算法。The algorithm used by the GenSig program was the SHA1withDSA algorithm from the SUN provider.GenSig程序使用的算法是SUN提供商的SHA1withDSA算法。

Signature sig = Signature.getInstance("SHA1withDSA", "SUN");

Next, you need to initialize the Signature object. The initialization method for verification requires the public key.接下来,您需要初始化Signature对象。验证的初始化方法需要公钥。

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. 现在,您需要向Signature对象提供生成签名的数据。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.与签名时一样,一次读取一个缓冲区的数据,并通过调用update方法将其提供给Signature对象。

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.一旦您将所有数据提供给Signature对象,您就可以验证该数据的数字签名并报告结果。回想一下,所谓的签名被读入了一个名为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.如果声称的签名(sigToVerify)是由与公钥pubKey对应的私钥生成的指定数据文件的实际签名,则verifies值将为true


Previous page: Input the Signature Bytes
Next page: Compile and Run the Program