using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Security.Cryptography; namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnPublic_key_Click(object sender, EventArgs e) { var cryptoServiceProvider = new RSACryptoServiceProvider(2048); //2048 - Długość klucza var publicKey = cryptoServiceProvider.ExportParameters(false); //Generowanie klucza publiczny string publicKeyString = GetKeyString(publicKey); lblPublic_Key.Text = publicKeyString; } private void btnPrivate_key_Click(object sender, EventArgs e) { var cryptoServiceProvider = new RSACryptoServiceProvider(2048); //2048 - Długość klucza var privateKey = cryptoServiceProvider.ExportParameters(true); //Generowanie klucza prywatnego string privateKeyString = GetKeyString(privateKey); lblPrivate_Key.Text = privateKeyString; } public static string GetKeyString(RSAParameters publicKey) { var stringWriter = new System.IO.StringWriter(); var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters)); xmlSerializer.Serialize(stringWriter, publicKey); return stringWriter.ToString(); } private void btnEncryptiontext_Click(object sender, EventArgs e) { string tekst = textBox_text.Text; string encryptedText = Encrypt(tekst, publicKeyString); //Szyfrowanie za pomocą klucza publicznego lbl_Encryptiontxt.Text = encryptedText; } public static string Encrypt(string tekst, string publicKeyString) { var bytesToEncrypt = Encoding.UTF8.GetBytes(tekst); using (var rsa = new RSACryptoServiceProvider(2048)) { try { rsa.FromXmlString(publicKeyString.ToString()); var encryptedData = rsa.Encrypt(bytesToEncrypt, true); var base64Encrypted = Convert.ToBase64String(encryptedData); return base64Encrypted; } finally { rsa.PersistKeyInCsp = false; } } } } }