internal class Program
{
static void Main(string[] args)
{
IRSAEncryption rsa = new RSAEncryption();
// Use only one time for generating keys
//rsa.GenerateKeys("mx.pub","px.pem");
var text = "Fıstıkçı Şahap 2";
var encryptedText = rsa.Encrypt(text, "mx.pub");
Console.WriteLine($"Encrpyted: {encryptedText}");
//var decryptedText = rsa.Decrypt(encryptedText, "mx.pem");
//Console.WriteLine($"Decrypted: {decryptedText}");
}
}
public interface IRSAEncryption
{
public void GenerateKeys(string pathPublicKey, string pathPrivateKey);
public string Encrypt(string plainText, string pathPublicKey);
public string Decrypt(string encrpyedText, string pathPrivateKey);
}
public class RSAEncryption : IRSAEncryption
{
private string ByteArrayToString(byte[] bytes)
{
var sb = new StringBuilder(bytes.Length * 2);
foreach (var b in bytes)
{
sb.AppendFormat("{0:x2}", b);
}
return sb.ToString();
}
public static byte[] StringToByteArray(String hex)
{
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
private RSAParameters ImportKey(string path)
{
var serializer = new XmlSerializer(typeof(RSAParameters));
using (var fs = new FileStream(path, FileMode.Open))
{
return (RSAParameters)serializer.Deserialize(fs);
}
}
private void ExportKey(RSAParameters parameters, string path)
{
var serializer = new XmlSerializer(typeof(RSAParameters));
using (var fs = new FileStream(path, FileMode.CreateNew))
using (var sw = new StreamWriter(fs, Encoding.UTF8))
{
serializer.Serialize(sw, parameters);
}
}
public string Decrypt(string encrpyedText, string pathPrivateKey)
{
using (var rsa = new RSACryptoServiceProvider())
{
var pubKey = ImportKey(pathPrivateKey);
rsa.ImportParameters(pubKey);
var data = StringToByteArray(encrpyedText);
var cypher = rsa.Decrypt(data, false);
return Encoding.UTF8.GetString(cypher);
}
}
public string Encrypt(string plainText, string pathPublicKey)
{
using (var rsa = new RSACryptoServiceProvider())
{
var pubKey = ImportKey(pathPublicKey);
rsa.ImportParameters(pubKey);
var data = Encoding.UTF8.GetBytes(plainText);
var cypher = rsa.Encrypt(data, false);
return ByteArrayToString(cypher);
}
}
public void GenerateKeys(string pathPublicKey, string pathPrivateKey)
{
using (var rsa = new RSACryptoServiceProvider(2048))
{
var pem = rsa.ExportParameters(true);
var pub = rsa.ExportParameters(false);
ExportKey(pem, "mx.pem");
ExportKey(pub, "mx.pub");
}
}
}