using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Web;
using System.IO;
/// <summary>
/// Summary description for RSAEncrption
/// </summary>
public class RSAEncrption
{
public RSAEncrption()
{
//
// TODO: Add constructor logic here
//
}
/// <summary>
/// 生成XML格式公钥与私钥
/// </summary>
/// <param name="privateKeyPath"></param>
/// <param name="publicKeyPath"></param>
public static void RSAKey(string privateXmlKeyPath, string publicXmlKeyPath)
{
RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider();
//only public key
SaveKey(privateXmlKeyPath, rsaProvider.ToXmlString(false));
//public and private key
SaveKey(publicXmlKeyPath, rsaProvider.ToXmlString(true));
}
/// <summary>
/// 保存XML格式公钥与私钥
/// </summary>
/// <param name="path"></param>
/// <param name="key"></param>
private static void SaveKey(string path, string key)
{
//create a file, if the file already exists, it will be overwritten.
using (FileStream filestream = new FileStream(path, FileMode.Create))
{
using (StreamWriter sw = new StreamWriter(filestream))
{
sw.Write(key);
}
}
}
/// <summary>
/// UnicodeEncoding编码进行RSA加密
/// </summary>
/// <param name="content">待加密数据</param>
/// <param name="publicXmlKey">XML格式公钥</param>
/// <returns></returns>
public static string RSAEncrypt(string content, string publicXmlKey)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.FromXmlString(publicXmlKey);
System.Text.UnicodeEncoding unicode = new System.Text.UnicodeEncoding();
byte[] data = unicode.GetBytes(content);
byte[] encryptedData = rsa.Encrypt(data, false);
return Convert.ToBase64String(encryptedData);
}
}
/// <summary>
/// UnicodeEncoding编码进行RSA解密
/// </summary>
/// <param name="content">待解密数据</param>
/// <param name="privateXmlKey">XML格式私钥</param>
/// <returns></returns>
public static string RSADecrypt(string content, string privateXmlKey)
{
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
byte[] encryptedData = Convert.FromBase64String(content);
rsa.FromXmlString(privateXmlKey);
byte[] data = rsa.Decrypt(encryptedData, false);
System.Text.UnicodeEncoding unicode = new System.Text.Uni
RSA 加密算法(.NET)
最新推荐文章于 2024-06-25 17:07:30 发布
本文深入探讨了RSA加密算法,详细介绍了如何在.NET环境中实现私钥和公钥的转换,包括对象类的使用,帮助开发者更好地理解和运用RSA加密技术进行数据保护。
摘要由CSDN通过智能技术生成