Last active
June 18, 2020 10:43
-
-
Save Maheshdeshmane/de4ed2b8dd15755c0b929ab3674d2c46 to your computer and use it in GitHub Desktop.
Program problem statement https://corevoila.in/computer-science/cryptography/asymmetric-cryptography-public-key-cryptography-part-i/
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; | |
namespace AsymmetricCryptography | |
{ | |
public class AsymmetricRsa | |
{ | |
static void Main() | |
{ | |
var rsaCryptoService = new RSACryptoServiceProvider(); | |
var publicKey = rsaCryptoService.ToXmlString(false); // false to get the public key | |
var privateKey = rsaCryptoService.ToXmlString(true); // true to get the private key | |
Console.WriteLine("Enter message to encrypt"); | |
var message = Console.ReadLine(); | |
var encryptedMessage = EncryptMessage(publicKey, message, rsaCryptoService); | |
Console.WriteLine(new UnicodeEncoding().GetString(encryptedMessage)); | |
var decryptData = DecryptData(privateKey,encryptedMessage); | |
Console.WriteLine(new UnicodeEncoding().GetString(decryptData)); | |
Console.ReadLine(); | |
} | |
static byte[] EncryptMessage(string publicKey, string message, RSACryptoServiceProvider rsaCryptoService) | |
{ | |
var dataToEncrypt = new UnicodeEncoding().GetBytes(message); | |
rsaCryptoService.FromXmlString(publicKey);//We can even create new instance for RSACryptoServiceProvider | |
return rsaCryptoService.Encrypt(dataToEncrypt, false); | |
} | |
static byte[] DecryptData(string privateKey, byte[] dataToDecrypt) | |
{ | |
var rsaCryptoService = new RSACryptoServiceProvider(); //a new instance for receiver; | |
rsaCryptoService.FromXmlString(privateKey); | |
return rsaCryptoService.Decrypt(dataToDecrypt, false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment