Esempio n. 1
0
        private async Task <bool> sendError(Dictionary <string, string> parameters, string idUser, string error)
        {
            bool resultado = false;

            try
            {
                //cargamos el servlet de storage para almacenar la operacion de cancelacion
                string rsServlet       = null;
                bool   rsServletLoaded = parameters.TryGetValue(ConstantsAfirmaMetro.SERVLET_STORAGE, out rsServlet);
                if (!rsServletLoaded)
                {
                    AfirmaMetroUtils.showMessageAndClose(labels.GetString("Iniciar_aplicacion_adecuado"), "TITULO");
                }

                // Asegurarse de que la ventana actual está activa.
                string result = await AfirmaMetroUtils.SendErrorServlet(rsServlet, idUser, error);

                //Se trata la respuesta del servidor.
                if (result.Equals("OK"))
                {
                    AfirmaMetroUtils.showMessageAndClose(labels.GetString("Error_cancelled_opperation"), "TITULO");
                    resultado = true;
                }
                else
                {
                    AfirmaMetroUtils.showMessageAndClose(labels.GetString("Error_communicating_with_web") + ".\n" + labels.GetString("Info_regreso_navegador"), "TITULO");
                }
            }
            catch (WebException)
            {
                AfirmaMetroUtils.showMessageAndClose(labels.GetString("Error_communicating_with_web") + ".\n" + labels.GetString("Info_regreso_navegador"), "TITULO");
            }
            return(resultado);
        }
Esempio n. 2
0
        /// <summary>
        /// Método que se ejecuta cuando se pulsa el botón de firma. Genera la propia firma
        /// y la manda al servidor.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Sign_Click(object sender, RoutedEventArgs e)
        {
            DisableComponents();
            if (!aliasList.SelectedItem.Equals(labels.GetString("Etiqueta_seleccion_alias")))
            {
                //Obtenemos la firma de los datos.
                byte[] firma   = null;
                bool   isError = false;
                try
                {
                    firma = CriptoManager.getCades(
                        signParameters.GetData(),
                        this.rsaKeyParameter,
                        store.GetCertificate((string)aliasList.SelectedItem).Certificate.GetEncoded(),
                        signParameters.GetSignatureAlgorithm(),
                        signParameters.GetSignatureFormat()
                        );
                }
                catch
                {
                    // Se produce un error en la operación de firma.
                    isError = true;
                }
                // Se informa sobre el error de la firma.
                if (isError)
                {
                    try
                    {
                        await AfirmaMetroUtils.SendErrorServlet(
                            signParameters.GetStorageServletUrl().ToString(),
                            signParameters.GetContentId(),
                            ConstantsAfirmaMetro.ERROR_SIGNING + ConstantsAfirmaMetro.ERROR_SEPARATOR + ConstantsAfirmaMetro.DESC_ERROR_SIGNING
                            );
                    }
                    finally
                    {
                        AfirmaMetroUtils.showMessageAndClose(labels.GetString("Info_operacion_finalizada"), "Error en la firma electrónica");
                    }
                }

                // Se cifran los datos
                bool isErrorCiphering = false;
                int  firmaSize        = firma.Length;
                try
                {
                    firma = CriptoManager.getDES(firma, signParameters.GetCipherKey());
                }
                catch
                {
                    isErrorCiphering = true;
                }
                if (isErrorCiphering)
                {
                    try
                    {
                        await AfirmaMetroUtils.SendErrorServlet(
                            signParameters.GetStorageServletUrl().ToString(),
                            signParameters.GetContentId(),
                            ConstantsAfirmaMetro.ERROR_INVALID_CIPHER_KEY + ConstantsAfirmaMetro.ERROR_SEPARATOR + ConstantsAfirmaMetro.DESC_ERROR_INVALID_CIPHER_KEY
                            );
                    }
                    finally
                    {
                        AfirmaMetroUtils.showMessageAndClose(labels.GetString("Info_operacion_finalizada"), "Operación finalizada correctamente (1)");
                    }
                }

                //Se envian los datos al servidor y se espera su respuesta.
                try
                {
                    int    padding  = (8 - firmaSize);
                    string response = AsyncHelpers.RunSync <string>(() => AfirmaMetroUtils.SendDataServlet(
                                                                        signParameters.GetStorageServletUrl().ToString(),
                                                                        signParameters.GetContentId(),
                                                                        firma,
                                                                        padding
                                                                        ));
                    //Se trata la respuesta del servidor.
                    if (response.Equals("OK"))
                    {
                        if (signParameters.IsWindowsNewUi())
                        {
                            try
                            {
                                AfirmaMetroUtils.showMessageAndClose("La operación ha finalizado correctamente.\nPara continuar, vuelva al navegador desde el que inició la operación (interfaz 'moderno' de Windows).", "Operación finalizada correctamente");
                            }
                            catch (Exception)
                            {
                                Application.Current.Exit();
                            }
                        }
                        else
                        {
                            AfirmaMetroUtils.showMessageAndClose("La operación ha finalizado correctamente.\nPara continuar, vuelva al navegador desde el que inició la operación (escritorio clásico de Windows).", "Operación finalizada correctamente");
                        }
                    }
                    else
                    {
                        AfirmaMetroUtils.showMessageAndClose(labels.GetString("Error_communicating_with_web") + ".\n" + labels.GetString("Info_regreso_navegador"), "TITULO");
                    }
                }
                catch (WebException)
                {
                    AfirmaMetroUtils.showMessageAndClose(labels.GetString("Error_communicating_with_web") + ".\n" + labels.GetString("Info_regreso_navegador"), "TITULO");
                }
            }
            EnableComponents();
        }
