// Set this city to a new policy public void setPolicy(policy newPolicy) { if (newPolicy == policy.neutral && Policy == policy.eco) { Region.affect_some_nearby_trees(0.9f, -0.4f, true); } else if (newPolicy == policy.neutral && Policy == policy.eco) { Region.affect_some_nearby_trees(0.9f, 0.2f, true); } Policy = newPolicy; switch (newPolicy) { case policy.industry: sr.sprite = industrySprite; Region.affect_some_nearby_trees(0.9f, 0.5f); break; case policy.neutral: sr.sprite = neutralSprite; break; case policy.eco: sr.sprite = ecoSprite; Region.affect_some_nearby_trees(0.9f, 0.4f); break; case policy.none: sr.sprite = untakenSprite; break; } }
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); }
// Update is called once per frame void Update() { if (PlayerManager.Gamestate == gamestate.sea_levels_rose) { return; } // Take in player input for switching policies for (int i = 0; i < 2; i++) { int Player = (i == 0) ? (int)player.A : (int)player.B; int currentPolicy = (int)policies[Player]; policy newPolicy = (policy)currentPolicy; XboxController controller = player_data.controllers[Player]; if (RCI.GetButtonDown(XboxButton.DPadDown, controller)) { newPolicy = (policy)Mathf.Clamp(currentPolicy - 1, 1, policiesCount - 1); } else if (RCI.GetButtonDown(XboxButton.DPadUp, controller)) { newPolicy = (policy)Mathf.Clamp(currentPolicy + 1, 1, policiesCount - 1); } ChangePolicyBonusDisplay(i, currentPolicy, newPolicy); if (newPolicy != policies[Player]) { policies[Player] = newPolicy; //city.updatePoliciesAll(Player, (policy)newPolicy); // Play corresponding sound effect if (newPolicy == policy.industry) { mixer.playSFX("ind policy"); } else if (newPolicy == policy.neutral) { mixer.playSFX("population growth"); } else if (newPolicy == policy.eco) { mixer.playSFX("eco policy"); } } } // Update policy displays for (int pol = 0; pol < policiesCount; pol++) { if (p1PolicyDisplays[pol] != null) { setPolicySR(p1PolicyDisplays[pol], policies[1] == (policy)pol); } if (p2PolicyDisplays[pol] != null) { setPolicySR(p2PolicyDisplays[pol], policies[2] == (policy)pol); } } }
public void Autenticar_Click(object sender, EventArgs e) { // Iniciamos el proceso de autenticar redireccionando el usuario a Viafirma. ViafirmaClient clienteViafirma = ViafirmaClientFactory.GetInstance(); policy pol = new policy(); clienteViafirma.AuthWithPolicy(pol); }
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 deleteUserFromPermissions(string userSearchPath, CognosReportNetService crnService, string sPath) { //set searchPath of the required folder //searchPathMultipleObject spMulti = new searchPathMultipleObject(); //spMulti.Value = sPath; report pFolder = (report)crnService.query(sPath, new propEnum[]{propEnum.searchPath,propEnum.policies},new sort[]{},new queryOptions())[0]; //keep trak if the aecurity object was found in the permissions bool found = false; for (int i = 0; i < pFolder.policies.value.Length && !found; i ++) { policy policy = pFolder.policies.value[i]; //If the security object already exists, update its permissions if(policy.securityObject.searchPath.value.Equals(userSearchPath)) { found = true; } } //if the security object exists, remove it from the array of permissions if (found) { policy[] newPolicies = new policy[pFolder.policies.value.Length-1]; policyArrayProp pArray = new policyArrayProp(); int newPolicyCount = 0; for (int i = 0; i < pFolder.policies.value.Length ; i ++) { policy policy = pFolder.policies.value[i]; if(!policy.securityObject.searchPath.value.Equals(userSearchPath)) { newPolicies[newPolicyCount] = new policy (); newPolicies[newPolicyCount].securityObject = pFolder.policies.value[i].securityObject; newPolicies[newPolicyCount].permissions = pFolder.policies.value[i].permissions; newPolicyCount = newPolicyCount + 1; } } //If the security object does not exist, nothing to delete pArray.value = newPolicies; pFolder.policies = pArray; crnService.update(new baseClass[]{pFolder},new updateOptions() ); } }
public void Test() { IRazorTemplateGenerator generator = new RazorTemplateGenerator(); var p = new policy { policyholders = new PolicyHolders { primarypolicyholder = new PolicyHolder { firstname = "jane", lastname = "doe" } } }; generator.RegisterTemplate <policy>(ResourceHelper.TestView); generator.CompileTemplates(); var output = generator.GenerateOutput(p); string byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()); if (output.StartsWith(byteOrderMarkUtf8)) { output = output.Remove(0, byteOrderMarkUtf8.Length); } output = output.Replace(Environment.NewLine, string.Empty); var xmldoc = XDocument.Parse(output); //Console.Out.WriteLine(output2); string formattedXml = XElement.Parse(output).ToString(); Console.WriteLine(formattedXml); Console.In.ReadLine(); }
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 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 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 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); }
/// <summary> /// Parse ADMX Files /// </summary> /// <param name="FilePath">Admx File Path</param> /// <param name="Language">Subfolder of the Admx File with the corresponding Adml File</param> public AdmxParse(string FilePath, string Language) { categories = new List <category>(); policies = new List <policy>(); xPathMapping.LoadXml(Properties.Settings.Default.DevicePathMapping); FileInfo fiAdmx = new FileInfo(FilePath); if (fiAdmx.Exists) { FileInfo fiAdml = new FileInfo(Path.Combine(fiAdmx.DirectoryName, Language, fiAdmx.Name.Replace(".admx", ".adml"))); if (fiAdml.Exists) { xAdml.Load(fiAdml.FullName); } xAdmx.Load(FilePath); XmlNamespaceManager ns = new XmlNamespaceManager(xAdmx.NameTable); ns.AddNamespace("pd", xAdmx.DocumentElement.NamespaceURI); //Get categories foreach (XmlNode xCat in xAdmx.SelectNodes("/pd:policyDefinitions/pd:categories/pd:category", ns)) { try { var oRes = new category(); oRes.displayName = sResourceStringLookup(xCat.Attributes["displayName"].InnerText.Replace("$(string.", "").TrimEnd(')')); oRes.name = xCat.Attributes["name"].InnerText; if (xCat["parentCategory"] == null) { //oRes.parent = oRes.name; ??? oRes.parent = ""; categories.Add(oRes); continue; } oRes.parent = xCat["parentCategory"].Attributes["ref"].InnerText; if (categories.FirstOrDefault(t => t.name == oRes.parent) == null) { var xParent = xPathMapping.SelectSingleNode("//*[@name='" + oRes.parent + "']"); if (xParent != null) { XmlNode xPar = xParent; while (xPar != null) { if (xPar.Name != "#document") { if (xPar.Attributes["name"] != null) { string sPar = ""; if (xPar.ParentNode.Attributes["name"] != null) { sPar = xPar.ParentNode.Attributes["name"].Value; } categories.Add(new category() { name = xPar.Attributes["name"].Value, displayName = xPar.Attributes["displayname"].Value, parent = sPar }); } } xPar = xPar.ParentNode; } } else { string sDispName = oRes.parent; categories.Add(new category() { name = sDispName, displayName = sDispName, parent = "" }); } } categories.Add(oRes); } catch (Exception ex) { ex.Message.ToString(); } } //Get Policies foreach (XmlNode xPol in xAdmx.SelectNodes("/pd:policyDefinitions/pd:policies/pd:policy", ns)) { var oRes = new policy(); oRes.elements = new List <element>(); oRes.displayName = sResourceStringLookup(xPol.Attributes["displayName"].InnerText.Replace("$(string.", "").TrimEnd(')')); oRes.name = xPol.Attributes["name"].InnerText; oRes.state = policyState.NotConfigured; if (string.IsNullOrEmpty(oRes.displayName)) { oRes.displayName = oRes.name; } if (xPol.Attributes["explainText"] != null) { oRes.explainText = sResourceStringLookup(xPol.Attributes["explainText"].InnerText.Replace("$(string.", "").TrimEnd(')')); } oRes.parentCategory = categories.FirstOrDefault(t => t.name == xPol["parentCategory"].Attributes["ref"].InnerText); catLookup(xPol["parentCategory"].Attributes["ref"].InnerText); oRes.path = GetPath(xPol["parentCategory"].Attributes["ref"].InnerText); var pCat = categories.FirstOrDefault(t => t.name == xPol["parentCategory"].Attributes["ref"].InnerText); if (pCat != null) { oRes.displaypath = GetDisplayPath(pCat.displayName); } else { var xParent = xPathMapping.SelectSingleNode("//*[@name='" + xPol["parentCategory"].Attributes["ref"].InnerText + "']"); if (xParent != null) { string sDispName = xParent.Attributes["displayname"].Value; string sName = xParent.Attributes["name"].Value; string sParent = ""; if (xParent.ParentNode.Attributes["name"] != null) { sParent = xParent.ParentNode.Attributes["name"].Value; } categories.Add(new category() { name = sName, displayName = sDispName, parent = sParent }); oRes.displaypath = GetDisplayPath(sDispName); } } oRes.key = xPol.Attributes["key"].InnerText; if (xPol.Attributes["presentation"] != null) { oRes.presentation = sPresentationStringLookup(xPol.Attributes["presentation"].InnerText.Replace("$(presentation.", "").TrimEnd(')')); } switch (xPol.Attributes["class"].InnerText) { case "Machine": oRes.policyType = classType.Machine; break; case "User": oRes.policyType = classType.User; break; } //oRes.innerXML = xPol.InnerXml; if (xPol.Attributes["valueName"] != null) { if (xPol["enabledValue"] != null) { polEnableElement oElem = new polEnableElement(); oElem.ValueName = xPol.Attributes["valueName"].InnerText; oElem.ValueType = valueType.PolicyEnable; if (xPol["enabledValue"]["decimal"] != null) { try { oElem.enabledValue = uint.Parse(xPol["enabledValue"]["decimal"].Attributes["value"].Value); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } if (xPol["disabledValue"] != null) { if (xPol["disabledValue"]["decimal"] != null) { try { oElem.disabledValue = uint.Parse(xPol["disabledValue"]["decimal"].Attributes["value"].Value); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } oRes.elements.Add(oElem); } else { polEnableElement oElem = new polEnableElement(); oElem.ValueName = xPol.Attributes["valueName"].InnerText; oElem.ValueType = valueType.PolicyEnable; oElem.enabledValue = 1; oElem.disabledValue = 0; oRes.elements.Add(oElem); } } if (xPol["elements"] != null) { foreach (XmlNode xElem in xPol["elements"].ChildNodes) { if (xElem.Name == "#comment") { continue; } if (xElem.Name == "#text") { continue; } element oElem = new element(); switch (xElem.Name.ToLower()) { case "decimal": oElem = new decimalElement(); oElem.ValueType = valueType.Decimal; if (xElem.Attributes["minValue"] != null) { uint iRes = 0; if (uint.TryParse(xElem.Attributes["minValue"].InnerText, out iRes)) { ((decimalElement)oElem).minValue = iRes; } } if (xElem.Attributes["maxValue"] != null) { uint iRes = 0; if (uint.TryParse(xElem.Attributes["maxValue"].InnerText, out iRes)) { ((decimalElement)oElem).maxValue = iRes; } } break; case "enum": oElem = new enumElement(); oElem.ValueType = valueType.Enum; ((enumElement)oElem).valueList = new Dictionary <string, string>(); foreach (XmlNode xElemItem in xElem.SelectNodes("pd:item", ns)) { try { string sDisplayName = sResourceStringLookup(xElemItem.Attributes["displayName"].Value.Replace("$(string.", "").TrimEnd(')')); if (string.IsNullOrEmpty(sDisplayName)) { sDisplayName = xElemItem.Attributes["displayName"].Value.Replace("$(string.", "").TrimEnd(')'); } if (xElemItem["value"].FirstChild.Name == "decimal") { if (xElemItem["value"].FirstChild.Attributes.Count > 0) { ((enumElement)oElem).valueList.Add(sDisplayName, xElemItem["value"].FirstChild.Attributes["value"].Value); } else { ((enumElement)oElem).valueList.Add(sDisplayName, xElemItem["value"].FirstChild.InnerText); } } if (xElemItem["value"].FirstChild.Name == "string") { ((enumElement)oElem).valueList.Add(sDisplayName, xElemItem["value"].FirstChild.InnerText); } string sDefault = oRes.sPresentationdefaultValue(xElem.Attributes["id"].Value); if (!string.IsNullOrEmpty(sDefault)) { int iDef = 0; int.TryParse(sDefault, out iDef); ((enumElement)oElem).defaultItem = iDef; } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } break; case "boolean": oElem = new decimalElement(); oElem.ValueType = valueType.Boolean; ((decimalElement)oElem).minValue = 0; ((decimalElement)oElem).maxValue = 1; oElem.value = oRes.sPresentationdefaultValue(xElem.Attributes["id"].Value); break; case "list": oElem = new listElement(); oElem.ValueType = valueType.List; ((listElement)oElem).valueList = new Dictionary <string, string>(); if (xElem.Attributes["additive"] != null) { bool bRes = false; if (bool.TryParse(xElem.Attributes["additive"].Value, out bRes)) { ((listElement)oElem).additive = bRes; } else { ((listElement)oElem).additive = null; } } if (xElem.Attributes["explicitValue"] != null) { bool bRes = false; if (bool.TryParse(xElem.Attributes["explicitValue"].Value, out bRes)) { ((listElement)oElem).explicitValue = bRes; } else { ((listElement)oElem).explicitValue = null; } } break; case "text": oElem = new textElement(); oElem.ValueType = valueType.Text; break; default: xElem.Name.ToString(); break; } oElem.value = oRes.sPresentationdefaultValue(xElem.Attributes["id"].InnerText); //oElem.innerXML = xElem.OuterXml; //List do not have a Value, they have List of Valuenames and Values if (oElem.ValueType != valueType.List) { oElem.ValueName = xElem.Attributes["valueName"].InnerText; } if (xElem.Attributes["required"] != null) { bool bReq = false; if (bool.TryParse(xElem.Attributes["required"].InnerText, out bReq)) { oElem.required = bReq; } } if (xElem.Attributes["key"] != null) { oElem.key = xElem.Attributes["key"].Value; } oRes.elements.Add(oElem); } } if (xPol["enabledList"] != null) { EnableListElement oElem = new EnableListElement(); oElem.ValueType = valueType.Enum; oElem.enabledValueList = new List <enabledList>(); foreach (XmlNode xElem in xPol["enabledList"].SelectNodes("pd:item", ns)) { try { enabledList oResList = new enabledList(); if (xElem["value"].FirstChild.Name == "decimal") { oResList.type = valueType.Decimal; oResList.key = xElem.Attributes["key"].Value; oResList.valueName = xElem.Attributes["valueName"].Value; oResList.value = xElem["value"].FirstChild.Attributes["value"].Value; } if (xElem["value"].FirstChild.Name == "string") { oResList.type = valueType.Text; oResList.key = xElem.Attributes["key"].Value; oResList.valueName = xElem.Attributes["valueName"].Value; if (xElem["value"].FirstChild.Attributes.Count > 0) { oResList.value = xElem["value"].FirstChild.Attributes["value"].Value; } else { oResList.value = xElem["value"].FirstChild.InnerText; } } oElem.enabledValueList.Add(oResList); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } oRes.elements.Add(oElem); } if (xPol["disabledList"] != null) { EnableListElement oElem = new EnableListElement(); oElem.ValueType = valueType.Enum; oElem.disabledValueList = new List <enabledList>(); foreach (XmlNode xElem in xPol["disabledList"].SelectNodes("pd:item", ns)) { try { enabledList oResList = new enabledList(); if (xElem["value"].FirstChild.Name == "decimal") { oResList.type = valueType.Decimal; oResList.key = xElem.Attributes["key"].Value; oResList.valueName = xElem.Attributes["valueName"].Value; oResList.value = xElem["value"].FirstChild.Attributes["value"].Value; } if (xElem["value"].FirstChild.Name == "string") { oResList.type = valueType.Text; oResList.key = xElem.Attributes["key"].Value; oResList.valueName = xElem.Attributes["valueName"].Value; if (xElem["value"].FirstChild.Attributes.Count > 0) { oResList.value = xElem["value"].FirstChild.Attributes["value"].Value; } else { oResList.value = xElem["value"].FirstChild.InnerText; } } oElem.disabledValueList.Add(oResList); } catch (Exception ex) { Debug.WriteLine(ex.Message); } } oRes.elements.Add(oElem); } policies.Add(oRes); } } }
// Activates a new bonus display and deactivates the previous one private void ChangePolicyBonusDisplay(int playerNum, int oldPolicy, policy newPolicy) { transform.GetChild(playerNum).GetChild(Mathf.Abs((int)oldPolicy - 4)).GetChild(0).gameObject.SetActive(false); transform.GetChild(playerNum).GetChild(Mathf.Abs((int)newPolicy - 4)).GetChild(0).gameObject.SetActive(true); }
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 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 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 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 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 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); }
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 setPermissionsOnFolders(string userSearchPath, contentManagerService1 cmService, string sPath) { searchPathMultipleObject spMulti = new searchPathMultipleObject(); spMulti.Value = sPath; folder pFolder = (folder)cmService.query(spMulti, new propEnum[]{propEnum.searchPath,propEnum.policies},new sort[]{},new queryOptions())[0]; bool found = false; permission newPermission = new permission(); newPermission.name ="execute"; newPermission.access = accessEnum.deny; for (int i = 0; i < pFolder.policies.value.Length && !found; i ++) { policy policy = pFolder.policies.value[i]; //If the security object already exists, update its permissions if(policy.securityObject.searchPath.value.Equals(userSearchPath)) { found = true; permission[] newPerms = new permission[policy.permissions.Length + 1]; for(int j = 0; j < policy.permissions.Length; j ++) { newPerms[j] = policy.permissions[j]; } newPerms[newPerms.Length - 1] = newPermission; policy.permissions = newPerms; } } //If the security object does not exist, create a new one if(!found) { baseClass entry = null; spMulti.Value = userSearchPath; entry = cmService.query(spMulti, new propEnum[]{},new sort[]{},new queryOptions())[0]; policy newPolicy = new policy(); newPolicy.securityObject = entry; permission[] permissions = new permission[1]; permissions[0] = newPermission; newPolicy.permissions = permissions; policyArrayProp existingPols = pFolder.policies ; policy[] newPols = new policy[existingPols.value.Length + 1]; for(int j = 0; j < existingPols.value.Length; j ++) { newPols[j] = existingPols.value[j]; } newPols[newPols.Length - 1] = newPolicy; existingPols.value = newPols; } cmService.update(new baseClass[]{pFolder},new updateOptions() ); }