Skip to content

Instantly share code, notes, and snippets.

@Infarh
Created March 11, 2024 21:35
Show Gist options
  • Save Infarh/018e1811bc6d1aa16890abe1f7f87eb5 to your computer and use it in GitHub Desktop.
Save Infarh/018e1811bc6d1aa16890abe1f7f87eb5 to your computer and use it in GitHub Desktop.
RSA encryption
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using RSACryptoServiceProvider rsa = new();
rsa.KeySize = 2048;
var xml_private_str = rsa.ToXmlString(true);
var xml_public_str = rsa.ToXmlString(false);
var rsa_parameters_public = rsa.ExportParameters(false);
var rsa_parameters_private = rsa.ExportParameters(true);
var json_options = new JsonSerializerOptions { IncludeFields = true, WriteIndented = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };
var json_public = JsonSerializer.Serialize(rsa_parameters_public, json_options);
var json_private = JsonSerializer.Serialize(rsa_parameters_private, json_options);
var key_public = rsa_parameters_public.Modulus!;
var key_private = rsa_parameters_private.Modulus!;
var message = "Привет!";
var message_bytes = Encoding.UTF8.GetBytes(message);
var encrypted_bytes = rsa.Encrypt(message_bytes, false);
var encrypted_str = Encoding.UTF8.GetString(encrypted_bytes);
var decrypted_bytes = rsa.Decrypt(encrypted_bytes, false);
var decrypted_str = Encoding.UTF8.GetString(decrypted_bytes);
using RSACryptoServiceProvider rsa2 = new();
rsa2.ImportParameters(rsa_parameters_private);
var decrypted_bytes2 = rsa2.Decrypt(encrypted_bytes, false);
var decrypted_str2 = Encoding.UTF8.GetString(decrypted_bytes2);
using var rsa3 = new RSACryptoServiceProvider();
rsa3.FromXmlString(xml_private_str);
var decrypted_bytes3 = rsa3.Decrypt(encrypted_bytes, false);
var decrypted_str3 = Encoding.UTF8.GetString(decrypted_bytes3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment