Exemple #1
0
        public static void SaveKey(RsaKeyPair Key)
        {
            string json = Key.ToJson();

            byte[] bytes = Crypto.RsaEncrypt(masterKey.PublicCsp, System.Text.Encoding.UTF8.GetBytes(json));

            string filename = $"{path}\\{Key.Hash.Replace("+", "").Replace("=", "").Replace("/", "").Substring(0, 16)}.key";

            if (System.IO.File.Exists(filename))
            {
                System.IO.File.Delete(filename);
            }
            System.IO.File.WriteAllBytes(filename, bytes);
        }
        private void exportButton_Click(object sender, RoutedEventArgs e)
        {
            RsaKeyPair key = ((Button)e.OriginalSource).DataContext as RsaKeyPair;

            Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
            dlg.FileName         = MakeValidFileName((string.IsNullOrWhiteSpace(key.Note) ? "" : key.Note + ".") + (key.PublicOnly ? "Public." : "") + key.Hash.Substring(0, 16));//key.Hash.Substring(0,16);
            dlg.Filter           = "JSON (.json)|*.json|plain text (*.txt)|*.txt|All files (*.*)|*.*";
            dlg.FilterIndex      = 1;
            dlg.RestoreDirectory = true;
            dlg.Title            = "Export Key";

            if (dlg.ShowDialog() == true)
            {
                try
                {
                    if (System.IO.File.Exists(dlg.FileName))
                    {
                        System.IO.File.Delete(dlg.FileName);
                    }

                    if (dlg.FileName.EndsWith(".JSON", StringComparison.InvariantCultureIgnoreCase))
                    {
                        System.IO.File.WriteAllText(dlg.FileName, key.ToJson());
                    }
                    else
                    {
                        string text = key.PublicKey;
                        if (!key.PublicOnly)
                        {
                            text += "\n" + key.PrivateKey;
                        }
                        text += "\n";
                        System.IO.File.WriteAllText(dlg.FileName, text);
                    }

                    MessageBox.Show("File saved", "Success", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"Encountered an error while trying to write to\n{dlg.FileName}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }