public void Sign(string unsignedXmlPath, string signedXmlPath, string pfxPath, string pfxPassword) { PrivateKey privateKey; Provider provider; X509Certificate certificate = _LoadCertificate(pfxPath, pfxPassword, out privateKey, out provider); if (certificate != null) { TrustFactory.instance = es.mityc.javasign.trust.TrustExtendFactory.newInstance(); TrustFactory.truster = es.mityc.javasign.trust.MyPropsTruster.getInstance(); PoliciesManager.POLICY_SIGN = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager(); PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); Document unsignedDocument = dbf.newDocumentBuilder().parse(new BufferedInputStream(new FileInputStream(unsignedXmlPath))); DataToSign dataToSign = new DataToSign(); dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); dataToSign.setEsquema(XAdESSchemas.XAdES_132); dataToSign.setPolicyKey("facturae31"); dataToSign.setAddPolicy(true); dataToSign.setXMLEncoding("UTF-8"); dataToSign.setEnveloped(true); dataToSign.addObject(new ObjectToSign(new AllXMLToSign(), "Description", null, "text/xml", null)); dataToSign.setDocument(unsignedDocument); Object[] res = new FirmaXML().signFile(certificate, dataToSign, privateKey, provider); UtilidadTratarNodo.saveDocumentToOutputStream((Document)res[0], new FileOutputStream(signedXmlPath), true); } }
public static void firmar(string Archivo) { string path = @"C:\Firma\fabricio_fortunato_mero_mosquera.p12"; PrivateKey privatekey; Provider provider; java.security.cert.X509Certificate certificate = LayerLogic.ClassLibrary.Complementos.Firmar.loadCertificate(path, "FFmm_1978", out privatekey, out provider); if (certificate != null) { //Creamos el documento a firmar DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); //C# var base64 = System.Convert.FromBase64String(Archivo); string bytes = System.Text.Encoding.UTF8.GetString(base64); ByteArrayInputStream bs = new ByteArrayInputStream(System.Text.Encoding.UTF8.GetBytes(bytes)); Document documento = dbf.newDocumentBuilder().parse(bs); //Creamos datos a firmar DataToSign dataToSign = new DataToSign(); dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); //XAdES-EPES dataToSign.setAddPolicy(false); dataToSign.setXMLEncoding(encoding); dataToSign.setEnveloped(true); dataToSign.addObject(new ObjectToSign(new InternObjectToSign(nodoFirma), "comprobante", null, "text/xml", null)); dataToSign.setParentSignNode(nodoFirma); //dataToSign.setDocument(LoadXML(NombreArchivo)); dataToSign.setDocument(documento); //Firmar Object[] res = new FirmaXML().signFile(certificate, dataToSign, privatekey, provider); Document doc = (Document)res[0]; //Transformar a string org.w3c.dom.ls.DOMImplementationLS domImplementation = (org.w3c.dom.ls.DOMImplementationLS)doc.getImplementation(); org.w3c.dom.ls.LSSerializer lsSerializer = domImplementation.createLSSerializer(); Archivo = lsSerializer.writeToString(doc).Replace("UTF-16", "UTF-8"); //C# var ArchivoFirmado = Encoding.UTF8.GetBytes(Archivo); string firmado = Convert.ToBase64String(ArchivoFirmado); var base642 = System.Convert.FromBase64String(firmado); string bytes2 = System.Text.Encoding.UTF8.GetString(base642); } }
public bool SignXml(string RutaCertificado, string Clave, string RutaXML, string RutaFirmado, ref string mensaje) { //if (!ValidateAccessKey) // return false; PrivateKey privateKey; Provider provider; try { //X509Certificate certificate = LoadCertificate("","", out privateKey, out provider); X509Certificate certificate = null; provider = null; privateKey = null; //Cargar certificado de fichero PFX KeyStore ks = KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(RutaCertificado), Clave.ToCharArray()); IPKStoreManager storeManager = new KSStore(ks, new PassStoreKS(Clave)); List certificates = storeManager.getSignCertificates(); //Si encontramos el certificado... if (certificates.size() >= 1) { certificate = (X509Certificate)certificates.get(0); // Obtención de la clave privada asociada al certificado privateKey = storeManager.getPrivateKey(certificate); // Obtención del provider encargado de las labores criptográficas provider = storeManager.getProvider(certificate); } if (certificate != null) { TrustFactory.instance = es.mityc.javasign.trust.TrustExtendFactory.newInstance(); TrustFactory.truster = es.mityc.javasign.trust.MyPropsTruster.getInstance(); PoliciesManager.POLICY_SIGN = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager(); [email protected] s = new [email protected](); PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager(); DataToSign dataToSign = new DataToSign(); dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); //XAdES-EPES dataToSign.setEsquema(XAdESSchemas.XAdES_132); dataToSign.setPolicyKey("facturae31"); //dataToSign.setAddPolicy(true); dataToSign.setAddPolicy(false); dataToSign.setXMLEncoding("UTF-8"); dataToSign.setEnveloped(true); dataToSign.addObject(new ObjectToSign(new InternObjectToSign("comprobante"), "contenido comprobante", null, "text/xml", null)); //string fileToSign = Path.Combine("", fileName); Document doc = LoadXML(RutaXML); dataToSign.setDocument(doc); //dataToSign.setDocument(IDocumentoElectronicoExtensions.LoadXml(fileToSign)); Object[] res = new FirmaXML().signFile(certificate, dataToSign, privateKey, provider); java.io.FileOutputStream file = new FileOutputStream(RutaFirmado); UtilidadTratarNodo.saveDocumentToOutputStream((Document)res[0], file, true); file.flush(); file.close(); //DeleteFile(fileToSign); } return(true); } catch (Exception ex) { //System.Windows.Forms.MessageBox.Show(ex.Message); Console.WriteLine(ex.Message); //System.Diagnostics.EventLog.WriteEntry("BcLog", "SignXml - Error en Certificado " + ex.Message); return(false); } }
public static string Firmalo(string pathCertificado, string password, string sRutaXml, string RutaXmlFirmado, string PathServer) { sRutaXml = sRutaXml.Trim(); string result = ""; if (sRutaXml.Length == 0) { result = "Por favor indique la ruta al XML"; return(result); } if (!System.IO.File.Exists(sRutaXml)) { result = "No existe el archivo XML especificado"; return(result); } //My.Settings.Save() java.security.PrivateKey privateKey = null; Provider provider = null; //muestra el selector de Windows Certificado cer = new Certificado(); java.security.cert.X509Certificate certificate = Certificado.LoadCertificate(pathCertificado, password, ref privateKey, ref provider); if (certificate == null) { result = "Seleccione un certificado"; return(result); } if (certificate != null) { //Política de firma (Con las librerías JAVA, esto se define en tiempo de ejecución) TrustFactory.instance = es.mityc.javasign.trust.TrustExtendFactory.newInstance(); TrustFactory.truster = es.mityc.javasign.trust.MyPropsTruster.getInstance(); PoliciesManager.POLICY_SIGN = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager(); PoliciesManager.POLICY_VALIDATION = new es.mityc.javasign.xml.xades.policy.facturae.Facturae31Manager(); //Crear datos a firmar DataToSign dataToSign = new DataToSign(); dataToSign.setXadesFormat(EnumFormatoFirma.XAdES_BES); //XAdES-EPES dataToSign.setEsquema(XAdESSchemas.XAdES_132); dataToSign.setPolicyKey("facturae31"); //Da igual lo que pongamos aquí, la política de firma se define arriba dataToSign.setAddPolicy(true); dataToSign.setXMLEncoding("UTF-8"); dataToSign.setEnveloped(true); dataToSign.addObject(new ObjectToSign(new InternObjectToSign("comprobante"), "powered by Tech Link", null, "text/xml", null)); dataToSign.setDocument(LoadXML(sRutaXml)); //Firmar object[] res = new es.mityc.firmaJava.libreria.xades.FirmaXML().signFile(certificate, dataToSign, privateKey, provider); //var PathServer = @"C:\Users\Public\Documents\ArchivosXml"; //Copiamos el archivo en la direccion correspondiente if (!Directory.Exists(PathServer + @"\Firmados\")) { Directory.CreateDirectory(PathServer + @"\Firmados\"); } System.IO.File.Copy(sRutaXml, RutaXmlFirmado, true); // Guardamos la firma a un fichero sRutaXml = RutaXmlFirmado; //Modificamos FileOutputStream fos = new FileOutputStream(sRutaXml); UtilidadTratarNodo.saveDocumentToOutputStream(((Document)res[0]), fos, true); fos.close(); } return(result); }