Documentation

The Java™ Tutorials
Hide TOC
Sign the Data签署数据
Trail: Security Features in Java SE
Lesson: Generating and Verifying Signatures
Section: Generating a Digital Signature

Sign the Data签署数据

Now that you have created a public key and a private key, you are ready to sign the data. In this example you will sign the data contained in a file. 现在您已经创建了公钥和私钥,可以对数据进行签名了。在这个例子中,您将对文件中包含的数据进行签名。GenSig gets the file name from the command line. A digital signature is created (or verified) using an instance of the Signature class.GenSig从命令行获取文件名。使用Signature类的实例创建(或验证)数字签名。

Signing data, generating a digital signature for that data, is done with the following steps.通过以下步骤对数据进行签名,并为该数据生成数字签名。

Get a Signature Object: The following gets a Signature object for generating or verifying signatures using the DSA algorithm, the same algorithm for which the program generated keys in the previous step, Generate Public and Private Keys.获取签名对象:下面获取一个Signature对象,用于使用DSA算法生成或验证签名,该算法与程序在上一步“生成公钥和私钥”中生成密钥的算法相同。

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

Note: When specifying the signature algorithm name, you should also include the name of the message digest algorithm used by the signature algorithm. SHA1withDSA is a way of specifying the DSA signature algorithm, using the SHA-1 message digest algorithm.注意:在指定签名算法名称时,还应包括签名算法使用的消息摘要算法的名称。SHA1withDSA是一种使用SHA-1消息摘要算法指定DSA签名算法的方法。

Initialize the Signature Object初始化签名对象

Before a Signature object can be used for signing or verifying, it must be initialized. The initialization method for signing requires a private key. Use the private key placed into the PrivateKey object named priv in the previous step.Signature对象可用于签名或验证之前,必须对其进行初始化。签名的初始化方法需要私钥。使用上一步中放置在名为privPrivateKey对象中的私钥。

dsa.initSign(priv);

Supply the Signature Object the Data to Be Signed向签名对象提供要签名的数据 This program will use the data from the file whose name is specified as the first (and only) command line argument. 此程序将使用文件中的数据,该文件的名称被指定为第一个(也是唯一一个)命令行参数。The program will read in the data a buffer at a time and will supply it to the Signature object by calling the update method.程序将一次从缓冲区读取数据,并通过调用update方法将其提供给Signature对象。

FileInputStream fis = new FileInputStream(args[0]);
BufferedInputStream bufin = new BufferedInputStream(fis);
byte[] buffer = new byte[1024];
int len;
while ((len = bufin.read(buffer)) >= 0) {
    dsa.update(buffer, 0, len);
};
bufin.close();

Generate the Signature生成签名

Once all of the data has been supplied to the Signature object, you can generate the digital signature of that data.一旦所有数据都提供给Signature对象,您就可以生成该数据的数字签名。

byte[] realSig = dsa.sign();

Previous page: Generate Public and Private Keys
Next page: Save the Signature and the Public Key in Files