如何使用证书和私钥在java中对XML文档进行签名?

如何使用证书和私钥在java中对XML文档进行签名?,java,security,xml-signature,Java,Security,Xml Signature,我正在尝试使用从数据库中正确检索的私钥和证书对XML文档进行签名。这个私钥和证书是给我的,所以我不太确定Java中的提供者等价性。用于对我使用的XML文档进行签名 我为此实现的代码如下所示: PrivateKey pk = null; javax.security.cert.X509Certificate cert = null; try{ ByteArrayInputStream bis = new ByteArrayIn

我正在尝试使用从数据库中正确检索的私钥和证书对XML文档进行签名。这个私钥和证书是给我的,所以我不太确定Java中的提供者等价性。用于对我使用的XML文档进行签名

我为此实现的代码如下所示:

        PrivateKey pk = null;
        javax.security.cert.X509Certificate cert = null;
        try{
            ByteArrayInputStream bis = new ByteArrayInputStream(keyCer.getLlave());
            ObjectInput in = new ObjectInputStream(bis);
            pk = (PrivateKey) in.readObject(); 
            bis.close();

            bis = new ByteArrayInputStream(keyCer.getCertificado());
            in = new ObjectInputStream(bis);
            cert = (javax.security.cert.X509Certificate) in.readObject(); 
            bis.close();

            keyCer.setCertB64(Base64.encodeBase64String(cert.getEncoded()));

            DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
            dbfac.setNamespaceAware(true);
            DocumentBuilder docBuilder;
            docBuilder = dbfac.newDocumentBuilder();
            DOMImplementation domImpl = docBuilder.getDOMImplementation();
            Document doc = domImpl.createDocument("http://cancelacfd.sat.gob.mx", "Cancelacion", null);
            doc.setXmlVersion("1.0");
            doc.setXmlStandalone(true);

            Element cancelacion = doc.getDocumentElement();
            cancelacion.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xsd","http://www.w3.org/2001/XMLSchema");
            cancelacion.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
            cancelacion.setAttribute("RfcEmisor", rfc);
            cancelacion.setAttribute("Fecha", fecha);

            Element folios = doc.createElement("Folios");
            cancelacion.appendChild(folios);
            for (int i=0; i<uuid.length; i++) {
                Element u = doc.createElement("UUID");
                u.setTextContent(uuid[i]);
                folios.appendChild(u);
            }

            DOMSignContext dsc = new DOMSignContext (pk, doc.getDocumentElement()); 
            XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

            Reference ref = fac.newReference ("", fac.newDigestMethod(DigestMethod.SHA1, null), 
                        Collections.singletonList
                        (fac.newTransform(Transform.ENVELOPED,
                        (TransformParameterSpec) null)), null, null);

            SignedInfo si = fac.newSignedInfo
                      (fac.newCanonicalizationMethod
                        (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                          (C14NMethodParameterSpec) null),
                        fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null),
                        Collections.singletonList(ref)); 

            KeyInfoFactory kif = fac.getKeyInfoFactory();
            KeyValue kv = kif.newKeyValue(cert.getPublicKey());
            KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv)); 

            XMLSignature signature = fac.newXMLSignature(si, ki);

            signature.sign(dsc);

            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
            trans.setOutputProperty(OutputKeys.VERSION, "1.0");
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //CREAR STRING DEL ARBOL XML
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            String xmlString = sw.toString();
            System.out.println(xmlString);

           } catch (Exception e) {
               e.printStackTrace();
           }

有什么建议吗?

也许您需要安装一个类似的JCE/JCA提供程序,可以在上找到。不过只是一个猜测。

也许您需要安装一个JCE/JCA提供程序,可以在上找到。不过只是猜测。

问题是我的,我错误地指定了签名方法。应该是:

SignedInfo si = fac.newSignedInfo
                      (fac.newCanonicalizationMethod
                        (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                          (C14NMethodParameterSpec) null),
                        fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                        Collections.singletonList(ref)); 

问题是我的,我错误地指定了签名方法。应该是:

SignedInfo si = fac.newSignedInfo
                      (fac.newCanonicalizationMethod
                        (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                          (C14NMethodParameterSpec) null),
                        fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
                        Collections.singletonList(ref)); 

您是否已经为运行时安装了Java加密扩展策略文件?不知道这是否是问题所在,只是偶尔问一下。是的,我实际上刚刚安装了它们,但我继续得到相同的异常。您是否已经为运行时安装了Java加密扩展策略文件?不知道这是否是问题所在,只是偶尔问一下。是的,我实际上刚刚安装了它们,但我仍然收到相同的异常。您知道如何在transforms元素中添加use xslt transform吗?如果是这样,请回复或至少指出一个链接,该链接给出了在xml签名中使用xslt的示例。我正在使用java。谢谢。您知道如何在transforms元素中添加use xslt transform吗?如果是这样,请回复或至少指出一个链接,该链接给出了在xml签名中使用xslt的示例。我正在使用java。非常感谢。