RSA加密与解密
参考:https://blog.csdn.net/weixin_33830216/article/details/85982029
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography;
namespace testApp
{
class Program
{
static void Main(string[] args)
{
var rsa = new RSACryptoServiceProvider();
//生成公钥和私钥
var privateKey = rsa.ToXmlString(true);
var publicKey = rsa.ToXmlString(false);
Console.WriteLine(privateKey);
Console.WriteLine(publicKey);
//公钥加密数据
var rsa1 = new RSACryptoServiceProvider();
var msg = Encoding.UTF8.GetBytes("hello ssdfsdffdf...");
rsa1.FromXmlString(publicKey);
var outputData = rsa1.Encrypt(msg, false);
Console.WriteLine("加密后的数据:"+ Encoding.UTF8.GetString(outputData));
//私钥解密数据
var rsa2 = new RSACryptoServiceProvider();
rsa2.FromXmlString(privateKey);
var inputData = rsa2.Decrypt(outputData, false);
Console.WriteLine("解密后的数据:" + Encoding.UTF8.GetString(inputData));
//基于RSA的签名与验签
var rsa4 = new RSACryptoServiceProvider();
rsa4.FromXmlString(publicKey);
var signData = rsa4.SignData(msg, "SHA1");
var rsa5 = new RSACryptoServiceProvider();
rsa5.FromXmlString(privateKey);
bool isOk = rsa5.VerifyData(msg, "SHA1", signData);
Console.WriteLine("验签结果:"+ isOk);
Console.ReadKey();
}
}
}