using System; using System.Security.Cryptography; using System.Text; public class RSATest { public static void Main() { string plainText = "This is a message to be encrypted."; byte[] data = Encoding.UTF8.GetBytes(plainText); // Generate public and private key pair using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { string publicKeyXml = rsa.ToXmlString(false); // Export only the public key Console.WriteLine("Public key: " + publicKeyXml); // Encrypt the data using the public key rsa.FromXmlString(publicKeyXml); byte[] encryptedData = rsa.Encrypt(data, false); Console.WriteLine("Encrypted data: " + Convert.ToBase64String(encryptedData)); } } }
using System; using System.Security.Cryptography; using System.Text; public class RSATest { public static void Main() { string encryptedData = "some encrypted data"; // Received encrypted data byte[] data = Convert.FromBase64String(encryptedData); // Load private key from XML string using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) { string privateKeyXml = "This example loads a private key from an XML string, which could be obtained from a key file or a database. It then uses the private key to decrypt some received encrypted data, and displays the decrypted plain text. Both examples use the RSACryptoServiceProvider class, which is part of the System.Security.Cryptography package in .NET."; // Private key XML string rsa.FromXmlString(privateKeyXml); // Decrypt the data using the private key byte[] decryptedData = rsa.Decrypt(data, false); string plainText = Encoding.UTF8.GetString(decryptedData); Console.WriteLine("Decrypted data: " + plainText); } } } ...