private void btnNew_Click(object sender, EventArgs e) { using (var Keygen = new frmRsaGen()) { if (Keygen.ShowDialog() == DialogResult.OK) { var Props = new { Keygen.KeyName, Keygen.KeySize }; foreach (var C in Controls) { ((Control)C).Enabled = false; } pbGenerator.Visible = true; Thread T = new Thread(delegate() { var Key = RSAEncryption.GenerateKey(Props.KeyName, Props.KeySize); Invoke((MethodInvoker) delegate { var Keys = Settings.LoadRSAKeys().ToList(); Keys.Add(Key); foreach (var C in Controls) { ((Control)C).Enabled = true; } pbGenerator.Visible = false; Settings.SaveRSAKeys(Keys, true); InitRSA(); }); }); T.IsBackground = true; T.Start(); } } }
private void btnCreate_Click(object sender, EventArgs e) { using (var F = new frmRsaGen()) { if (F.ShowDialog() == DialogResult.OK) { var Props = new { F.KeyName, F.KeySize }; foreach (var C in Controls) { ((Control)C).Enabled = false; } pbKeygen.Visible = true; Thread T = new Thread(delegate() { var Key = RSAEncryption.GenerateKey(Props.KeyName, Props.KeySize); AllKeys.Add(Key); Invoke((MethodInvoker) delegate { foreach (var C in Controls) { ((Control)C).Enabled = true; } pbKeygen.Visible = false; InitList(Key); }); }); T.IsBackground = true; T.Start(); } } }
private void btnRsaSelect_Click(object sender, EventArgs e) { using (var F = new frmRSASelect(Settings.LoadRSAKeys(), true, RsaKey)) { if (F.ShowDialog() == DialogResult.OK) { cbRSA.Checked = true; RsaKey = F.SelectedKey; if (RsaKey == null) { lblRsaName.Text = "<No key selected>"; cbRSA.Checked = false; } else { lblRsaName.Text = RsaKey.Name; if (!RSAEncryption.HasPrivateKey(RsaKey.Key)) { Program.AlertMsg( "You picked a key that can only encrypt, not decrypt. " + "You will not be able to open the file again once you close it.\r\n" + "You should only do this if you're encrypting the file for someone else."); } } } Settings.SaveRSAKeys(F.AllKeys, true); } }
private void btnBackup_Click(object sender, EventArgs e) { const string ExportAlert = "You're about to export at least one RSA key that has private key information.\r\n" + "Under no circumstances should you share those keys with anybody, regardless of what they tell you.\r\nContinue?"; if (lvRSA.SelectedItems.Count > 0) { var Keys = lvRSA.SelectedItems .OfType <ListViewItem>() .Where(m => m.Tag != null) .Select(m => (RSAKey)m.Tag) .ToArray(); if (Keys.Length == 0) { Program.AlertMsg("You can't export administratively added keys"); return; } if (!Keys.Any(m => RSAEncryption.HasPrivateKey(m.Key)) || Program.AlertMsg(ExportAlert, true) == DialogResult.Yes) { if (lvRSA.SelectedItems.Count == 1) { SFD.FileName = Tools.SanitizeName(Keys[0].Name + ".rsa"); if (SFD.ShowDialog() == DialogResult.OK) { try { System.IO.File.WriteAllText(SFD.FileName, Keys[0].ToXML()); } catch (Exception ex) { Program.ErrorMsg("Unable to back up your key. Error:\r\n" + ex.Message); } } } else { if (FBD.ShowDialog() == DialogResult.OK) { foreach (var K in Keys) { try { System.IO.File.WriteAllText(Tools.UniqueName(FBD.SelectedPath, Tools.SanitizeName(K.Name + ".rsa")), K.ToXML()); } catch (Exception ex) { Program.ErrorMsg($"Unable to back up your key named {K.Name}. Error:\r\n{ex.Message}"); } } } } } } else { Program.AlertMsg("Please select at least one key"); } }
private void btnExport_Click(object sender, EventArgs e) { const string ExportAlert = "You're about to export only the public RSA key parts.\r\n" + "This key will allow encryption only and is meant for sharing with other people and not creating backups.\r\n" + "Continue?"; if (lvRSA.SelectedItems.Count > 0) { var Keys = lvRSA.SelectedItems .OfType <ListViewItem>() .Where(m => m.Tag != null) .Select(m => RSAEncryption.StripPrivate((RSAKey)m.Tag)) .ToArray(); if (Keys.Length > 0 && Program.AlertMsg(ExportAlert, true) == DialogResult.Yes) { if (lvRSA.SelectedItems.Count == 1) { SFD.FileName = Tools.SanitizeName(Keys[0].Name + ".rsa"); if (SFD.ShowDialog() == DialogResult.OK) { try { System.IO.File.WriteAllText(SFD.FileName, Keys[0].ToXML()); } catch (Exception ex) { Program.ErrorMsg("Unable to export your key. Error:\r\n" + ex.Message); } } } else { if (FBD.ShowDialog() == DialogResult.OK) { foreach (var K in Keys) { try { System.IO.File.WriteAllText(Tools.UniqueName(FBD.SelectedPath, Tools.SanitizeName(K.Name + ".rsa")), K.ToXML()); } catch (Exception ex) { Program.ErrorMsg($"Unable to export your key named {K.Name}. Error:\r\n{ex.Message}"); } } } } } else if (Keys.Length == 0) { Program.AlertMsg("You can't export administratively added keys"); } } else { Program.AlertMsg("Please select at least one key"); } }
/// <summary> /// Decrypts data using the given RSA key /// </summary> /// <param name="Data">Data to decrypt</param> /// <param name="Params">RSA key</param> /// <returns>Decrypted data</returns> private static byte[] DecryptWithRSAKey(AesCryptoData Data, RSAParameters Params) { if (RSAEncryption.HasPrivateKey(Params)) { return(RSAEncryption.Decrypt(Params, Data.Data)); } throw new CryptographicException("The supplied RSA key lacks the private key parts"); }
/// <summary> /// Checks if the instance has a valid key /// </summary> /// <returns>true, if key is valid</returns> public bool IsValid() { //We currently don't allow keys that only have the private key parts set. //This means a key must either have the public part only, or both parts. //"x || (x && y)" can be simplified as just "x" due to the 4 possibilities collapsing: //true || (true && false) --> true //true || (true && true) --> true //false || (false && false) --> false //false || (false && true) --> false return(RSAEncryption.HasPublicKey(Key)); }
private void InitRSA() { lvRSA.Items.Clear(); foreach (var Key in Settings.LoadRSAKeys()) { var Item = lvRSA.Items.Add(Key.Name); Item.Tag = Key; Item.SubItems.Add(Key.Size.ToString()); Item.SubItems.Add(RSAEncryption.HasPublicKey(Key.Key) ? "Yes" : "No"); Item.SubItems.Add(RSAEncryption.HasPrivateKey(Key.Key) ? "Yes" : "No"); } }
/// <summary> /// Checks if two given instances are identical /// </summary> /// <param name="obj">object to compare to</param> /// <returns>true, if identical</returns> public override bool Equals(object obj) { if (obj == null) { return(false); } if (obj.GetType() == typeof(RSAKey)) { var o = (RSAKey)obj; return(o == this || (Name == o.Name && RSAEncryption.Compare(Key, o.Key))); } return(base.Equals(obj)); }
/// <summary> /// Encrypts data using the given RSA public key /// </summary> /// <param name="Data">Data to encrypt</param> /// <param name="Password">Key to encrypt the data with</param> /// <returns>Encrypted data</returns> private static AesCryptoData EncryptWithRSAKey(byte[] Data, RSAParameters Params) { if (RSAEncryption.HasPublicKey(Params)) { return(new AesCryptoData() { IV = null, Salt = null, Data = RSAEncryption.Encrypt(Params, Data) }); } throw new CryptographicException("The supplied RSA key lacks the public key parts"); }
private void btnImport_Click(object sender, EventArgs e) { if (OFD.ShowDialog() == DialogResult.OK) { var Keys = Settings.LoadRSAKeys(); var AdminKeys = AppSettings.GetAdministrativeKeys(); var NewKeys = new List <RSAKey>(); foreach (var Name in OFD.FileNames) { try { var Key = Tools.FromXML <RSAKey>(System.IO.File.ReadAllText(Name)); if (!Key.IsValid()) { throw new Exception("The loaded RSA key is not valid"); } //Check if the key exists as-is if (!Keys.Concat(AdminKeys).Any(m => m.Equals(Key))) { //Check if the key has a private key if (RSAEncryption.HasPrivateKey(Key.Key)) { //Check if any existing keys have the same public key for (var i = 0; i < Keys.Length; i++) { //Replace existing key with imported key if the imported key has a private key if (Keys[i].IsSamePublicKey(Key)) { Keys[i] = Key; } } } else { //Key does not exists and has no private key. Just add it. NewKeys.Add(Key); } } } catch (Exception ex) { Program.ErrorMsg("Unable to import your key. Error:\r\n" + ex.Message); } } Settings.SaveRSAKeys(Keys.Concat(NewKeys), true); //Render new RSA key list InitRSA(); } }
private void InitRSA() { lvRSA.Items.Clear(); foreach (var Key in Settings.LoadRSAKeys()) { var Item = lvRSA.Items.Add(Key.Name); Item.Tag = Key; Item.SubItems.Add(Key.Size.ToString()); Item.SubItems.Add(RSAEncryption.HasPublicKey(Key.Key) ? "Yes" : "No"); Item.SubItems.Add(RSAEncryption.HasPrivateKey(Key.Key) ? "Yes" : "No"); } foreach (var Key in AppSettings.GetAdministrativeKeys()) { var Item = lvRSA.Items.Add(Key.Name); Item.Tag = null; Item.BackColor = System.Drawing.Color.FromArgb(0xFF, 0xAA, 0xAA); Item.SubItems.Add(Key.Size.ToString()); Item.SubItems.Add(RSAEncryption.HasPublicKey(Key.Key) ? "Yes" : "No"); Item.SubItems.Add(RSAEncryption.HasPrivateKey(Key.Key) ? "Yes" : "No"); } }
private void OpenText() { byte[] Data = null; EncryptedData TempFile = null; if (!HasChange || SaveText(false, HasChange)) { if (dlgOpen.ShowDialog() == DialogResult.OK) { try { TempFile = Tools.FromXML <EncryptedData>(File.ReadAllText(dlgOpen.FileName)); try { Data = Encryption.Decrypt(TempFile); Debug.WriteLine("Decrypted using parameterless provider"); } catch { Debug.WriteLine("Parameterless provider could not decrypt the file"); if (TempFile.HasProvider(CryptoMode.RSA)) { //Try all RSA keys until one succeeds foreach (var K in Settings.LoadRSAKeys().Where(m => RSAEncryption.HasPrivateKey(m.Key))) { FileParams[CryptoMode.RSA] = K.Key; try { Data = Encryption.Decrypt(TempFile, FileParams); Debug.WriteLine($"Decrypted using RSA provider and key: {K.Name}"); break; } catch { Debug.WriteLine($"Key failed: {K.Name}"); //Try next key } } if (Data == null) { Debug.WriteLine($"No RSA key could decrypt the content"); FileParams.Remove(CryptoMode.RSA); } } if (Data == null) { if (TempFile.HasProvider(CryptoMode.Keyfile) || TempFile.HasProvider(CryptoMode.Password)) { using (var pwd = new frmCryptoInput(TempFile.AllModes, null)) { if (pwd.ShowDialog() == DialogResult.OK) { if (pwd.ValidInput) { if (!string.IsNullOrEmpty(pwd.Password)) { FileParams[CryptoMode.Password] = pwd.Password; } if (!string.IsNullOrEmpty(pwd.Keyfile)) { if (File.Exists(pwd.Keyfile)) { FileParams[CryptoMode.Password] = pwd.Keyfile; } else { Program.ErrorMsg("Invalid key file selected"); } } if (FileParams.Count > 0) { try { Data = Encryption.Decrypt(TempFile, FileParams); } catch (Exception ex) { Program.ErrorMsg($"Unable to decrypt the file using the supplied data. Invalid key file or password?\r\n{ex.Message}"); } } } else { Program.ErrorMsg("You need to provide at least one of the offered options to decrypt the file."); } } } } else if (TempFile.HasProvider(CryptoMode.RSA)) { Program.AlertMsg( "The file is encrypted using RSA but none of your keys can decrypt it.\r\n" + "Please add the matching RSA private key to the key store using the \"Tools >> Options\" Menu"); } else { Program.ErrorMsg("Failed to decrypt the data."); } } } } catch { Program.ErrorMsg("Unable to open the specified file. It's not a valid encrypted text document"); } } } //Open the selected file, provided it could be decrypted if (Data != null) { FileName = dlgOpen.FileName; CurrentFile = TempFile; BaseContent = tbEditor.Text = Encoding.UTF8.GetString(Data); UpdateStatus(); } }