RSA
在项目中经常会使用到一些加密场合,恰好最近有用到RSA加密解密算法,以此篇文章记录一下。
RSA加密是一种非对称加密。可以在不直接传递密钥的情况下,完成解密。这能够确保信息的安全性,避免了直接传递密钥所造成的被破解的风险。是由一对密钥来进行加解密的过程,分别称为公钥和私钥。两者之间有数学相关,该加密算法的原理就是对一极大整数做因数分解的困难性来保证安全性。通常个人保存私钥,公钥是公开的(可能同时多人持有)。
.net实现RSA加密解密算法需要引用System.Security.Cryptography程序集。通过RSACryptoServiceProvider方法来实现操作。
一、生成密钥

公钥文件

/// <summary>
///在给定路径中生成XML格式的私钥和公钥。
/// </summary>
public void GenerateKeys(string path)
{
using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
{
try
{
// 获取私钥和公钥。
var publicKey = rsa.ToXmlString(false);
var privateKey = rsa.ToXmlString(true);
// 保存到磁盘
File.WriteAllText(Path.Combine(path, publicKeyFileName), publicKey);
File.WriteAllText(Path.Combine(path, privateKeyFileName), privateKey);
MessageBox.Show(string.Format("生成的RSA密钥的路径: {0}\\ [{1}, {2}]", path, publicKeyFileName, privateKeyFileName));
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
二、加密解密
1.加密

/// <summary>
/// 用给定路径的RSA公钥文件加密纯文本。
/// </summary>
/// <param name="plainText">要加密的文本</param>
/// <param name="pathToPublicKey">用于加密的公钥路径.</param>
/// <returns>表示加密数据的64位编码字符串.</returns>
public string Encrypt(string plainText, string pathToPublicKey)
{
using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
{
try
{
//加载公钥
var publicXmlKey = File.ReadAllText(pathToPublicKey);
rsa.FromXmlString(publicXmlKey);
var bytesToEncrypt = System.Text.Encoding.Unicode.GetBytes(plainText);
var bytesEncrypted = rsa.Encrypt(bytesToEncrypt, false);
return Convert.ToBase64String(bytesEncrypted);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
2.解密

/// <summary>
/// Decrypts encrypted text given a RSA private key file path.给定路径的RSA私钥文件解密 加密文本
/// </summary>
/// <param name="encryptedText">加密的密文</param>
/// <param name="pathToPrivateKey">用于加密的私钥路径.</param>
/// <returns>未加密数据的字符串</returns>
public string Decrypt(string encryptedText, string pathToPrivateKey)
{
using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
{
try
{
var privateXmlKey = File.ReadAllText(pathToPrivateKey);
rsa.FromXmlString(privateXmlKey);
var bytesEncrypted = Convert.FromBase64String(encryptedText);
var bytesPlainText = rsa.Decrypt(bytesEncrypted, false);
return System.Text.Encoding.Unicode.GetString(bytesPlainText);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
完整代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace RSA
{
public partial class Form1 : Form
{
//声明存放公钥私钥的位置
private const int RsaKeySize = 2048;
private const string publicKeyFileName = "PublicKey.txt";
private const string privateKeyFileName = "PrivateKey.txt";
private string basePathToStoreKeys = @"E:/test/RSA";
public Form1()
{
InitializeComponent();
}
//生成密钥
private void button1_Click_1(object sender, EventArgs e)
{
GenerateKeys(basePathToStoreKeys);
}
//加密文本框内容
private void button2_Click_1(object sender, EventArgs e)
{
var encryptedString = Encrypt(textBox1.Text, Path.Combine(basePathToStoreKeys, publicKeyFileName));
textBox2.Text = encryptedString;
}
//解密文本框内容
private void button3_Click_1(object sender, EventArgs e)
{
var decryptedString = Decrypt(textBox2.Text, Path.Combine(basePathToStoreKeys, privateKeyFileName));
textBox2.Text = decryptedString;
}
/// <summary>
///在给定路径中生成XML格式的私钥和公钥。
/// </summary>
public void GenerateKeys(string path)
{
using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
{
try
{
// 获取私钥和公钥。
var publicKey = rsa.ToXmlString(false);
var privateKey = rsa.ToXmlString(true);
// 保存到磁盘
File.WriteAllText(Path.Combine(path, publicKeyFileName), publicKey);
File.WriteAllText(Path.Combine(path, privateKeyFileName), privateKey);
MessageBox.Show(string.Format("生成的RSA密钥的路径: {0}\\ [{1}, {2}]", path, publicKeyFileName, privateKeyFileName));
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
/// <summary>
/// 用给定路径的RSA公钥文件加密纯文本。
/// </summary>
/// <param name="plainText">要加密的文本</param>
/// <param name="pathToPublicKey">用于加密的公钥路径.</param>
/// <returns>表示加密数据的64位编码字符串.</returns>
public string Encrypt(string plainText, string pathToPublicKey)
{
using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
{
try
{
//加载公钥
var publicXmlKey = File.ReadAllText(pathToPublicKey);
rsa.FromXmlString(publicXmlKey);
var bytesToEncrypt = System.Text.Encoding.Unicode.GetBytes(plainText);
var bytesEncrypted = rsa.Encrypt(bytesToEncrypt, false);
return Convert.ToBase64String(bytesEncrypted);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
/// <summary>
/// Decrypts encrypted text given a RSA private key file path.给定路径的RSA私钥文件解密 加密文本
/// </summary>
/// <param name="encryptedText">加密的密文</param>
/// <param name="pathToPrivateKey">用于加密的私钥路径.</param>
/// <returns>未加密数据的字符串</returns>
public string Decrypt(string encryptedText, string pathToPrivateKey)
{
using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
{
try
{
var privateXmlKey = File.ReadAllText(pathToPrivateKey);
rsa.FromXmlString(privateXmlKey);
var bytesEncrypted = Convert.FromBase64String(encryptedText);
var bytesPlainText = rsa.Decrypt(bytesEncrypted, false);
return System.Text.Encoding.Unicode.GetString(bytesPlainText);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
.NET RSA加密解密实战
本文介绍了.NET中使用RSA加密解密的方法,包括如何生成密钥对,详细讲解了加密和解密的步骤,适用于保障信息安全的场景。通过引用System.Security.Cryptography程序集,利用RSACryptoServiceProvider进行操作。
872

被折叠的 条评论
为什么被折叠?



