Created
March 28, 2024 05:05
-
-
Save normanlmfung/f431c1bfe3c3c04cb6c579fe4701b534 to your computer and use it in GitHub Desktop.
csharp_rsa_encrypt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Security.Cryptography; | |
using System.Text; | |
public class AsymmetricEncryptionExample | |
{ | |
public static void Main(string[] args) | |
{ | |
try | |
{ | |
// Generate RSA key pair (public and private keys) | |
using (var rsa = new RSACryptoServiceProvider()) | |
{ | |
// Get the public and private key | |
var publicKey = rsa.ToXmlString(false); | |
var privateKey = rsa.ToXmlString(true); | |
// Display the keys | |
Console.WriteLine("Public Key:"); | |
Console.WriteLine(publicKey); | |
Console.WriteLine(); | |
Console.WriteLine("Private Key:"); | |
Console.WriteLine(privateKey); | |
Console.WriteLine(); | |
// Example text to be encrypted | |
string originalText = "Hello, world!"; | |
// Convert the text to bytes | |
byte[] byteText = Encoding.UTF8.GetBytes(originalText); | |
// Encrypt the text using the public key | |
byte[] encryptedBytes; | |
using (var rsaEncryptor = new RSACryptoServiceProvider()) | |
{ | |
rsaEncryptor.FromXmlString(publicKey); | |
encryptedBytes = rsaEncryptor.Encrypt(byteText, false); | |
} | |
// Convert encrypted bytes to base64 for easy display | |
string encryptedText = Convert.ToBase64String(encryptedBytes); | |
Console.WriteLine("Encrypted Text:"); | |
Console.WriteLine(encryptedText); | |
Console.WriteLine(); | |
// Decrypt the text using the private key | |
byte[] decryptedBytes; | |
using (var rsaDecryptor = new RSACryptoServiceProvider()) | |
{ | |
rsaDecryptor.FromXmlString(privateKey); | |
decryptedBytes = rsaDecryptor.Decrypt(encryptedBytes, false); | |
} | |
// Convert decrypted bytes back to text | |
string decryptedText = Encoding.UTF8.GetString(decryptedBytes); | |
Console.WriteLine("Decrypted Text:"); | |
Console.WriteLine(decryptedText); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("An error occurred: " + ex.Message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment