using System;
using System.Security.Cryptography;
using System.Text;
public class RsaExample
{
public static void Main()
{
// 创建 RSA 加密服务提供程序实例
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
// 生成公钥和私钥
string publicKey = rsa.ToXmlString(false); // 只导出公钥
string privateKey = rsa.ToXmlString(true); // 导出公钥和私钥
Console.WriteLine("Public Key: " + publicKey);
Console.WriteLine("Private Key: " + privateKey);
// 要加密的字符串
string originalData = "Hello, World!";
Console.WriteLine("Original Data: " + originalData);
// 将字符串转换为字节数组
byte[] dataToEncrypt = Encoding.UTF8.GetBytes(originalData);
// 使用公钥加密数据
byte[] encryptedData = rsa.Encrypt(dataToEncrypt, false);
Console.WriteLine("Encrypted Data: " + Convert.ToBase64String(encryptedData));
// 使用私钥解密数据
byte[] decryptedData = rsa.Decrypt(encryptedData, false);
string decryptedString = Encoding.UTF8.GetString(decryptedData);
Console.WriteLine("Decrypted Data: " + decryptedString);
}
}
}
RSACryptoServiceProvider 类创建一个 RSA 加密服务提供程序实例。ToXmlString 方法生成公钥和私钥。false 参数表示只导出公钥,true 表示导出公钥和私钥。这个示例展示了如何在 C# 中使用 RSA 算法进行简单的加密和解密操作。
上一篇:c# post请求
下一篇:c# dictionary 遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站