Documentos de Académico
Documentos de Profesional
Documentos de Cultura
2 *
3 * @author ccarreno
4 */
5
6 public class DevelopedSignature {
7
8 public static void main(String[] args) throws Exception {
9
10 /*String xmlPath = "c:\\1‐001‐020000000543.XML";
11 String pathSignature = "c:\\certificado.p12";
12 String passSignature = "constraseña";
13 String pathOut = "c:\\";
14 String nameFileOut = "factura_sign.xml";*/
15
16 String xmlPath = args[2];
17 String pathSignature = args[0];
18 String passSignature = args[1];
19 String pathOut = args[3];
20 String nameFileOut = args[4];
21
22 System.out.println("Ruta del XML de entrada: " + xmlPath);
23 System.out.println("Ruta Certificado: " + pathSignature);
24 System.out.println("Clave del Certificado: " + passSignature);
25 System.out.println("Ruta de salida del XML: " + pathOut);
26 System.out.println("Nombre del archivo salido: " + nameFileOut);
27
28 try{
29 XAdESBESSignature.firmar(xmlPath, pathSignature, passSignature, pathOut, nameFileOut);
30 }catch(Exception e){
31 System.out.println("Error: " + e);
32 }
33 }
34
35
36 }
1 /**
2 *
3 * @author ccarreno
4 */
5 import es.mityc.firmaJava.libreria.xades.DataToSign;
6 import es.mityc.firmaJava.libreria.xades.FirmaXML;
7 import java.io.File;
8 import java.io.FileInputStream;
9 import java.io.IOException;
10 import java.security.KeyStore;
11 import java.security.KeyStoreException;
12 import java.security.NoSuchAlgorithmException;
13 import java.security.PrivateKey;
14 import java.security.Provider;
15 import java.security.UnrecoverableKeyException;
16 import java.security.cert.CertificateException;
17 import java.security.cert.X509Certificate;
18 import java.util.Enumeration;
19 import javax.xml.parsers.DocumentBuilder;
20 import javax.xml.parsers.DocumentBuilderFactory;
21 import javax.xml.parsers.ParserConfigurationException;
22 import javax.xml.transform.Transformer;
23 import javax.xml.transform.TransformerConfigurationException;
24 import javax.xml.transform.TransformerException;
25 import javax.xml.transform.TransformerFactory;
26 import javax.xml.transform.dom.DOMSource;
27 import javax.xml.transform.stream.StreamResult;
28 import org.w3c.dom.Document;
29 import org.xml.sax.SAXException;
30
31 public abstract class GenericXMLSignature
32 {
33 private String pathSignature;
34 private String passSignature;
35
36 public String getPathSignature()
37 {
38 return this.pathSignature;
39 }
40
41 public void setPathSignature(String pathSignature)
42 {
43 this.pathSignature = pathSignature;
44 }
45
46 public String getPassSignature()
47 {
48 return this.passSignature;
49 }
50
51 public void setPassSignature(String passSignature)
52 {
53 this.passSignature = passSignature;
54 }
55
56 protected void execute()
57 throws CertificateException
58 {
59 KeyStore keyStore = getKeyStore();
60 if (keyStore == null)
61 {
62 System.err.println("No se pudo obtener almacen de firma.");
63 return;
64 }
65 String alias = getAlias(keyStore);
66
67
68
69 X509Certificate certificate = null;
70 try
71 {
72 certificate = (X509Certificate)keyStore.getCertificate(alias);
73 if (certificate == null)
74 {
75 System.err.println("No existe ningún certificado para firmar.");
76 return;
77 }
78 }
79 catch (KeyStoreException e1)
80 {
81 System.err.println("Error: " + e1.getMessage());
82 //e1.printStackTrace();
83 }
84 PrivateKey privateKey = null;
85 KeyStore tmpKs = keyStore;
86 try
87 {
88 privateKey = (PrivateKey)tmpKs.getKey(alias, this.passSignature.toCharArray());
89 }
90 catch (UnrecoverableKeyException e)
91 {
92 System.err.println("No existe clave privada para firmar.");
93 //e.printStackTrace();
94 }
95 catch (KeyStoreException e)
96 {
97 System.err.println("No existe clave privada para firmar.");
98 //e.printStackTrace();
99 }
100 catch (NoSuchAlgorithmException e)
101 {
102 System.err.println("No existe clave privada para firmar.");
103 //e.printStackTrace();
104 }
105 Provider provider = keyStore.getProvider();
106
107 DataToSign dataToSign = createDataToSign();
108
109 FirmaXML firma = new FirmaXML();
110
111 Document docSigned = null;
112 try
113 {
114 Object[] res = firma.signFile(certificate, dataToSign, privateKey, provider);
115 docSigned = (Document)res[0];
116 }
117 catch (Exception ex)
118 {
119 System.err.println("Error realizando la firma: " + ex.getMessage());
120 //ex.printStackTrace();
121 return;
122 }
123 String filePath = getPathOut() + File.separatorChar + getSignatureFileName();
124 System.out.println("Firma guardada en: " + filePath);
125
126 saveDocumenteDisk(docSigned, filePath);
127 }
128
129 protected abstract DataToSign createDataToSign();
130
131 protected abstract String getSignatureFileName();
132
133 protected abstract String getPathOut();
134
135 protected Document getDocument(String resource)
136 {
137 Document doc = null;
138 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
139 dbf.setNamespaceAware(true);
140 File file = new File(resource);
141 try
142 {
143 DocumentBuilder db = dbf.newDocumentBuilder();
144
145 doc = db.parse(file);
146 }
147 catch (ParserConfigurationException|SAXException|IOException|IllegalArgumentException ex)
148 {
149 System.err.println("Error al parsear el documento: " + ex.getMessage());
150 //ex.printStackTrace();
151 System.exit(‐1);
152 }
153 return doc;
154 }
155
156 private KeyStore getKeyStore()
157 throws CertificateException
158 {
159 KeyStore ks = null;
160 try
161 {
162 ks = KeyStore.getInstance("PKCS12");
163 ks.load(new FileInputStream(this.pathSignature), this.passSignature.toCharArray());
164 }
165 catch (KeyStoreException e)
166 {
167 System.err.println("Error: " + e.getMessage());
168 //e.printStackTrace();
169 }
170 catch (NoSuchAlgorithmException e)
171 {
172 System.err.println("Error: " + e.getMessage());
173 //e.printStackTrace();
174 }
175 catch (CertificateException e)
176 {
177 System.err.println("Error: " + e.getMessage());
178 // e.printStackTrace();
179 }
180 catch (IOException e)
181 {
182 System.err.println("Error: " + e.getMessage());
183 //e.printStackTrace();
184 }
185 return ks;
186 }
187
188 private static String getAlias(KeyStore keyStore)
189 {
190 String alias = null;
191 try
192 {
193 Enumeration nombres = keyStore.aliases();
194 while (nombres.hasMoreElements())
195 {
196 String tmpAlias = (String)nombres.nextElement();
197 if (keyStore.isKeyEntry(tmpAlias)) {
198 alias = tmpAlias;
199 }
200 }
201 }
202 catch (KeyStoreException e)
203 {
204 System.err.println("Error: " + e.getMessage());
205 //e.printStackTrace();
206 }
207 return alias;
208 }
209
210 public static void saveDocumenteDisk(Document document, String pathXml)
211 {
212 try
213 {
214 DOMSource source = new DOMSource(document);
215 StreamResult result = new StreamResult(new File(pathXml));
216
217 TransformerFactory transformerFactory = TransformerFactory.newInstance();
218
219 Transformer transformer = transformerFactory.newTransformer();
220 transformer.transform(source, result);
221 }
222 catch (TransformerConfigurationException e)
223 {
224 System.err.println("Error: " + e.getMessage());
225 //e.printStackTrace();
226 }
227 catch (TransformerException e)
228 {
229 System.err.println("Error: " + e.getMessage());
230 //e.printStackTrace();
231 }
232 }
233 }
1 import es.mityc.firmaJava.libreria.xades.DataToSign;
2 import es.mityc.firmaJava.libreria.xades.XAdESSchemas;
3 import es.mityc.javasign.EnumFormatoFirma;
4 import es.mityc.javasign.xml.refs.InternObjectToSign;
5 import es.mityc.javasign.xml.refs.ObjectToSign;
6 import java.security.cert.CertificateException;
7 import org.w3c.dom.Document;
8
9 public class XAdESBESSignature
10 extends GenericXMLSignature
11 {
12 private static String nameFile;
13 private static String pathFile;
14 private String fileToSign;
15
16 public XAdESBESSignature(String fileToSign)
17 {
18 this.fileToSign = fileToSign;
19 }
20
21 public static void firmar(String xmlPath, String pathSignature, String passSignature, String pathOut, String nameFileOut)
22 throws CertificateException
23 {
24 XAdESBESSignature signature = new XAdESBESSignature(xmlPath);
25 signature.setPassSignature(passSignature);
26 signature.setPathSignature(pathSignature);
27 pathFile = pathOut;
28 nameFile = nameFileOut;
29
30 signature.execute();
31 }
32
33 protected DataToSign createDataToSign()
34 {
35 DataToSign datosAFirmar = new DataToSign();
36
37 datosAFirmar.setXadesFormat(EnumFormatoFirma.XAdES_BES);
38
39 datosAFirmar.setEsquema(XAdESSchemas.XAdES_132);
40 datosAFirmar.setXMLEncoding("UTF‐8");
41 datosAFirmar.setEnveloped(true);
42 datosAFirmar.addObject(new ObjectToSign(new InternObjectToSign("comprobante"), "contenido comprobante", null, "text/xml
43 datosAFirmar.setParentSignNode("comprobante");
44
45 Document docToSign = getDocument(this.fileToSign);
46 datosAFirmar.setDocument(docToSign);
47
48 return datosAFirmar;
49 }
50
51 protected String getSignatureFileName()
52 {
53 return nameFile;
54 }
55
56 protected String getPathOut()
57 {
58 return pathFile;
59 }
60 }
1 Dim jar = "c:\SignSRI.jar"
2 Dim certificado = "c:\certificado.p12"
3 Dim passCertificado = "constraseña"
4 Dim xmlIn = "c:\1‐001‐020000000543.XML"
5 Dim xmlOut = "c:\"
6 Dim fileOut = "factura_sign.xml"
7
8 Shell("cmd.exe /K java ‐jar" & " " & jar & " " & certificado & " " & passCertificado & " " & xmlIn & " " & xmlOut & " " & fi
Comentarios (128) AÑADIR NUEVO
Por otro lado, yo programo en .net y la solución a este problema de la Firma Electrónica de los XML lo encontré en un sitio y lo publico
ahora aquí. Ojo, recalco que no es una solución mía propia de mi propiedad jejeje, se trata de un proyecto que alguna buena persona lo
realizó y lo compartió, pero yo le hice algunos ajustes. . Por el momento estoy haciendo unas modificaciones para que funcione "además
del certificado en archivo" con token pero no lo he logrado, apenas tenga la solución de igual manera lo publicaré o si alguien puede
aportar, mucho mejor.
Descarguen el proyecto:
Por otro lado, yo programo en .net y la solución a este problema de la Firma Electrónica de los XML lo encontré en un sitio y lo publico
ahora aquí. Ojo, recalco que no es una solución mía propia de mi propiedad jejeje, se trata de un proyecto que alguna buena persona lo
realizó y lo compartió, pero yo le hice algunos ajustes. sviudes.blogspot.com/2010/05/facturae-con-net-y-c.html. Por el momento estoy
haciendo unas modificaciones para que funcione "además del certificado en archivo" con token pero no lo he logrado, apenas tenga la
solución de igual manera lo publicaré o si alguien puede aportar, mucho mejor.
Error: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded
Error: Uninitialized keystore
Error: Uninitialized keystore
No existe clave privada para firmar.
Error realizando la firma: null
Te comento que estoy probando en la misma maquina donde tengo instalado el software gratuito de firma y autorizacion que proporciona
el SRI y el archivo de firma está instalado en esta maquina, mi intencion es ya no usar el software del SRI y tratar de hacerlo con el codigo
que compartistes.
Gracias nuevamente
Rolando
0 CITAR RESPONDER
Adicionalmente te consulto, que tan dicil es implementarlo en VFP9, pregunto esto ya que no se como programar en JAVA, puedes darme
alguna orientacion para realizar el firmado desde VFP.
0 CITAR RESPONDER
Adicionalmente te consulto, que tan dicil es implementarlo en VFP9, pregunto esto ya que no se como programar en JAVA, puedes
darme alguna orientacion para realizar el firmado desde VFP.
0 CITAR RESPONDER
Gracias Cristhian, investigué un poco sobre los certificados y le hice el siguiente cambio a excecute() y me funcionó,
Clic aquí
0 CITAR RESPONDER
0 CITAR RESPONDER
www.subirimagenes.net/i/150507061826533408.jpg
www.subirimagenes.net/i/150507061828109483.jpg
www.subirimagenes.net/i/150507061829857531.jpg
www.subirimagenes.net/i/150507061839129055.jpg
1 CITAR RESPONDER
...y todo funcionó ok. Posteriormente probé el envío del comprobante firmado al SRI con mi proyecto que lo subí a este blog y (aunque
tenía mis dudas) todo funcionó 100%.
Agradezco mucho que hayas compartido este proyecto junto con la dll.
Veo que cada ves nos unimos más a este blog y a la filosofía de que "El conocimiento debe ser libre"
1 CITAR RESPONDER
LOCAL lc_RutaP12,lc_Pass,lc_XML_IN,lc_XML_OUT,lc_NameFileOut,ln_Result
lc_RutaP12 = "C:\RutaArchivoP12\certificado.p12"
lc_Pass = "Password"
lc_XML_IN = "C:\TMPS\xFile.XML"
lc_XML_OUT = "C:\TMPS\"
lc_NameFileOut = "xFile_sign.xml"
FirmarXMLXades.GuardarDocumentoFirmado(GuardarDocumento.FileName)
Soy nuevo en JAVA alguno me puede ayuda con alguna guia como solucionarlo, si alguien requiere ayuda con PHP dejo mi mail
ricardodaniel83@gmail.com puedo compartir mi desarrllo.
0 CITAR RESPONDER
Para Firmar el XML no necesitas especificar ambiente, pero en el XML hay una etiqueta donde se especifica cual es el ambiente, el cual ya
debe estar señalada antes de firmarlo
0 CITAR RESPONDER
ESte es el error........
ESte es el error........
si ya esta instalado en el ordenador y no necesitas poner la usb para validar, si solo con el CN del certificado es suficiente
0 CITAR RESPONDER