ansformerFactory tf = TransformerFactory.newInstance();
2. Transformer transformer = tf.newTransformer();
3. transformer.transform(new DOMSource(doc), new StreamResult(System.out));
3.1.2 验证签名
本节介绍如何使用 Java SE 6提供的 XML 数字签名 API 对上一节生成的数字签名进行验证。验证代码如表5:
表 5 验证 XML 数字签名
1. private static void validate(String signedFile) throws Exception {
2. // Parse the signed XML document to unmarshal <Signature> object.
3. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
4. dbf.setNamespaceAware(true);
5. Document doc =
6. dbf.newDocumentBuilder().parse(new FileInputStream(signedFile));
7.
8. // Search the Signature element
9. NodeList nl =
10. doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
11. if (nl.getLength() == 0) {
12. throw new Exception("Cannot find Signature element");
13. }
14. Node signatureNode = nl.item(0);
15.
16. XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
17. XMLSignature signature =
18. fac.unmarshalXMLSignature(new DOMStructure(signatureNode));
19.
20. // Get the public key for signature validation
21. KeyValue keyValue = (KeyValue)signature.getKeyInfo().getContent().get(0);
22. PublicKey pubKey = keyValue.getPublicKey();
23.
24. // Create ValidateContext
25. DOMValidateContext valCtx = new DOMValidateContext(pubKey, signatureNode);
26.
27. // Validate the XMLSignature
28. boolean coreValidity = signature.validate(valCtx);
29.
30. // Check core validation status
31. if (coreValidity == false) {
32. System.err.println("Core validation failed");
33. // Check the signature validation status
34. boolean sv = signature.getSignatureValue().validate(valCtx);
35. System.out.println("Signature validation status: " + sv);
36. // check the validation status of each Reference
37. List refs = signature.getSignedInfo().getReferences();
38. for(int i=0; i<refs.size(); i++) {
39. Reference ref = (Reference)refs.get(i);
40. boolean refValid = ref.validate(valCtx);
41. System.out.println("Reference["+i+"] validity status: " + refValid);
42. }
43. } else {
44. System.out.println("Signature passed core validation");
45. }46. }
上一页 [1] [2] [3] [4] [5] 下一页
1. 解析签名后生成的 XML 文档(行2 - 行6)
对于 Enveloped 格式的 XML 签名而言,生成的 <Signature> 元素位于被签名的 XML 中,所以这里首先使用 JAXP 将签名后生成的 XML 文档解析。
2. 查找签名元素(行8 - 行14)
所有与 XML 数字签名相关的信息都存放在 <Signature> 元素中,所以需要先取到 <Signature> 元素。由于前面在生成签名的时候将 <Signature> 元素存放为文档根元素的直接子元素,所以这里根据元素名 ”Signature” 进行搜索,搜索到的第一个元素即为 <Signature> 元素。
3. 构造 <Signature> 元素(行16 - 行19)
使用 XMLSignatureFactory 类的 unmarshalXMLSignature 方法从 DOM 节点构造出 XMLSignature 对象,为下一步验证签名作准备。
4. 获取验证签名所需的公共密钥(行20 - 行22)
在本例中,验证密钥以 <DSAKeyValue> 的格式存放于 <KeyIn 上一页 [1] [2] [3] [4] [5] [6] [7] [8] 下一页
|