コード例 #1
0
ファイル: App.xaml.cs プロジェクト: luchees/clienteafirmaEN
        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);
        }
コード例 #2
0
        /// <summary>
        /// Método que importa un almacén a la aplicación. Solicita la clave del almacén y verifica que es un almacén,
        /// en cuyo caso, almacenará dicho almacén en la carpeta de la aplicación para poder ser utilizado más tarde.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Button_Import_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder contents = new StringBuilder();

            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".pfx");
            openPicker.FileTypeFilter.Add(".p12");
            StorageFile selectedFile2 = await openPicker.PickSingleFileAsync();

            if (selectedFile2 != null)
            {
                CredentialPanel cp = new CredentialPanel();
                cp.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                CustomDialog customDialog = new CustomDialog(cp, labels.GetString("Etiqueta_peticion_pass"));
                customDialog.Commands.Add(new UICommand(labels.GetString("Boton_aceptar")));
                customDialog.Commands.Add(new UICommand(labels.GetString("Boton_cancelar")));
                customDialog.DefaultCommandIndex = 0;
                customDialog.CancelCommandIndex  = 1;
                IUICommand com = await customDialog.ShowAsync();

                if (com.Label.Equals(labels.GetString("Boton_aceptar")))
                {
                    if (cp.getPassword() != null)
                    {
                        using (StreamReader reader = new StreamReader(await selectedFile2.OpenStreamForReadAsync()))
                        {
                            char[] password = cp.getPassword().ToCharArray();
                            try
                            {
                                store = new Pkcs12Store(reader.BaseStream, password);
                                if (store != null)
                                {
                                    await selectedFile2.CopyAsync(localFolder, selectedFile2.Name, NameCollisionOption.ReplaceExisting);

                                    AfirmaMetroUtils.showMessage(labels.GetString("Info_almacen_importado") + selectedFile2.Name + "\"", "Importación de almacén correcta");
                                    // Recargamos los almacenes
                                    loadStorage();
                                }
                            }
                            catch
                            {
                                AfirmaMetroUtils.showMessage(labels.GetString("Error_carga_almacen"), "TITULO");
                            }
                        }
                    }
                }
            }
        }
コード例 #3
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();
        }
コード例 #4
0
        /// <summary>
        /// Método que carga un almacén. Solicita la contraseña del almacén seleccionado y carga los alias de dicho
        /// alamacén en la lista de alias si la contraseña proporcionada fuera correcta.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ComboBox_Stores_Selection_Changed(object sender, SelectionChangedEventArgs e)
        {
            if (pfxList.SelectedItem != null)
            {
                // Si no se ha seleccionado el elemento "dummy"...
                if (!pfxList.SelectedItem.Equals(labels.GetString("Etiqueta_seleccion_almacen")))
                {
                    IReadOnlyList <StorageFile> files = await ApplicationData.Current.LocalFolder.GetFilesAsync();

                    StorageFile fileSelected = null;
                    foreach (StorageFile file in files)
                    {
                        if (file.Name.Equals((String)pfxList.SelectedItem))
                        {
                            fileSelected = file;
                            break;
                        }
                    }
                    if (fileSelected != null)
                    {
                        using (StreamReader reader = new StreamReader(await fileSelected.OpenStreamForReadAsync()))
                        {
                            // Pedimos el PIN del almacén al usuario
                            CredentialPanel2 cp2 = new CredentialPanel2(pfxList.SelectedItem.ToString());
                            cp2.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                            CustomDialog customDialog = new CustomDialog(cp2, labels.GetString("Etiqueta_peticion_pass"));
                            customDialog.Commands.Add(new UICommand(labels.GetString("Boton_aceptar")));
                            customDialog.Commands.Add(new UICommand(labels.GetString("Boton_cancelar")));
                            customDialog.DefaultCommandIndex = 0;
                            customDialog.CancelCommandIndex  = 1;
                            IUICommand com = await customDialog.ShowAsync();

                            // El usuario ha cancelado, si solo no estaba el elemento "dummy"
                            // hay que añadirlo en la posición cero y seleccionarlo, para permitirle reintentar
                            if (com.Label.Equals(labels.GetString("Boton_cancelar")))
                            {
                                if (!pfxList.Items.Contains(labels.GetString("Etiqueta_seleccion_almacen")))
                                {
                                    pfxList.Items.Insert(0, labels.GetString("Etiqueta_seleccion_almacen"));
                                }
                                pfxList.SelectedIndex = 0;
                            }
                            // El usuario ha aceptado en el diálogo de PIN
                            if (com.Label.Equals(labels.GetString("Boton_aceptar")))
                            {
                                aliasList.Items.Clear();
                                try
                                {
                                    store = new Pkcs12Store(reader.BaseStream, cp2.getPassword().ToCharArray());
                                    foreach (string n in store.Aliases)
                                    {
                                        if (store.IsKeyEntry(n))
                                        {
                                            AsymmetricKeyEntry key = store.GetKey(n);

                                            if (key.Key.IsPrivate)
                                            {
                                                aliasList.Items.Clear();
                                                aliasList.IsEnabled = true;
                                                RsaPrivateCrtKeyParameters parameters = key.Key as RsaPrivateCrtKeyParameters;
                                                rsaKeyParameter = (RsaKeyParameters)key.Key;
                                                foreach (object s in store.Aliases)
                                                {
                                                    aliasList.Items.Add((string)s);
                                                }
                                            }
                                        }
                                    }
                                }
                                catch
                                {
                                    AfirmaMetroUtils.showMessage(labels.GetString("Error_carga_almacen"), "Error en el almacén de claves" + " (" + pfxList.SelectedItem + ")");
                                    // Para permitirle reintentar insertamos el elemento "dummy" como primer elemento
                                    // y lo seleccionamos
                                    if (!pfxList.Items.Contains(labels.GetString("Etiqueta_seleccion_almacen")))
                                    {
                                        pfxList.Items.Insert(0, labels.GetString("Etiqueta_seleccion_almacen"));
                                    }
                                    pfxList.SelectedIndex = 0;
                                    return;
                                }

                                // Se ha seleccionado correctamente un almacén, eliminamos el componente "dummy"
                                if (pfxList.Items.Contains(labels.GetString("Etiqueta_seleccion_almacen")))
                                {
                                    pfxList.Items.Remove(labels.GetString("Etiqueta_seleccion_almacen"));
                                }

                                aliasList.SelectedIndex = 0;
                            }
                        }
                    }
                }
                else
                {
                    disableComboAlias();
                }
            }
        }
