using System;
using System.Security.Cryptography;
using System.Text;
namespace RASEncryption
{
class Program
{
static void Main(string[] args)
{
// 创建一个RAS对象
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
// 生成一对公钥和私钥
string publicKey = rsa.ToXmlString(false);
string privateKey = rsa.ToXmlString(true);
// 显示公钥和私钥
Console.WriteLine("Public Key: \n" + publicKey);
Console.WriteLine("Private Key: \n" + privateKey);
// 输入要加密的数据
Console.WriteLine("Enter the data to encrypt:");
string data = Console.ReadLine();
// 将数据转换为字节数组
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
// 获取模块长度
int modulusLength = rsa.KeySize / 8;
// 创建一个存储加密后的数据的字节数组
byte[] encryptedData = new byte[dataBytes.Length];
// 分段加密数据
for (int i = 0; i < dataBytes.Length; i += modulusLength)
{
// 获取当前片段的长度
int segmentLength = Math.Min(modulusLength, dataBytes.Length - i);
// 获取当前片段的字节数组
byte[] segmentBytes = new byte[segmentLength];
Array.Copy(dataBytes, i, segmentBytes, 0, segmentLength);
// 用公钥加密当前片段
byte[] encryptedSegment = rsa.Encrypt(segmentBytes, false);
// 将加密后的片段复制到加密后的数据的字节数组中
Array.Copy(encryptedSegment, 0, encryptedData, i, encryptedSegment.Length);
}
// 将加密后的数据转换为十六进制字符串
string encryptedDataHex = BitConverter.ToString(encryptedData).Replace("-", "");
// 显示加密后的数据
Console.WriteLine("Encrypted Data: \n" + encryptedDataHex);
}
}
}