RSACryptoServiceProvider类。以下是一个简单的示例代码,演示如何使用C#进行RSA加密和解密:using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
try
{
// 创建RSA加密解密服务提供程序
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// 获取公钥和私钥
string publicKey = rsa.ToXmlString(false); // 获取公钥
string privateKey = rsa.ToXmlString(true); // 获取私钥
// 显示公钥和私钥(通常私钥需要保密)
Console.WriteLine("Public Key:");
Console.WriteLine(publicKey);
Console.WriteLine("Private Key:");
Console.WriteLine(privateKey);
// 要加密的数据
string originalData = "Hello, RSA Encryption and Decryption!";
// 使用公钥进行加密
byte[] encryptedData = Encrypt(publicKey, originalData);
Console.WriteLine("Encrypted Data:");
Console.WriteLine(Convert.ToBase64String(encryptedData));
// 使用私钥进行解密
string decryptedData = Decrypt(privateKey, encryptedData);
Console.WriteLine("Decrypted Data:");
Console.WriteLine(decryptedData);
}
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
}
// 使用公钥加密数据
static byte[] Encrypt(string publicKey, string data)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicKey);
byte[] dataBytes = Encoding.UTF8.GetBytes(data);
byte[] encryptedData = rsa.Encrypt(dataBytes, false);
return encryptedData;
}
}
// 使用私钥解密数据
static string Decrypt(string privateKey, byte[] encryptedData)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(privateKey);
byte[] decryptedDataBytes = rsa.Decrypt(encryptedData, false);
string decryptedData = Encoding.UTF8.GetString(decryptedDataBytes);
return decryptedData;
}
}
}
在这个示例中,我们创建了一个RSACryptoServiceProvider,生成了公钥和私钥,并使用公钥加密数据,然后使用私钥解密数据。请注意,RSA加密和解密使用不同的密钥,因此需要分别获取公钥和私钥。此示例将数据转换为字节数组以进行加密和解密,然后将结果显示在控制台上。
请注意,这只是一个简单的示例,实际应用中可能需要更复杂的密钥管理和数据保护机制。此外,为了提高安全性,通常建议使用更长的RSA密钥。
using System;
using System.Security.Cryptography;
using System.Text;
class Program
{
static void Main()
{
// 创建RSA实例
using (RSA rsa = RSA.Create())
{
// 加载私钥
rsa.FromXmlString("<私钥>");
// 要签名的数据
string data = "要签名的数据";
// 使用SHA256计算数据的哈希值
byte[] hash = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(data));
// 对哈希值进行RSA签名
byte[] signature = rsa.SignHash(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// 将签名转换为Base64字符串输出
Console.WriteLine("签名结果: " + Convert.ToBase64String(signature));
// 加载公钥
rsa.FromXmlString("<公钥>");
// 使用SHA256计算要验签的数据的哈希值
byte[] hashToVerify = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(data));
// 使用公钥进行验签
bool verified = rsa.VerifyHash(hashToVerify, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
if (verified)
{
Console.WriteLine("验签成功");
}
else
{
Console.WriteLine("验签失败");
}
}
}
}
注意,你需要将<私钥>和<公钥>替换为你实际使用的RSA密钥的值。此外,你也可以根据需要修改哈希算法和签名填充方式。