首页 > 应用开发 > Java > JavaSE 6基于JSR105的XML签名之实践篇
| <?XML version="1.0" encoding="UTF-8" standalone="no"?> <invoice XMLns="http://www.company.com/accounting"> <items> <item> <desc>Applied Cryptography</desc> <type>book</type> <unitprice>44.50</unitprice> <quantity>1</quantity> </item> </items> <creditcard> <number>123456789</number> <expiry>10/20/2009</expiry> <lastname>John</lastname> <firstname>Smith</firstname> </creditcard> </invoice> |
| keytool -genkey -keysize 512 -sigalg DSA -dname "cn=Young Yang, ou=Architecture, o=Company, L=New York, ST=NY, c=US" -alias biz -keypass kp1234 -keystore bizkeystore -storepass sp1234 -validity 180 |
| public static KeyPair getKeyPair(String store,String sPass,String kPass,String alias) throws CertificateException, IOException, UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException{ KeyStore ks = loadKeyStore(store,sPass); KeyPair keyPair = null; Key key = null; PublicKey publicKey = null; PrivateKey privateKey = null; if (ks.containsAlias(alias)){ key = ks.getKey(alias,kPass.toCharArray()); if (key instanceof PrivateKey){ Certificate cert = ks.getCertificate(alias); publicKey = cert.getPublicKey(); privateKey = (PrivateKey)key; return new KeyPair(publicKey,privateKey); }else{ return null; } } else { return null; } } |
| public static PublicKey getPublicKey(String store, String sPass, String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{ KeyStore ks = loadKeyStore(store, sPass); Certificate cert = ks.getCertificate(alias); return cert.getPublicKey(); } |
| private static KeyStore loadKeyStore(String store, String sPass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{ KeyStore myKS = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(store); myKS.load(fis,sPass.toCharArray()); fis.close(); return myKS; } |
伴随JDK提供的keytool还可以把存储在一个密钥储存文件内的证书输出到系统文件中。例如,为了创建一个包含X509证书(关联于别名为biz的密钥入口)的biz.cer文件,我们可以从文件夹./etcdirectory下运行下列命令:
keytool -export -alias biz -file biz.cer -keystore bizkeystore -storepass sp1234
这个证书实现认证我们讨论上面的公共密钥。
我们还在示例中包括了一个Java类-CertificateInfo,用于把一个证书中的一些有趣的信息输出到System.out。为了试验这一点,读者可以运行Ant目标certInfo。然而,要理解该代码及其输出,必须具有DSA和RSA算法的基本知识。当然,读者可以安全地绕过这个程序而继续阅读本文后面的内容。
二、 生成一个Enveloping签名 这一节讨论借助于JSR-105 API及其缺省实现来实现对invoice.xml文件的签名。
我们的示例中创建了一个enveloping签名。注意,当你想使用在一种detached或enveloped签名情形下时,也仅需对本例作一些细微修改。
下面,让我们分析程序Sign.java,它能够生成invoice.xml文件的XML签名。
| public class Sign { public static void main(String[] args) throws Exception { String input = "./etc/invoice.xml "; String output = "./etc/signature.xml"; if (args.length > 2) { input = args[0]; output = args[1]; } //准备 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); //步骤1 String providerName = System.getProperty("jsr105Provider","org.jcp.XML.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",(Provider) Class.forName(providerName).newInstance()); //步骤2 Reference ref = fac.newReference("#invoice",fac.newDigestMethod(DigestMethod.SHA1, null)); //步骤3 Document XML = dbf.newDocumentBuilder().parse(new File(input)); Node invoice = XML.getDocumentElement(); XMLStructure content = new DOMStructure(invoice); XMLObject obj = fac.newXMLObject(Collections.singletonList(content),"invoice", null, null); //步骤4 SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref)); //步骤5,分为情形5.0或5.1 PrivateKey privateKey = null; //情形5.0 privateKey = KeyStoreInfo.getPrivateKey("./etc/bizkeystore","sp1234","kp1234", "biz"); //情形5.1,分为情形5.1.1或5.1.2 //情形5.1.1 //KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); //kpg.initialize(512); //KeyPair kp = kpg.generateKeyPair(); //情形5.1.2 // KeyPair kp = KeyStoreInfo.getKeyPair("./etc/bizkeystore", "sp1234", // "kp1234","biz"); //如果针对情形5.1,请去掉下面一行中的注释 // privateKey = kp.getPrivate(); //步骤6,分为情形6.0,6.1或6.2 //情形6.0,如果针对情形6.1或6.2也使用下面这一行 KeyInfo ki = null; //如果针对情形6.1或6.2请去掉下面一行中的注释 // KeyInfoFactory kif = fac.getKeyInfoFactory(); //情形6.1 // KeyValue kv = kif.newKeyValue(kp.getPublic()); // ki = kif.newKeyInfo(Collections.singletonList(kv)); //情形6.2 // CertificateFactory cf = CertificateFactory.getInstance("X.509"); // FileInputStream fis = new FileInputStream("./etc/biz.cer"); // java.security.cert.Certificate cert = cf.generateCertificate(fis); // fis.close(); // X509Data x509d = kif.newX509Data(Collections.singletonList(cert)); // ki = kif.newKeyInfo(Collections.singletonList(x509d)); //步骤7 XMLSignature signature = fac.newXMLSignature(si, ki,Collections.singletonList(obj), null, null); //步骤8 Document doc = dbf.newDocumentBuilder().newDocument(); DOMSignContext dsc = new DOMSignContext(privateKey, doc); //步骤9 signature.sign(dsc); //转换成一个xml文档 TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(doc),new StreamResult(new FileOutputStream(output))); } } |
| public abstract DigestMethod newDigestMethod(String algorithm, DigestMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException |
| public abstract Reference newReference(String uri, DigestMethod dm); public abstract Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id); public abstract Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id, byte[] digestValue); ...... |
| <element name="Reference" type="ds:ReferenceType"/> <complexType name="ReferenceType"> <sequence> <element ref="ds:Transforms" minOccurs="0"/> <element ref="ds:DigestMethod"/> <element ref="ds:DigestValue"/> </sequence> <attribute name="Id" type="ID" use="optional"/> <attribute name="URI" type="anyURI" use="optional"/> <attribute name="Type" type="anyURI" use="optional"/> </complexType> |
| <element name="Object" type="ds:ObjectType"/> <complexType name="ObjectType" mixed="true"> <sequence minOccurs="0" maxOccurs="unbounded"> <any namespace="##any" processContents="lax"/> </sequence> <attribute name="Id" type="ID" use="optional"/> <attribute name="MimeType" type="string" use="optional"/> <attribute name="Encoding" type="anyURI" use="optional"/> </complexType> |
| <element name="SignedInfo" type="ds:SignedInfoType"/> <complexType name="SignedInfoType"> <sequence> <element ref="ds:CanonicalizationMethod"/> <element ref="ds:SignatureMethod"/> <element ref="ds:Reference" maxOccurs="unbounded"/> </sequence> <attribute name="Id" type="ID" use="optional"/> </complexType> |
| fac.newCanonicalizationMethod(alg,null) |
| public abstract SignatureMethod newSignatureMethod(String algorithm, SignatureMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException |
| public abstract SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references); public abstract SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references, String id). |
在第二个工厂方法中的第二个参数-id响应于XML签名文档中的SignedInfo元素的Id属性。
【步骤5】-获得签名私有密钥。
在我们的示例中,我们展示了三种不同的方法来得到该私有密钥。在第一种方法中,我们调用我们的KeyStoreInfo类的getPrivateKey()方法来检索我们使用keytool创建的DSA类型私有密钥,并且把它储存在密钥存储文件-bizkeystore(前面的5.0情形)中。为了获得该私有密钥,我们还可以从bizkeystore中检索该KeyPair-通过调用KeyStoreInfo的getKeyPair()方法,然后调用KeyPair实例(5.1.2情形)的getPrivate()。另一方面,JCA提供了一个名字为KeyPairGenerator的类用于根据需要随时动态地创建一个KeyPair,这正是Sign.java中的情形5.1.1提到的情况。
读者还应该注意,JSR-105允许通过一个KeySelector对象获得私有密钥。我们在下节讨论KeySelector时还要详细分析。
【步骤6】创建一个KeyInfo对象。这一步是可选的,就象KeyInfo作为签名元素中的一个元素是可选的一样。在我们的示例的情形6.0下,我们使KeyInfo成为null;这样以来,可以完全从结果XML签名中忽略它。
W3C建议和JSR-105定义RSA的KeyValues以及DSA类型for wrapping,respectively,RSA和DSA公共密钥,并允许它们成为KeyInfo的内容。我们的示例中的情形6.1从我们以前使用JDK keytool生成的公共密钥中创建一个KeyValue对象,并且把它放到一个KeyInfo对象。后面,当讨论我们的核心校验程序时,我们将看到它如何使用这样的一个KeyInfo对象来检索公共密钥以用于签名校验。
在JSR-105中,我们通过调用一个KeyInfoFactory实例中的操作创建了KeyValue和KeyInfo对象。其中,KeyInfoFactory负责创建所有主要的与KeyInfo相关的对象-例如KeyName,KeyValue,X509Data等。我们可以以与我们在〖步骤1〗得到XMLSignatureFactory实例相同的方式得到一个KeyInfoFactory实例。我们的示例调用XMLSignatureFactory对象的getKeyInfoFactory()方法取得KeyInfoFactory实例。
我们的示例的情形6.2将创建一个X509Data对象-使用我们以前借助于工具keytool从bizkeystore中导出的证书biz.cer,然后把这个对象作为内容放入一个KeyInfo对象中。再次,后面我们将讨论的核心校验程序将证明我们如何从这样的一个KeyInfo对象中取得用于签名校验的公共密钥。
【步骤7】创建一个XMLSignature对象。在JSR-105中,XMLSignature接口为W3C中建议的签名元素实现了建模。我们已经在前面看到该签名元素的结构。为了创建一个XMLSiganture实例,我们可以在XMLSignatureFactory中调用下列两个方法之一:
| public abstract XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki); public abstract XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki, List objects, String id, String signatureValueId). |
三、 XML签名核心校验 在前面一节中,我们把invoice.xml文档签名成一个在signature.xml文件中捕获的enveloping XML签名。
为了校验该签名,我们可以使用下列程序-Validate.java:
| public class Validate { public static void main(String[] args) throws Exception { //第一步 String providerName = System.getProperty("jsr105Provider","org.jcp.XML.dsig.internal.dom.XMLDSigRI"); XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",(Provider) Class.forName(providerName).newInstance()); //第二步 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(args[0])); //第三步 NodeList nl = doc.getElementsByTagNameNS(XMLSignature.xmlNS,"Signature"); if (nl.getLength() == 0) { throw new Exception("Cannot find Signature element!"); } //第四步,分为情形4.0,4.1,4.2或4.3 //第4.0种情形 DOMValidateContext valContext = new DOMValidateContext(new KeyStoreKeySelector(), nl.item(0)); //第4.1种情形,需要Sign.java中的第6.1种情形 // DOMValidateContext valContext = new DOMValidateContext( // new KeyValueKeySelector(), nl.item(0)); //第4.2种情形,需要Sign.java中的第6.2种情形 // KeyStore ks = KeyStore.getInstance("JKS"); // FileInputStream fis = new FileInputStream("./etc/bizkeystore"); // ks.load(fis,"sp1234".toCharArray()); // fis.close(); // X509KeySelector x509ks = new X509KeySelector(ks); // DOMValidateContext valContext = new DOMValidateContext(x509ks, nl.item(0)); //第4.3中情形 // PublicKey pKey = KeyStoreInfo.getPublicKey("./etc/bizkeystore", // "sp1234", "biz"); //第五步 XMLSignature signature = fac.unmarshalXMLSignature(valContext); //XMLSignature signature = fac.unmarshalXMLSignature(new DOMStructure(nl.item(0))); //第六步 boolean coreValidity = signature.validate(valContext); //检查核心校验状态 if (coreValidity == false) { System.err.println("Signature failed core validation!"); boolean sv = signature.getSignatureValue().validate(valContext); System.out.println("Signature validation status: " + sv); //每一个Reference的检查校验状态 Iterator i = signature.getSignedInfo().getReferences().iterator(); for (int j = 0; i.hasNext(); j++) { boolean refValid = ((Reference) i.next()).validate(valContext); System.out.println("Reference (" + j + ") validation status: "+ refValid); } } else { System.out.println("Signature passed core validation!"); } } } |
| public DOMValidateContext(Key validatingKey,Node node) |
| public abstract KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException public static KeySelector singletonKeySelector(Key key) |
| public abstract XMLSignature unmarshalXMLSignature(XMLValidateContext context) throws MarshalException |
四、 修改XML签名 为了表明该校验程序确实能够捕获对生成的XML签名的修改,我们可以在我们的示例中创建一个Tamper.java程序,允许我们修改清单中的信用卡号(或signature.xml文件中的SignatureValue元素)。
这个程序使用XML签名文档和一个布尔值作为参数。当该布尔参数为true时,程序改变信用卡号;否则,它修改签名值。
| public class Tamper { public static void main(String[] args) throws Exception { String sigfile = "etc/signature.xml"; //决定要修改的标志-Reference或SignatureValue boolean tamperRef = true ; if (args.length >= 2) { sigfile = args[0]; tamperRef = Boolean.parseBoolean(args[1]); } File file = new File(sigfile); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document signature = dbf.newDocumentBuilder().parse(file); if (tamperRef){ //修改信用卡号 NodeList targets =signature.getDocumentElement().getElementsByTagName("number"); Node number = targets.item(0); if (!number.getTextContent().equals("987654321")){ number.setTextContent("987654321"); }else{ number.setTextContent("000000000"); } }else{ //修改SignatureValue(第一字节) BASE64Encoder en = new BASE64Encoder(); BASE64Decoder de = new BASE64Decoder(); NodeList sigValues =signature.getDocumentElement().getElementsByTagName("SignatureValue"); Node sigValue = sigValues.item(0); byte[] oldValue = de.decodeBuffer(sigValue.getTextContent()); if (oldValue[0]!= 111){ oldValue[0] = (byte)111; }else{ oldValue[0] = (byte)112; } sigValue.setTextContent(en.encode(oldValue)); } TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); trans.transform(new DOMSource(signature),new StreamResult(new FileOutputStream(file))); } } |
http://www.sina.com.cn 2007年01月11日 08:56
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8271432/viewspace-890419/ ,如需转载,请注明出处,否则将追究法律责任。