Documentation

The Java™ Tutorials
Hide TOC
Input and Convert the Encoded Public Key Bytes输入并转换编码的公钥字节
Trail: Security Features in Java SE
Lesson: Generating and Verifying Signatures
Section: Verifying a Digital Signature

Input and Convert the Encoded Public Key Bytes输入并转换编码的公钥字节

Next, VerSig needs to import the encoded public key bytes from the file specified as the first command line argument and to convert them to a PublicKey. 接下来,VerSig需要从指定为第一个命令行参数的文件中导入编码的公钥字节,并将其转换为PublicKeyA PublicKey is needed because that is what the Signature initVerify method requires in order to initialize the Signature object for verification.需要公钥,因为Signature initVerify方法需要公钥来初始化Signature对象进行验证。

First, read in the encoded public key bytes.首先,读取编码的公钥字节。

FileInputStream keyfis = new FileInputStream(args[0]);
byte[] encKey = new byte[keyfis.available()];  
keyfis.read(encKey);

keyfis.close();

Now the byte array encKey contains the encoded public key bytes.现在字节数组encKey包含编码的公钥字节。

You can use a KeyFactory class in order to instantiate a DSA public key from its encoding. 您可以使用KeyFactory类从编码中实例化DSA公钥。The KeyFactory class provides conversions between opaque keys (of type Key) and key specifications, which are transparent representations of the underlying key material. KeyFactory类提供不透明键(Key类型)和键规范之间的转换,键规范是底层键材质的透明表示。With an opaque key you can obtain the algorithm name, format name, and encoded key bytes, but not the key material, which, for example, may consist of the key itself and the algorithm parameters used to calculate the key. 使用不透明密钥,您可以获得算法名称、格式名称和编码密钥字节,但无法获得密钥材料,例如,密钥材料可能由密钥本身和用于计算密钥的算法参数组成。(Note that PublicKey, because it extends Key, is itself a Key.)(请注意,由于PublicKey扩展了Key,因此它本身就是一个Key。)

So, first you need a key specification. You can obtain one via the following, assuming that the key was encoded according to the X.509 standard, which is the case, for example, if the key was generated with the built-in DSA key-pair generator supplied by the SUN provider:所以,首先你需要一个关键规范。假设密钥是根据X.509标准编码的,例如,如果密钥是使用SUN提供商提供的内置DSA密钥对生成器生成的,则可以通过以下方式获得密钥:

X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);

Now you need a KeyFactory object to do the conversion. That object must be one that works with DSA keys.现在,您需要一个KeyFactory对象来进行转换。该对象必须与DSA密钥配合使用。

KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");

Finally, you can use the KeyFactory object to generate a PublicKey from the key specification.最后,您可以使用KeyFactory对象从密钥规范生成PublicKey

PublicKey pubKey =
    keyFactory.generatePublic(pubKeySpec);

Previous page: Prepare Initial Program Structure
Next page: Input the Signature Bytes