Esempio n. 3
0
        /// <summary>
        /// Este método se invoca cuando se arranca la aplicación por URI. Es decir, cuando se invoca por
        /// url "afirma://parametros".
        /// </summary>
        /// <param name="args">Información detallada acerca de la solicitud y el proceso de inicio.</param>
        protected async override void OnActivated(IActivatedEventArgs args)
        {
            if (args.Kind == ActivationKind.Protocol)
            {
                ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;

                // Preparamos la ventana actual
                Frame mainFrame = new Frame();
                Window.Current.Content = mainFrame;
                // Asegurarse de que la ventana actual está activa.
                Window.Current.Activate();

                // Comprobamos que la entrada es una URI con parámetros
                WwwFormUrlDecoder decoder;
                try
                {
                    String uri = protocolArgs.Uri.AbsoluteUri;
                    decoder = new WwwFormUrlDecoder(uri.Substring(uri.IndexOf("?"), uri.Length - uri.IndexOf("?")));
                }
                catch (Exception)
                {
                    decoder = null;
                }
                if (decoder == null)
                {
                    await new Windows.UI.Popups.MessageDialog(labels.GetString("Error_parametros") + " (ERR:W00)").ShowAsync();
                    Application.Current.Exit();
                }

                // Si el protocolo es de tipo "afirma://sign?"
                if (protocolArgs.Uri.Authority.Equals(ConstantsAfirmaMetro.SIGN_OPERATION))
                {
                    mainFrame.Navigate(typeof(MainPage));

                    // Obtenemos el objeto de parámetros de la URL
                    string errorMessage = "Error indefinido";
                    try
                    {
                        MainPage.signParameters = new SignParameters(protocolArgs.Uri.AbsoluteUri);
                    }
                    catch (UnsupportedSignatureFormat e)
                    {
                        MainPage.signParameters = null;
                        errorMessage            = "El formato de firma no está soportado en este entorno operativo: " + e.GetMessage();
                    }
                    catch (UnsupportedSignatureAlgorithm e)
                    {
                        MainPage.signParameters = null;
                        errorMessage            = "El algoritmo de firma no está soportado en este entorno operativo: " + e.GetMessage();
                    }
                    catch (ParameterException e)
                    {
                        MainPage.signParameters = null;
                        errorMessage            = e.GetMessage();
                    }
                    if (MainPage.signParameters == null)
                    {
                        AfirmaMetroUtils.showMessageAndClose(
                            errorMessage,
                            "Error en la página Web de invocación"
                            );
                        return;
                    }

                    // Comprobamos si hay datos, y si no los hay los leemos desde disco
                    if (MainPage.signParameters.GetData() == null)
                    {
                        mainFrame.Navigate(typeof(FileOpenPicker));
                        string fileOpenErrorMessage = null;
                        try
                        {
                            MainPage.signParameters.SetData(await AfirmaWMetro.Utils.FileManager.GetDataFromDisk("Firmar fichero"));
                        }
                        catch (Exception e)
                        {
                            fileOpenErrorMessage = e.Message;
                        }
                        // Usamos el mensaje de error para determinar si se leyeron los datos
                        if (fileOpenErrorMessage != null)
                        {
                            AfirmaMetroUtils.showMessageAndClose("No se han seleccionado datos a firmar, se cancelará la operación en curso.\n" + fileOpenErrorMessage, "Error en la apertura de datos");
                            return;
                        }
                    }
                } // FIN SIGN

                // EL PROTOCOLO ES DE TIPO "afirma://save?"
                else if (protocolArgs.Uri.Authority.Equals(ConstantsAfirmaMetro.SAVE_OPERATION))
                {
                    SaveParameters saveParameters;
                    try
                    {
                        saveParameters = new SaveParameters(protocolArgs.Uri.AbsoluteUri);
                    }
                    catch (ParameterException e)
                    {
                        // La excepcion contiene el mensaje de error apropiado
                        AfirmaMetroUtils.showMessageAndClose(e.GetMessage(), "Error en la página Web de invocación");
                        return;
                    }

                    // Mostramos el diálogo de guardado de datos
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                    if (saveParameters.getFileDescription() != null && saveParameters.getFileExtension() != null)
                    {
                        savePicker.FileTypeChoices.Add(saveParameters.getFileDescription(), new List <string>()
                        {
                            saveParameters.getFileExtension()
                        });
                    }
                    if (saveParameters.getFileName() != null)
                    {
                        savePicker.SuggestedFileName = saveParameters.getFileName();
                    }

                    var rootFrame = new Frame();
                    rootFrame.Navigate(typeof(FileSavePicker));
                    Window.Current.Content = rootFrame;
                    Window.Current.Activate();

                    StorageFile file = await savePicker.PickSaveFileAsync();

                    if (file != null)
                    {
                        CachedFileManager.DeferUpdates(file);
                        await FileIO.WriteBytesAsync(file, saveParameters.getData());

                        FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);

                        if (status != FileUpdateStatus.Complete)
                        {
                            AfirmaMetroUtils.showMessageAndClose("Ocurrió un error y no se pudo guardar el fichero, pruebe a reintentarlo más tarde o en un directorio diferente.", "Error en el salvado de fichero");
                            return;
                        }
                    }
                    else
                    {
                        AfirmaMetroUtils.showMessageAndClose("Se ha cancelado el guardado de fichero.", "Operación cancelada por el usuario");
                        return;
                    }
                    AfirmaMetroUtils.showMessageAndClose("El fichero se ha guardado correctamente.", "Operación finalizada correctamente");
                    return;
                }
            }
        }