private void openPrivateKeyToolStripMenuItem_Click(object sender, EventArgs e) { if (privateKey != null) { privateKey.Dispose(); privateKey = null; } openFileDialog1.Title = "Open Private Key"; if (openFileDialog1.ShowDialog() == DialogResult.OK) { try { string privateKeyFile; using (var streamReader = new StreamReader(openFileDialog1.FileName, Encoding.UTF8)) { privateKeyFile = streamReader.ReadToEnd(); } privateKey = RSAKeys.ImportPrivateKey(privateKeyFile); } catch (Exception ex) { privateKey = null; resetOpenFileDialog(); MessageBox.Show("Error while importing Private Key" + Environment.NewLine + ex.Message); return; } label6.Text = openFileDialog1.FileName; } resetOpenFileDialog(); toggleControls(); }
public static void SaveKeys(string keyFileName) { using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048)) { try { // Can be verified via: // openssl rsa -in private.key -pubout > public2.pem using (StreamWriter writer = File.CreateText(keyFileName + "_public.pem")) { writer.Write(RSAKeys.ExportPublicKey(rsa)); } using (StreamWriter writer = File.CreateText(keyFileName + "_private.key")) { writer.Write(RSAKeys.ExportPrivateKey(rsa)); } } catch (Exception e) { MessageBox.Show("Error while writing keys to files." + Environment.NewLine + e.Message); } finally { rsa.PersistKeyInCsp = false; } } }