コード例 #5
0
ファイル: App.xaml.cs プロジェクト: luchees/clienteafirmaEN
        /// <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;
                }
            }
        }
コード例 #6
0
        private async void Button_Import_Click(object sender, RoutedEventArgs e)
        {
            StringBuilder  contents      = new StringBuilder();
            StorageFile    selectedFile2 = null;
            FileOpenPicker openPicker    = new FileOpenPicker();

            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            openPicker.FileTypeFilter.Add(".pfx");
            openPicker.FileTypeFilter.Add(".p12");

            if (ApplicationView.Value == ApplicationViewState.Snapped)
            {
                if (ApplicationView.TryUnsnap())
                {
                    selectedFile2 = await openPicker.PickSingleFileAsync();
                }
            }
            else
            {
                selectedFile2 = await openPicker.PickSingleFileAsync();
            }

            if (selectedFile2 != null)
            {
                CredentialPanel cp           = new CredentialPanel();
                bool            foco         = cp.Focus(Windows.UI.Xaml.FocusState.Programmatic);
                CustomDialog    customDialog = new CustomDialog(cp, labels.GetString("Etiqueta_peticion_pass"));
                customDialog.Commands.Add(new UICommand(labels.GetString("Boton_aceptar")));
                customDialog.Commands.Add(new UICommand(labels.GetString("Boton_cancelar")));
                customDialog.DefaultCommandIndex = 0;
                customDialog.CancelCommandIndex  = 1;
                IUICommand com = await customDialog.ShowAsync();

                if (com.Label.Equals(labels.GetString("Boton_aceptar")))
                {
                    if (cp.getPassword() != null)
                    {
                        using (StreamReader reader = new StreamReader(await selectedFile2.OpenStreamForReadAsync()))
                        {
                            char[] password = cp.getPassword().ToCharArray();
                            try
                            {
                                store = new Pkcs12Store(reader.BaseStream, password);
                                if (store != null)
                                {
                                    await selectedFile2.CopyAsync(localFolder, selectedFile2.Name, NameCollisionOption.ReplaceExisting);

                                    storeData = new StoreData();
                                    storeData.LoadData();
                                    _source = storeData.GetGroupsByCategory();
                                    ItemGridView2.ItemsSource = storeData.Collection;
                                    EvaluateDeleteButton(storeData);
                                    // Le quitamos la extensión al nombre del almacén por coherencia con el borrado, que al pillarlo de la lista no tiene extensión.
                                    AfirmaMetroUtils.showMessage(labels.GetString("Info_almacen_importado") + selectedFile2.Name.Replace(selectedFile2.FileType, "") + "\".", "Importación de almacén correcta");

                                    // Lanzamos:
                                    var options = new Windows.System.LauncherOptions();
                                    options.DisplayApplicationPicker = true;
                                    var file2 = await localFolder.GetFileAsync(selectedFile2.Name);

                                    bool success = await Windows.System.Launcher.LaunchFileAsync(file2, options);
                                }
                            }
                            catch
                            {
                                AfirmaMetroUtils.showMessage(labels.GetString("Error_carga_almacen"), "Error en la importación de almacén");
                            }
                        }
                    }
                }
            }
        }