public void FirmarUserPDF_POLICY_SELLO_GENERICO_Button_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. //string path = Environment.CurrentDirectory; //FileStream fs = File.OpenRead(path + "\\resources\\exampleSign.pdf"); Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //Obtengo la imagen a estampar Stream stampImage = assembly.GetManifestResourceStream(Global.DEMO_STAMPER_PATH); byte[] image = new byte[stampImage.Length]; stampImage.Read(image, 0, image.Length); String imageB64 = System.Convert.ToBase64String(image); // Enviamos a firmar el documento //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "PDF_SELLOIMAGEN.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PAdES_BASIC; doc.tipo = typeFile.PDF; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_BASIC, typeSign.ATTACHED); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "1"); //creamos el rectangle rectangle r = PolicyUtil.newRectangle(140, 200, 100, 50); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(r)); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void FirmarServerPDFButton_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. //string path = Environment.CurrentDirectory; //FileStream fs = File.OpenRead(path + "\\resources\\exampleSign.pdf"); Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //byte[] datos_a_firmar = File.ReadAllBytes(@"C:\598MB.pdf"); //FileStream strm = new FileStream(@"C:\598MB.pdf", FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous); //datos_a_firmar_grande = new byte[strm.Length]; //IAsyncResult result = strm.BeginRead(datos_a_firmar_grande, 0, datos_a_firmar_grande.Length, new AsyncCallback(CompleteRead), strm); // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); // Enviamos a firmar el documento al servidor y obtenemos el identificador final de la firma. //idFirma = clienteViafirma.signByServerWithTypeFileAndFormatSign("FicheroEjemploServer.pdf", datos_a_firmar, Global.ALIAS, Global.PASS_CERT, typeFile.PDF, typeFormatSign.PDF_PKCS7); //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "PDF_ejemplo.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PAdES_LTV; doc.tipo = typeFile.PDF; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_LTV, typeSign.ATTACHED); idFirma = clienteViafirma.SignByServerWithPolicy(pol, doc, Global.ALIAS, Global.PASS_CERT); // Generamos la url a la página que gestiona la comunicación con Viafirma. // Uri url = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/ResultadoFirmaServidor.aspx")); // Log.Debug("Redireccionado al usuario a: " + url); // Guardamos el Id de Firma HttpContext.Current.Session["idFirma"] = idFirma; // Redirecciona a la url // HttpContext.Current.Response.Redirect(url.AbsoluteUri); }
public async void Firmar_ClickAsync(object sender, EventArgs e) { // Iniciamos el proceso de autenticar redireccionando el usuario a Viafirma. ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); AuthOperationRequest authRequest = new AuthOperationRequest(); authRequest.AutoSend = true; string sessionId = HttpContext.Current.Session.SessionID; string[] languages = HttpContext.Current.Request.UserLanguages; string locale = languages[0]; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_BASIC, typeSign.ATTACHED); //Creamos el rectangle rectangle r = PolicyUtil.newRectangle(40, 10, 550, 75); //Seteamos la politica PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "1"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(r)); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_HIDE_STATUS, "true"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_TEXT, "Firmado por [CN] con DNI [SERIALNUMBER]\ntrabajador de [O] en el departamento de [OU]"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_TYPE, "QR-BAR-H"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_ROTATION_ANGLE, "90"); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); OperationFile file = new OperationFile(); file.Filename = "example.pdf"; file.Base64Content = System.Convert.ToBase64String(datos_a_firmar); file.Policy = pol; List <OperationFile> files = new List <OperationFile>(); files.Add(file); desktopInvocation = await clienteViafirma.PrepareSignatureForDirectDesktopAsync(authRequest, files, sessionId, locale); System.Console.Write("OperationId: " + desktopInvocation.OperationId); }
public void signByClient(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //Obtengo el certificado con el cual voy a firmar Stream certificate = assembly.GetManifestResourceStream(Global.DEMO_P12_PATH); String certificatePass = "******"; // Enviamos a firmar el documento //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "clientSigned.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PAdES_BASIC; doc.tipo = typeFile.PDF; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_BASIC, typeSign.ENVELOPED); //PolicyUtil.AddParameter(pol, PolicyParams.SIGNATURE_ALGORITHM, "SHA1withRSA"); //PolicyUtil.AddParameter(pol, PolicyParams.DIGEST_METHOD, "SHA1"); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; //Hacemos la llamada a la firma en cliente signId = clienteViafirma.SignByClient(certificate, certificatePass, pol, doc); // Guardamos el Id de Firma HttpContext.Current.Session["signId"] = signId; }
public void FirmarServerPDFButton_T_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. //string path = Environment.CurrentDirectory; //FileStream fs = File.OpenRead(path + "\\resources\\exampleSign.pdf"); Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "FicheroEjemplo.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PDF_PKCS7_T; doc.tipo = typeFile.PDF; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PDF_PKCS7_T, typeSign.ENVELOPED); idFirma = clienteViafirma.SignByServerWithPolicy(pol, doc, Global.ALIAS, Global.PASS_CERT); // Generamos la url a la página que gestiona la comunicación con Viafirma. // Uri url = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/ResultadoFirmaServidor.aspx")); // Log.Debug("Redireccionado al usuario a: " + url); // Guardamos el Id de Firma HttpContext.Current.Session["idFirma"] = idFirma; // Redirecciona a la url // HttpContext.Current.Response.Redirect(url.AbsoluteUri); }
public void FirmarUserCADES_DETACHED(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_CADES_T_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); // Enviamos a firmar el documento //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "documento.CADES"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.CAdES_T; doc.tipo = typeFile.doc; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.CAdES_T, typeSign.DETACHED); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".CADES"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void FirmarUserXMLButton_Click(object sender, EventArgs e) { Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_XML_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); string originalHash = System.Convert.ToBase64String(datos_a_firmar); try { ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); string idFirma; //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "prueba.xml"; doc.datos = Encoding.ASCII.GetBytes(originalHash); doc.typeFormatSign = typeFormatSign.XADES_EPES_ENVELOPED; doc.tipo = typeFile.hash; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.XADES_EPES_ENVELOPED, typeSign.ENVELOPED); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. idFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".xml"; clienteViafirma.Sign(idFirma); } catch (Exception ex) { Console.Write(ex.StackTrace); } }
public void InitDigitalizedButton_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //recuperamos la clave pública de encriptación Stream pemStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EjemploWebViafirmaClientDotNet.resources.xnoccio.pem"); String pem = new StreamReader(pemStream).ReadToEnd(); // En algunos casos, por ejemplo en el arranque de la aplicación, puede ser interesante comprobar conectividad System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "signatureDigitalized.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.DIGITALIZED_SIGN; doc.tipo = typeFile.PDF; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.DIGITALIZED_SIGN, typeSign.ATTACHED); //Indica el color de fondo de la pantalla (para aquellos dispositivos de firma que lo permitan - dispositivos móviles) // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_BACK_COLOUR, "#0000FF"); //Indica el color de la firma de la pantalla (para aquellos dispositivos de firma que lo permitan - dispositivos móviles) PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_COLOUR, "#FF0000"); //Indica el texto de ayuda que aparece en la pantalla PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_HELP_TEXT, "Texto de ayuda aportado por el integrador"); //Logo a mostrar (para aquellos dispositivos de firma que lo permitan - dispositivos móviles ) // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_LOGO, logoStamp); //Rectangulo donde se fija la firma // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_RECTANGLE, new Rectangle(400,60,160,120)); //Biometric alias - pass son utilizados para firmar los datos biometricos en servidor (el alias debe existir en el servidor) PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_BIOMETRIC_ALIAS, "xnoccio"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_BIOMETRIC_PASS, "12345"); //Clave publica en formato pem con la que cifrar los datos biometricos, si no se indica no se cifran PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_BIOMETRIC_CRYPTO_PEM, pem); //Pagina donde insertar la firma, -1 para la ultima pagina, si no se indica, en iOS/Android se permitirá seleccionar la pagina/s manualmente, en tabletas digitalizadoras se pondrá en la última página // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_PAGE, -1); //Firma en servidor del documento PDF (en este ejemplo se usa el mismo certificado que en la firma en servidor de los datos biométricos) PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_ALIAS, "xnoccio"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGN_PASS, "12345"); //Información adicional mapeada como título de firma (por ejemplo el nombre del firmante) PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_SIGNATURE_INFO, "Firmante de ejemplo"); //Estados permitidos para localización GPS (para aquellos dispositivos de firma que lo permitan - dispositivos móviles) // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_LOCATION_STATUS, "0"); //Indica los stylus permitidos (para aquellos dispositivos de firma que lo permitan - dispositivos móviles) // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_PRESSURE_STYLUS, ""); //Indica si se muestra o no valores de presión (para aquellos dispositivos de firma que lo permitan - dispositivos móviles) // PolicyUtil.AddParameter(pol, PolicyParams.DIGITALIZED_PRESSURE_INFO, ""); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void Firmar_Button_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH_10_PAGS); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //Obtengo la imagen a estampar Stream stampImage = assembly.GetManifestResourceStream(Global.DEMO_STAMPER_PATH); byte[] image = new byte[stampImage.Length]; stampImage.Read(image, 0, image.Length); String imageB64 = System.Convert.ToBase64String(image); // Enviamos a firmar el documento //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "PDF_SELLOIMAGEN.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PAdES_BASIC; doc.tipo = typeFile.PDF; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_BASIC, typeSign.ATTACHED); //Al indicar como página el caráter especial "0", la platforma entiende que se desea incorporar el justificante de firma en TODAS las paginas PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "0"); //Se puede insertar justificantes en varias páginas (no todas) del siguiente modo //ArrayList pages = new ArrayList(); //pages.Add("1"); //Se puede usar -1 para referenciar a la última página //pages.Add("3"); //pages.Add("5"); //pages.Add("7"); //pages.Add("9"); //PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, PolicyUtil.ObjectToJson(pages)); //Creamos el rectangle rectangle r = PolicyUtil.newRectangle(100, 0, 400, 15); //Seteamos la politica PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(r)); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_HIDE_STATUS, "true"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_TEXT, "Firmado por [CN] - NIF [SERIALNUMBER] - [vCSVKey]"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_TRANSPARENT_BACKGROUND, "true"); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void FirmarUserPDFImageButton_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //Recuperamos la imagen de sello Stream fsImage = assembly.GetManifestResourceStream(Global.DEMO_IMAGE_LOGO_PATH); byte[] image = new byte[fsImage.Length]; fsImage.Read(image, 0, image.Length); String imageB64 = System.Convert.ToBase64String(image); //Creamos el rectangle donde se posicionará el sello rectangle _rectangle = new rectangle(); _rectangle.height = 50; _rectangle.width = 100; _rectangle.x = 120; _rectangle.y = 50; // Enviamos a firmar el documento // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "FicheroEjemplo.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PDF_PKCS7; doc.tipo = typeFile.PDF; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PDF_PKCS7, typeSign.ENVELOPED); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "1"); //creamos el rectangle PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(_rectangle)); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_HIDE_STATUS, "true"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_IMAGE_STAMPER, imageB64); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void FirmarUserXMLButton_Click(object sender, EventArgs e) { typeFormatSign typeFormatSign = typeFormatSign.XMLDSIG; Button btn = (Button)sender; switch (btn.CommandName) { case "XMLDSIG": typeFormatSign = typeFormatSign.XMLDSIG; break; case "XADES_BES": typeFormatSign = typeFormatSign.XADES_BES; break; case "XADES_EPES": typeFormatSign = typeFormatSign.XADES_EPES_ENVELOPED; break; case "XADES_T": typeFormatSign = typeFormatSign.XADES_T_ENVELOPED; break; case "XADES_XL": typeFormatSign = typeFormatSign.XADES_XL_ENVELOPED; break; case "XADES_A": typeFormatSign = typeFormatSign.XADES_A_ENVELOPED; break; } Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_XML_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); try { ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); string idFirma; //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "prueba.xml"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign; doc.tipo = typeFile.XML; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign, typeSign.ENVELOPED); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. idFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".xml"; clienteViafirma.Sign(idFirma); } catch (Exception ex) { Console.Write(ex.StackTrace); } }
public void FirmarServerPDFImageButton_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); //Recuperamos la imagen de sello Stream fsImage = assembly.GetManifestResourceStream(Global.DEMO_IMAGE_LOGO_PATH); byte[] image = new byte[fsImage.Length]; fsImage.Read(image, 0, image.Length); String imageB64 = System.Convert.ToBase64String(image); //Creamos el rectangle donde se posicionará el sello rectangle _rectangle = new rectangle(); _rectangle.height = 50; _rectangle.width = 100; _rectangle.x = 200; _rectangle.y = 100; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "FicheroEjemploServer.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PDF_PKCS7; doc.tipo = typeFile.PDF; //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PDF_PKCS7, typeSign.ENVELOPED); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "1"); //creamos el rectangle PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(_rectangle)); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_HIDE_STATUS, "true"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_IMAGE_STAMPER, imageB64); // Enviamos a firmar el documento al servidor y obtenemos el identificador final de la firma. idFirma = clienteViafirma.SignByServerWithPolicy(pol, doc, Global.ALIAS, Global.PASS_CERT); // Generamos la url a la página que gestiona la comunicación con Viafirma. // Uri url = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/ResultadoFirmaServidor.aspx")); // Log.Debug("Redireccionado al usuario a: " + url); // Guardamos el Id de Firma HttpContext.Current.Session["idFirma"] = idFirma; // Redirecciona a la url // HttpContext.Current.Response.Redirect(url.AbsoluteUri); }
public void FirmarServerPDFButton_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos el objeto documento con los datos a firmar typeFormatSign tipoFirma = typeFormatSign.PAdES_BES; documento doc = new documento(); doc.nombre = "PDF_SELLOIMAGEN.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = tipoFirma; doc.tipo = typeFile.PDF; //Obtengo la imagen a estampar Stream stampImage = assembly.GetManifestResourceStream(Global.DEMO_STAMPER_PATH); byte[] image = new byte[stampImage.Length]; stampImage.Read(image, 0, image.Length); String imageB64 = System.Convert.ToBase64String(image); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(tipoFirma, typeSign.DETACHED); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "1"); //Creamos el rectangle rectangle r = PolicyUtil.newRectangle(40, 100, 300, 240); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(r)); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_IMAGE_STAMPER, imageB64); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_TEXT, "Prueba Firmado por [CN]\ncon DNI [SERIALNUMBER]\ntrabajador de [O]\nen el departamento de [OU]"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_HIDE_STATUS, "true"); idFirma = clienteViafirma.SignByServerWithPolicy(pol, doc, Global.ALIAS, Global.PASS_CERT); //Obtengo la infirmación del documento firmado byte[] signedDoc = clienteViafirma.getDocumentoCustodiado(idFirma); firmaInfoViafirma info = clienteViafirma.getSignInfo(idFirma); string signTimeStamp = info.signTimeStamp; //tsa_cert_notafter usuarioGenericoViafirmaEntry[] usersInfo = info.properties; foreach (usuarioGenericoViafirmaEntry userInfo in usersInfo) { if ("tsa_cert_notafter".Equals(userInfo.key)) { Console.WriteLine(userInfo.value); } } // Generamos la url a la página que gestiona la comunicación con Viafirma. // Uri url = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/ResultadoFirmaServidor.aspx")); // Log.Debug("Redireccionado al usuario a: " + url); // Guardamos el Id de Firma HttpContext.Current.Session["idFirma"] = idFirma; // Redirecciona a la url // HttpContext.Current.Response.Redirect(url.AbsoluteUri); }
public void Firmar_Button_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. //string path = Environment.CurrentDirectory; //FileStream fs = File.OpenRead(path + "\\resources\\exampleSign.pdf"); Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); // Enviamos a firmar el documento //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "PDF_SELLOIMAGEN.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PAdES_BASIC; doc.tipo = typeFile.PDF; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_BASIC, typeSign.ATTACHED); // Solo certificados con: // O="FMNT" o (1.3.6.1.4.1.5734.1.8 existe e ISSUER.CN="AVANSI CERTIFICADOS DIGITALES") List <Dictionary <String, String> > filters = new List <Dictionary <String, String> >(); Dictionary <String, String> filter1 = new Dictionary <String, String>(); filter1.Add("O", "FNMT"); Dictionary <String, String> filter2 = new Dictionary <String, String>(); filter2.Add("1.3.6.1.4.1.5734.1.8", "*"); filter2.Add("ISSUER.CN", "AVANSI CERTIFICADOS DIGITALES"); filters.Add(filter1); filters.Add(filter2); PolicyUtil.AddParameter(pol, PolicyParams.FILTER_CERTIFICATE_BY, PolicyUtil.ObjectToJson(filters)); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void FirmarUserPDFButton_Click(object sender, EventArgs e) { typeFormatSign typeFormatSign = typeFormatSign.PDF_PKCS7; Button btn = (Button)sender; switch (btn.CommandName) { case "PDF_PKCS7": typeFormatSign = typeFormatSign.PDF_PKCS7; break; case "PDF_PKCS7_T": typeFormatSign = typeFormatSign.PDF_PKCS7_T; break; case "PAdES_BASIC": typeFormatSign = typeFormatSign.PAdES_BASIC; break; case "PAdES_BES": typeFormatSign = typeFormatSign.PAdES_BES; break; case "PAdES_EPES": typeFormatSign = typeFormatSign.PAdES_EPES; break; } //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); // Enviamos a firmar el documento // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible try { System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); } catch (System.Web.Services.Protocols.SoapException exc) { System.Console.WriteLine(exc.Message); } // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirma = null; try { //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "FicheroEjemplo.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign; doc.tipo = typeFile.PDF; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign, typeSign.ENVELOPED); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. idTemporalFirma = clienteViafirma.PrepareSignWithPolicy(pol, doc); System.Console.Write("idTemporalFirma: " + idTemporalFirma); } catch (Exception exc) { System.Console.WriteLine(exc.Message); String messageError = exc.Message; Uri url = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/errorPage.aspx?errorMessage=" + exc.Message)); HttpContext.Current.Response.Redirect(url.AbsoluteUri); return; } System.Console.Write("idTemporalFirma: " + idTemporalFirma); //Logica del ejemplo para descagar el fichero con la extension correcta Session["extension"] = ".pdf"; // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario a Viafirma para la firma del documento con el // identificador de firma indicado. clienteViafirma.Sign(idTemporalFirma); }
public void FirmarUserCadesTDetached_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos los documentos a firmar. //Docx de ejemplo Assembly assembly = Assembly.GetExecutingAssembly(); Stream fsdocx = assembly.GetManifestResourceStream(Global.DEMO_CADES_T_PATH); byte[] datos_a_firmarDocx = new byte[fsdocx.Length]; fsdocx.Read(datos_a_firmarDocx, 0, datos_a_firmarDocx.Length); //XML de ejemplo Stream fsxml = assembly.GetManifestResourceStream(Global.DEMO_FILE_XML_PATH); byte[] datos_a_firmarXml = new byte[fsdocx.Length]; fsxml.Read(datos_a_firmarXml, 0, datos_a_firmarXml.Length); //Creamos el objeto documento del docx con los datos a firmar en CAdES_T documento docx = new documento(); docx.nombre = "firmaDocx.CAdES"; docx.datos = datos_a_firmarDocx; docx.typeFormatSign = typeFormatSign.CAdES_T; docx.tipo = typeFile.doc; //Creamos el objeto documento del xml con los datos a firmar en XAdES_T documento xml = new documento(); xml.nombre = "firmaXml.XAdES"; xml.datos = datos_a_firmarXml; xml.typeFormatSign = typeFormatSign.XADES_T_ENVELOPED; xml.tipo = typeFile.xlm; // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); // Registramos los documento que deseamos firmar en un listado. List <string> idsFirma = new List <string>(); //Creamos la politica de firma del docx en CAdES policy pol = PolicyUtil.newPolicy(typeFormatSign.CAdES_T, typeSign.DETACHED); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirmaCAdES = clienteViafirma.PrepareSignWithPolicy(pol, docx); //Creamos la politica de firma del xml en XAdES pol = PolicyUtil.newPolicy(typeFormatSign.XADES_T_ENVELOPED, typeSign.DETACHED); // Registramos el documento que deseamos firmar. Obteniendo un identificador temporal. // Este identificador temporal no es necesario que sea almacenado ya que sólo tiene validez durante el proceso de firma. string idTemporalFirmaXAdES = clienteViafirma.PrepareSignWithPolicy(pol, xml); //Añadimos los ids temporales de las firmas que hemos preparado idsFirma.Add(idTemporalFirmaCAdES); idsFirma.Add(idTemporalFirmaXAdES); // Iniciamos el proceso de firma redireccionando al usuario a Viafirma.. // Esto redireccionará al usuario para la firma de los documentos // con una sola intervención del usuario. clienteViafirma.solicitarFirmasIndependientes(idsFirma.ToArray()); }
public void FirmarServerPDFButton_Click(object sender, EventArgs e) { //Recuperamos la instancia del cliente ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); // Recuperamos el documento a firmar. //string path = Environment.CurrentDirectory; //FileStream fs = File.OpenRead(path + "\\resources\\exampleSign.pdf"); Assembly assembly = Assembly.GetExecutingAssembly(); Stream fs = assembly.GetManifestResourceStream(Global.DEMO_FILE_PDF_PATH); byte[] datos_a_firmar = new byte[fs.Length]; fs.Read(datos_a_firmar, 0, datos_a_firmar.Length); // En algunos casos, por ejemplo en el arranque de la aplicación puede ser interesante // Comprobar que efectivamente el servidor de firma está disponible System.Console.Write(clienteViafirma.ping("Prueba Conexión") + "\n"); // Enviamos a firmar el documento al servidor y obtenemos el identificador final de la firma. //idFirma = clienteViafirma.signByServerWithTypeFileAndFormatSign("FicheroEjemploServer.pdf", datos_a_firmar, Global.ALIAS, Global.PASS_CERT, typeFile.PDF, typeFormatSign.PDF_PKCS7); //Creamos el objeto documento con los datos a firmar documento doc = new documento(); doc.nombre = "PDF_SELLOIMAGEN.pdf"; doc.datos = datos_a_firmar; doc.typeFormatSign = typeFormatSign.PAdES_BASIC; doc.tipo = typeFile.PDF; //Obtengo la imagen a estampar Stream stampImage = assembly.GetManifestResourceStream(Global.DEMO_STAMPER_PATH); byte[] image = new byte[stampImage.Length]; stampImage.Read(image, 0, image.Length); String imageB64 = System.Convert.ToBase64String(image); //Creamos la politica de firma policy pol = PolicyUtil.newPolicy(typeFormatSign.PAdES_BASIC, typeSign.ATTACHED); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_PAGE, "1"); //Creamos el rectangle rectangle r = PolicyUtil.newRectangle(40, 100, 300, 240); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_RECTANGLE, PolicyUtil.rectangleToJson(r)); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_IMAGE_STAMPER, imageB64); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_TEXT, "Prueba Firmado por [CN]\ncon DNI [SERIALNUMBER]\ntrabajador de [O]\nen el departamento de [OU]"); PolicyUtil.AddParameter(pol, PolicyParams.DIGITAL_SIGN_STAMPER_HIDE_STATUS, "true"); idFirma = clienteViafirma.SignByServerWithPolicy(pol, doc, Global.ALIAS, Global.PASS_CERT); // Generamos la url a la página que gestiona la comunicación con Viafirma. // Uri url = new Uri(HttpContext.Current.Request.Url, HttpContext.Current.Response.ApplyAppPathModifier("~/ResultadoFirmaServidor.aspx")); // Log.Debug("Redireccionado al usuario a: " + url); // Guardamos el Id de Firma HttpContext.Current.Session["idFirma"] = idFirma; // Redirecciona a la url // HttpContext.Current.Response.Redirect(url.AbsoluteUri); }